I have the following function which does fine at converting current time to UTC time.
Function toUtc(byVal dDate)
Dim oShell : Set oShell = CreateObject("WScript.Shell")
toUtc = dateadd("n", oShell.RegRead("HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias"), cDate(dDate))
End Function
However, I am thinking that this does not adequately handle conversion of future or historical dates to UTC, since the function would need to know the offset of the server's timezone at the time of the date that is being converted, and whether or not it was during daylight savings time or not.
How can I get around this?
I am using vbScript/Classic ASP on windows server with IIS7.5
To clarify, this has nothing to do with formatting the date. It is all about converting to UTC from the server timezone for historical dates. During Daylight savings time, the offset will be off by 60 minutes if I try to convert a datetime which occurred in standard time.
For example:
Lets say that today, 2013-02-19 (non daylight-savings time), I want to covert a timestamp from say, 2008-06-05 (during daylight savings period) from PDT (my server timezone) to UTC. using the method in my function will give me a value which is 60 minutes off from the correct value (because the CURRENT time is PST (not PDT), the offset will be incorrect for that historical date).
In other words, the timezone offset of the input date could be UTC-7 or UTC-8 depending on whether or not DST was observed on that particular date. I need to calculate the correct UTC date for the input date and I need the code to work whether or not DST is observed on current date.
Here is the solution I ended up implementing at the suggestion of #AardVark71.
I put this in my func.asp file:
<script language="javascript" runat="server">
function toUtcString(d) {
var dDate = new Date(d);
return Math.round(dDate.getTime() / 1000);
};
</script>
It outputs a timestamp value. Then from anywhere in the classic asp code, I can do this:
response.Write DateAdd("s", toUtcString(cDate("11/11/2012 06:25 PM")), "01/01/1970 00:00:00") 'expect 11/11/2012 10:25:00 PM gmt/utc time
response.Write DateAdd("s", toUtcString(cDate("06/11/2012 06:25 PM")), "01/01/1970 00:00:00") 'expect 6/11/2012 9:25:00 PM gmt/utc time
This (I believe) is simple, and it produces the expected values and fully factors in the DST.
In ASP classic you can mix VBScript and JScript code inside one page. The JScript Date object could be used for local ⇄ UTC date conversion. Complete example:
<%# language="vbscript" %>
<%
Option Explicit
Dim local_date
Dim utc_date
For Each local_date In Array("11/11/2012 06:25 PM", "06/11/2012 06:25 PM")
utc_date = local_to_utc(local_date)
Response.Write "Local: " & local_date & ", UTC: " & utc_date & vbNewLine
Next
For Each utc_date In Array("2012-11-12T02:25:00Z", "2012-06-12T01:25:00+00:00")
local_date = utc_to_local(utc_date)
Response.Write "UTC: " & utc_date & ", Local: " & local_date & vbNewLine
Next
%>
<script language="jscript" runat="server">
function local_to_utc(datestr) {
// note that this function lets JScript engine parse the date, correctly or otherwise
var date = new Date(datestr);
var result = date.getUTCFullYear() + "-" + (date.getUTCMonth() + 1) + "-" + date.getUTCDate() + "T" + date.getUTCHours() + ":" + date.getUTCMinutes() + ":" + date.getUTCSeconds();
return result.replace(/(\D)(\d)(?!\d)/g, "$10$2") + "Z";
}
function utc_to_local(datestr) {
// note that this function parses only a subset of ISO 8601 date format
var match = datestr.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?(?:Z|([-+])(\d{2}):(\d{2}))$/);
var offset = match[8] ? (match[8] === "+" ? 1 : -1) * (match[9] * 60 + match[10] * 1) : 0;
var date = new Date(Date.UTC(match[1], match[2] - 1, match[3], match[4], match[5] - offset, match[6], match[7] || 0));
var result = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
return result.replace(/(\D)(\d)(?!\d)/g, "$10$2");
}
</script>
Expected result:
Nov 11 2012 18:25 PST = Nov 12 2012 02:25 UTC
Jun 11 2012 18:25 PDT = Jun 12 2012 01:25 UTC
And the output when executed on a server using PST/PDT time:
Local: 11/11/2012 06:25 PM, UTC: 2012-11-12T02:25:00Z
Local: 06/11/2012 06:25 PM, UTC: 2012-06-12T01:25:00Z
UTC: 2012-11-12T02:25:00Z, Local: 2012-11-11 18:25:00
UTC: 2012-06-12T01:25:00+00:00, Local: 2012-06-11 18:25:00
If I not miss something, you need to get local time on remote machine and it time zone offset, right?
Here I see self-answer based on WMI Win32_TimeZone Bias property. But according to this MSDN example: "Converting Local Time to UTC Time", quote:
Use Win32_ComputerSystem CurrentTimeZone property, because it
automatically adjusts the Time Zone bias for daylight saving time
Win32_TimeZone Bias property does not.
So, next example function get current date time, and I'll leave to you to modify it for concrete date time measuring.
' "." mean local computer
WScript.Echo FormatDateTime(UTCDate("."), 0)
Function UTCDate(strComputer)
Dim objWMIService, ColDate, ColCS
On Error Resume Next
Set objWMIService = _
GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set ColDate = objWMIService.ExecQuery("Select * From Win32_LocalTime")
UTCDate = DateSerial(100, 1, 1)
For Each objDate In ColDate
UTCDate = DateAdd("yyyy", ObjDate.Year - 100, UTCDate)
UTCDate = DateAdd("m", ObjDate.Month - 1, UTCDate)
UTCDate = DateAdd("d", ObjDate.Day - 1, UTCDate)
UTCDate = DateAdd("h", ObjDate.Hour, UTCDate)
UTCDate = DateAdd("n", ObjDate.Minute, UTCDate)
UTCDate = DateAdd("s", ObjDate.Second, UTCDate)
Next
' http://msdn.microsoft.com/en-us/library/windows/desktop/ms696015(v=vs.85).aspx
Set ColCS = objWMIService.ExecQuery("Select * From Win32_ComputerSystem")
Dim TimeZoneOffset, LocalTimeZone
For Each LocalTimeZone In ColCS
TimeZoneOffset = LocalTimeZone.CurrentTimeZone
Next
If TimeZoneOffset < 0 Then
TimeZoneOffset = Abs(TimeZoneOffset)
Else
TimeZoneOffset = -Abs(TimeZoneOffset)
End If
UTCDate = DateAdd("n", TimeZoneOffset, UTCDate)
If Err Then UTCDate = vbNull
Set objWMIService = Nothing
End Function
[EDIT] Well, looks like should not trust on MSDN then (or maybe this work only for current time). However, I see it's not the answer you looking for. If you not find better idea, you may automate this online calculator.
P.S. Ok, strike out above code and lets try another "iteration".
Just to note that I made a code compatible with my time zone (Bulgaria), where PDT start at last Sunday of March and end at last Sunday of October. This allow me to set easy my PDT range. Shortly, the idea is to make algorithm applicable to your region. The rest is clearly, I hope.
With New DateDrill
Debug.WriteLine .UTCDate("2008-6-28")
Debug.WriteLine .UTCDate("2014-1-21")
End With
Class DateDrill
Public Function UTCDate(ByVal dtDate)
If Not IsDate(dtDate) Then Err.Raise 5
dtDate = CDate(dtDate)
Dim ZoneBias: ZoneBias = TimeZoneBias()
If IsPDT(Now) <> IsPDT(dtDate) Then
ZoneBias = ZoneBias - 60
End If
UTCDate = DateAdd("n", ZoneBias, dtDate)
End Function
Private Function IsPDT(ByVal dtDate)
If Not IsDate(dtDate) Then Err.Raise 5
dtDate = CDate(dtDate)
Dim pdtLow, pdtUpr, nDaysBack
pdtLow = DateSerial(Year(dtDate), 3, 31)
pdtUpr = DateSerial(Year(dtDate), 10, 31)
pdtLow = DateAdd("h", 2, pdtLow)
pdtUpr = DateAdd("h", 2, pdtUpr)
nDaysBack = Weekday(pdtLow) - 1
If nDaysBack <> 0 Then
pdtLow = DateAdd("d", -nDaysBack, pdtLow)
End If
nDaysBack = Weekday(pdtUpr) - 1
If nDaysBack <> 0 Then
pdtUpr = DateAdd("d", -nDaysBack, pdtUpr)
End If
IsPDT = (dtDate >= pdtLow And dtDate <= pdtUpr)
End Function
Private Function TimeZoneBias()
Dim LTZone
With GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\.\root\cimv2")
For Each LTZone In .ExecQuery(_
"Select * From Win32_ComputerSystem")
TimeZoneBias = LTZone.CurrentTimeZone
Next
End With
TimeZoneBias = TimeZoneBias * -1
End Function
End Class
This little collection of ASP VBScript functions may do what you need. I'm drawing a Unix Timestamp from a MySQL database. Depending on you database it may be a slightly different query, but most DBs can return a Unix Timestamp. On my server the query only takes one or two milliseconds.
Note: pquery is my own function for running SQL queries. Obviously substitute in your own method.
I'm calculating the offset each time unixTime() runs. You could of course calculate it once in a "bootstrap" file and set a global variable if you prefer.
Function unixTimestamp()
' Unix Timestamp, drawn from MySQL because ASP doesn't natively handle time zones
rs = pquery( "SELECT unix_timestamp() AS `ts`", null )
unixTimestamp = cLng( rs("ts") )
End Function
Function utc_offset()
' Offset of Server time from UTC, in seconds
dim unixNow : unixNow = unixTimestamp()
dim aspNow : aspNow = cLng( DateDiff( "s", "01/01/1970 00:00:00", now() ) )
utc_offset = cLng( ( aspNow - unixNow ))
End Function
Function unixTime( byVal dt )
dim offset : offset = utc_offset()
if( VarType( dt ) = vbDate ) then
unixTime = cLng( DateDiff( "s", "01/01/1970 00:00:00", dt ) - offset )
else
if( isDate( dt ) ) then
dt = cDate( dt )
unixTime = cLng( DateDiff( "s", "01/01/1970 00:00:00", dt ) - offset )
else
unixTime = null
end if
end if
End Function
Function datetimeFromUnix( byVal udt, offset )
datetimeFromUnix = cDate( DateAdd( "s", udt + offset , "01/01/1970 00:00:00" ) )
End Function
Now run:
utcTimestamp = unixTime( dDate )
utcDate = datetimeFromUnix( utcTimestamp, 0 ) ' UTC
localDate = datetimeFromUnix( utcTimestamp, utc_offset() ) ' back where we started
Related
I am newish to MS Access.
I require the equivalent formula from excel to mc access which will workout -1 day from my data-set less weekends/public holidays.
So this is what i use in excel atm: =WORKDAY(start date,days,[holidays])
Any help would be greatly appreciated.
There is no native function, but you can use this set of functions:
Option Explicit
' Common constants.
' Date.
Public Const DaysPerWeek As Long = 7
Public Const MaxDateValue As Date = #12/31/9999#
Public Const MinDateValue As Date = #1/1/100#
' Workdays per week.
Public Const WorkDaysPerWeek As Long = 5
' Average count of holidays per week maximum.
Public Const HolidaysPerWeek As Long = 1
' Adds Number of full workdays to Date1 and returns the found date.
' Number can be positive, zero, or negative.
' Optionally, if WorkOnHolidays is True, holidays are counted as workdays.
'
' For excessive parameters that would return dates outside the range
' of Date, either 100-01-01 or 9999-12-31 is returned.
'
' Will add 500 workdays in about 0.01 second.
'
' Requires table Holiday with list of holidays.
'
' 2015-12-19. Gustav Brock. Cactus Data ApS, CPH.
'
Public Function DateAddWorkdays( _
ByVal Number As Long, _
ByVal Date1 As Date, _
Optional ByVal WorkOnHolidays As Boolean) _
As Date
Const Interval As String = "d"
Dim Holidays() As Date
Dim Days As Long
Dim DayDiff As Long
Dim MaxDayDiff As Long
Dim Sign As Long
Dim Date2 As Date
Dim NextDate As Date
Dim DateLimit As Date
Dim HolidayId As Long
Sign = Sgn(Number)
NextDate = Date1
If Sign <> 0 Then
If WorkOnHolidays = True Then
' Holidays are workdays.
Else
' Retrieve array with holidays between Date1 and Date1 + MaxDayDiff.
' Calculate the maximum calendar days per workweek.
MaxDayDiff = Number * DaysPerWeek / (WorkDaysPerWeek - HolidaysPerWeek)
' Add one week to cover cases where a week contains multiple holidays.
MaxDayDiff = MaxDayDiff + Sgn(MaxDayDiff) * DaysPerWeek
If Sign > 0 Then
If DateDiff(Interval, Date1, MaxDateValue) < MaxDayDiff Then
MaxDayDiff = DateDiff(Interval, Date1, MaxDateValue)
End If
Else
If DateDiff(Interval, Date1, MinDateValue) > MaxDayDiff Then
MaxDayDiff = DateDiff(Interval, Date1, MinDateValue)
End If
End If
Date2 = DateAdd(Interval, MaxDayDiff, Date1)
' Retrive array with holidays.
Holidays = GetHolidays(Date1, Date2)
End If
Do Until Days = Number
If Sign = 1 Then
DateLimit = MaxDateValue
Else
DateLimit = MinDateValue
End If
If DateDiff(Interval, DateAdd(Interval, DayDiff, Date1), DateLimit) = 0 Then
' Limit of date range has been reached.
Exit Do
End If
DayDiff = DayDiff + Sign
NextDate = DateAdd(Interval, DayDiff, Date1)
Select Case Weekday(NextDate)
Case vbSaturday, vbSunday
' Skip weekend.
Case Else
' Check for holidays to skip.
' Ignore error when using LBound and UBound on an unassigned array.
On Error Resume Next
For HolidayId = LBound(Holidays) To UBound(Holidays)
If Err.Number > 0 Then
' No holidays between Date1 and Date2.
ElseIf DateDiff(Interval, NextDate, Holidays(HolidayId)) = 0 Then
' This NextDate hits a holiday.
' Subtract one day before adding one after the loop.
Days = Days - Sign
Exit For
End If
Next
On Error GoTo 0
Days = Days + Sign
End Select
Loop
End If
DateAddWorkdays = NextDate
End Function
' Returns the holidays between Date1 and Date2.
' The holidays are returned as a recordset with the
' dates ordered ascending, optionally descending.
'
' Requires table Holiday with list of holidays.
'
' 2015-12-18. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DatesHoliday( _
ByVal Date1 As Date, _
ByVal Date2 As Date, _
Optional ByVal ReverseOrder As Boolean) _
As DAO.Recordset
' The table that holds the holidays.
Const Table As String = "Holiday"
' The field of the table that holds the dates of the holidays.
Const Field As String = "Date"
Dim rs As DAO.Recordset
Dim SQL As String
Dim SqlDate1 As String
Dim SqlDate2 As String
Dim Order As String
SqlDate1 = Format(Date1, "\#yyyy\/mm\/dd\#")
SqlDate2 = Format(Date2, "\#yyyy\/mm\/dd\#")
ReverseOrder = ReverseOrder Xor (DateDiff("d", Date1, Date2) < 0)
Order = IIf(ReverseOrder, "Desc", "Asc")
SQL = "Select " & Field & " From " & Table & " " & _
"Where " & Field & " Between " & SqlDate1 & " And " & SqlDate2 & " " & _
"Order By 1 " & Order
Set rs = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)
Set DatesHoliday = rs
End Function
' Returns the holidays between Date1 and Date2.
' The holidays are returned as an array with the
' dates ordered ascending, optionally descending.
'
' The array is declared static to speed up
' repeated calls with identical date parameters.
'
' Requires table Holiday with list of holidays.
'
' 2015-12-18. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function GetHolidays( _
ByVal Date1 As Date, _
ByVal Date2 As Date, _
Optional ByVal OrderDesc As Boolean) _
As Date()
' Constants for the arrays.
Const DimRecordCount As Long = 2
Const DimFieldOne As Long = 0
Static Date1Last As Date
Static Date2Last As Date
Static OrderLast As Boolean
Static DayRows As Variant
Static Days As Long
Dim rs As DAO.Recordset
' Cannot be declared Static.
Dim Holidays() As Date
If DateDiff("d", Date1, Date1Last) <> 0 Or _
DateDiff("d", Date2, Date2Last) <> 0 Or _
OrderDesc <> OrderLast Then
' Retrieve new range of holidays.
Set rs = DatesHoliday(Date1, Date2, OrderDesc)
' Save the current set of date parameters.
Date1Last = Date1
Date2Last = Date2
OrderLast = OrderDesc
Days = rs.RecordCount
If Days > 0 Then
' As repeated calls may happen, do a movefirst.
rs.MoveFirst
DayRows = rs.GetRows(Days)
' rs is now positioned at the last record.
End If
rs.Close
End If
If Days = 0 Then
' Leave Holidays() as an unassigned array.
Erase Holidays
Else
' Fill array to return.
ReDim Holidays(Days - 1)
For Days = LBound(DayRows, DimRecordCount) To UBound(DayRows, DimRecordCount)
Holidays(Days) = DayRows(DimFieldOne, Days)
Next
End If
Set rs = Nothing
GetHolidays = Holidays()
End Function
Does anyone know if there's an actual equivalent method in VB6 for .NET's DateTime.ParseExact() method? I've tried using DateSerial(), IsDate() and CDate(), but, due to all of VB6's "helpfulness", I'm coming up with some unexpected results.
To be more specific, I'm trying to parse a text string from user input to validate whether or not it's an actual date. As an example, I'll be using the date 8/25/16. The usual expected input may or may not have delimiters between the month, day and year, so it may be entered as 82516.
Here's a sample of the code that's not working as intended (the value of 82516 is stored in the TempStr variable):
If IsDate(Format(TempStr, "#/##/##")) And IsDate(Format(TempStr, "##/#/##")) Then
TempDate = #12:00:00 AM#
ElseIf IsDate(Format(TempStr, "#/##/##")) Then
TempDate = CDate(Format(Tempstr, "#/##/##"))
ElseIf IsDate(Format(TempStr, "##/#/##")) Then
TempDate = CDate(Format(TempStr, "##/#/##"))
End If
Using the stated value, the first condition triggers. Knowing how it works, I understand why it's happening (it's "rearranging" the month, day and year to try to match a valid date), but I'm really trying to get it to parse the date in a specific order. I know that .NET's DateTime.ParseExact() method would get me there, but I have to do this in VB6 (maintaining some legacy code).
I tried using DateSerial():
If DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 1)), CInt(Mid(TempStr, 2, 2))) > #12:00:00 AM# Then
If DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 2)), CInt(Mid(TempStr, 3, 1))) > #12:00:00 AM# Then
TempDate = #12:00:00 AM#
Else
TempDate = DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 1)), CInt(Mid(TempStr, 2, 2)))
End If
Else
If DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 2)), CInt(Mid(TempStr, 3, 1))) > #12:00:00 AM# Then
TempDate = DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 2)), CInt(Mid(TempStr, 3, 1)))
Else
TempDate = #12:00:00 AM#
End If
End If
But that also comes along with an automatic correction if the values for any of the parameters fall outside of the acceptable ranges.
I also tried the following variation of the above code:
If IsDate(Format(TempStr, "m/dd/yy")) And IsDate(Format(TempStr, "mm/d/yy")) Then
...
But the first test results in an entirely different value of 3/12/26, which is WAY off from the original input.
Is there any way to accurately emulate the .NET DateTime.ParseExact() method in VB6, or am I just going to have to toss these types of user input values out as invalid/ambiguous?
I will personally write a function for ensuring the correct date is returned -
First get the string/integer, break it down into chunks and add values to those chunks and return a combined date...
Option Explicit
Public Function MakeCorrectDate()
Dim xMakeDate As Long, xDay As Integer, xMonth As Integer, xYear As Integer, xCentury As Integer, strCorrectDate As String
''xMake as long because of size, strCorrectDate as string to allow the /...
xMakeDate = txtInput.Text
''Assuming the format will ALWAYS be the same days, months and year (12/20/16) and length is ALWAYS 6...
xDay = Left$(xMakeDate, 2)
xMonth = Mid$(xMakeDate, 3, 2)
xYear = Right(xMakeDate, 2)
''First get the correct part to 1900 or 2000...
If xYear = "00" Then
xCentury = 20
ElseIf xYear < 99 And xYear > 20 Then ''Year 2000 and year 2020
xCentury = 19
Else
xCentury = 20
End If
strCorrectDate = xDay & "/" & xMonth & "/" & xCentury & xYear
txtYear.Text = strCorrectDate
End Function
Private Sub cmdGetCorrectDate_Click()
If Not Len(txtInput.Text) = 6 Then
MsgBox "Incorrect information, must be 6 or more characters."
Exit Sub
Else
Call MakeCorrectDate
End If
End Sub
Private Sub txtInput_Change()
''Ensure the user adds only numerical text...
Dim WshShell As Object
Set WshShell = CreateObject("WScript.Shell")
If Not IsNumeric(txtInput.Text) Then
WshShell.SendKeys "{BackSpace}"
End If
End Sub
Okay, so here's what I've come up with as a solution for my current needs. Similar to what #Andre-Oosthuizen posted above, I've decided to drastically simplify the validation from what I was doing before. This series of functions requires the user to enter a six-digit date (two-digit month, two-digit day, and two-digit year). I don't believe the century is going to be a factor in this specific application, so I'm going to leave that test out.
This should be acceptable to our users as they've had similar restrictions in other systems. While I'd personally prefer a more "bullet-proof" solution (such as using a DatePicker or other manipulation of the UI), I think this is going to be the most effective for our environment.
'----------------------------------------------------------------------
' LostFocus event handler for the txtEffectiveDate TextBox.
' Test for a valid date when the user attempts to leave the field.
'----------------------------------------------------------------------
Private Sub txtEffectiveDate_LostFocus()
' *********************************************************************
' ** Don't have the event handler try to do any parsing. Just pass **
' ** the .Text value to the validation function. If a date comes **
' ** back, reformat it to "look" like a date and move on. Otherwise **
' ** pop up an "error" message and return focus to the TextBox for **
' ** the user to correct their input. **
' *********************************************************************
Dim TempDate As Date
TempDate = CheckForValidDate(Me.txtEffectiveDate.Text)
If TempDate > #12:00:00 AM# Then
' If a valid Date is returned, put the formatted String value
' into the TextBox and move on.
Me.txtEffectiveDate.Text = Format(TempDate, "mm/dd/yy")
Else
' If the Date value is not valid (#12:00:00 AM#), notify the
' user and refocus on the TextBox to force the user to
' correct the input before continuing.
MsgBox "The date you entered was not valid." & vbCrLf & vbCrLf & _
"Please enter two digits for the month, two digits for the day and" & vbCrLf & _
"two digits for the year." & vbCrLf & vbCrLf & _
"For example, today's date should be entered as either " & Format(Now, "mmddyy") & vbCrLf & _
" or " & Format(Now, "mm/dd/yy") & ".", _
vbOKOnly + vbExclamation, "INVALID INPUT FORMAT"
Me.txtEffectiveDate.SetFocus
Me.txtEffectiveDate.SelStart = 0
Me.txtEffectiveDate.SelLength = Len(Me.txtEffectiveDate.Text)
End If
End Sub
'----------------------------------------------------------------------
' Attempts to convert the String input to a Date value. If the String
' value is already a Date (i.e., "1/1/16" or similar), go ahead and
' assume that the user wants that date and return it as a Date value.
' Otherwise, strip any non-numeric characters and break apart the input
' to pass along for further validation.
'----------------------------------------------------------------------
Private Function CheckForValidDate(ByVal DateStr As String) As Date
Dim TempDate As Date
If IsDate(DateStr) Then
' If the String value is already in a date format,
' just return the Date value of the String.
TempDate = CDate(DateStr)
Else
Dim TempStr As String
Dim CurrentChar As String
Dim TempYear As Integer
Dim TempMonth As Integer
Dim TempDay As Integer
Dim I As Integer
' Strip all non-numeric characters to get a purely numeric string.
For I = 1 To Len(DateStr)
CurrentChar = Mid(DateStr, I, 1)
If IsNumeric(CurrentChar) Then
TempStr = TempStr & CurrentChar
End If
Next I
' The all-numeric string should be exactly six characters
' (for this application).
If Len(Trim(TempStr)) = 6 Then
Dim NewDateStr As String
' Break the numeric string into the component parts -
' Month, Day, and Year. At six characters, there should
' be two characters for each element.
TempMonth = CInt(Left(TempStr, 2))
TempDay = CInt(Mid(TempStr, 3, 2))
TempYear = CInt(Right(TempStr, 2))
' Now pass the individual values to the second part of
' the validation to ensure each of the individual values
' falls within acceptable ranges.
NewDateStr = GetValidDateString(TempMonth, TempDay, TempYear)
' If the returned String value is not empty, then convert
' it to a Date value for returning to the calling method
If Len(Trim(NewDateStr)) > 0 Then
TempDate = CDate(NewDateStr)
End If
End If
End If
CheckForValidDate = TempDate
End Function
'----------------------------------------------------------------------
' Using numeric values for Month, Day, and Year, attempt to build a
' valid Date in mm/dd/yy format.
'----------------------------------------------------------------------
Private Function GetValidDateString(ByVal intMonth As Integer, ByVal intDay As Integer, ByVal intYear As Integer) As String
Dim ReturnStr As String
ReturnStr = ""
If intMonth >= 1 And intMonth <= 12 Then
Select Case intMonth
Case 1, 3, 5, 7, 8, 10, 12
' January, March, May, July, August, October and December
' have 31 days.
If intDay >= 1 And intDay <= 31 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
Case 4, 6, 9, 11
' April, June, September and November
' have 30 days
If intDay >= 1 And intDay <= 30 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
Case 2
' Depending on whether it is a Leap Year (every four years),
' February may have 28 or 29 days.
If intYear Mod 4 = 0 Then
If intDay >= 1 And intDay <= 29 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
Else
If intDay >= 1 And intDay <= 28 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
End If
End Select
End If
' Return the recombined string to the calling function.
GetValidDateString = ReturnStr
End Function
There's still obviously going to be some room for error, but I believe this will solve the issue for now. It's not perfect, but hopefully we'll be able to move away from this VB6 system soon. Thank you for all of the ideas and suggestions. They were very helpful in narrowing down the best solution for this specific implementation.
I have a problem with SQlite for DateTime in UWP-app.
Assume the SQLite DB has the following data:
PurchaseDate (Date in SQLite format)
-----------------------------------
2016-09-10 11:10:10
2016-09-10 11:10:15
2016-09-10 11:10:30
Pass in this Date:
strSQLiteDate ="2016-09-10"
I just want to check if there is any row in the tblPurchase.
There is no match from below SQL-Select. What did I miss? Did I miss the hh:mm:ss part? But I just need to check the yyyy-mm-dd part.
using (var db = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DBPath))
{
var query = db.Query<tblPurchase>("Select * From tblPurchase where PurchaseDate = " + " date('" + strSQliteDate + "')");
intcount = query.Count;
if (intcount != 0)
{
return intcount;
}
}
Edit 1
10/8/2016 10:13:26 AM
The above date will be recreated as DateTime and SQLit.Net-PCL use it to insert into SQLite DB
string[] strAr_Date = strDate.Split('/');
string strYear = strAr_Date[0].ToString();
string strMth = strAr_Date[1].ToString();
string strDay = strAr_Date[2].ToString();
string strDateTime = strDay + "/" + strMth + "/" + strYear + " " + strTime;
DateTime dt = DateTime.Parse(strDateTime);
... where PurchaseDate = date('2016-09-10')
The date() function removes the time portion from a date/time value.
But the value 2016-09-10 does not have a time portion, so it is not changed.
The PurchaseDate values still have the time portion, so you end up with a comparison like this:
... where '2016-09-10 11:10:10' = '2016-09-10'
You have to remove the time from the PurchaseDate values:
... where date(PurchaseDate) = '2016-09-10'
I'm doing the following query to check if the current month is the same as the SQL field "Start".
If Today.Month = CDate(rsData("Start")).Month Then
What I'd like to do is switch it so that it will check within a 30 day period rather than identify the current month? Any ideas on how to do this?
If Date.Today.AddDays(-30) >= CDate(rsData("Start"))
' start date not older than 30 days '
End If
or if you have a variable date:
var minBoundary = New Date(2011,1,1)
var maxBoundary = New Date(2012,1,1)
var startDate = CDate(rsData("Start"))
If startDate >= MinBoundary AndAlso startDate <= maxBoundary
' start date between two dates '
End If
I believe in this case you would want to use the AddDays method of DateTime.
Dim mydate as DateTime = CDate(rsData("Start"))
Dim checkdate as DateTime = mydate.AddDays(30)
I have a dropdownlist that displays time. For example 8:00AM or 8:30AM.
When I save this time to database, I want to save as todays date + time.
eg: 8:00AM as 03/30/2009 8:00:00:000. Can anybody give appropriate code to convert as shown above?
I tried
Convert.ToDateTime(ddlStartTime.SelectedItem.Text)
But there is an error stating "String was not recognized as a valid DateTime."
VB.NET answer for Portmans Solution. Too many chars for comment so included here.
Dim time As String() = Me.DropDownList1.SelectedValue.Split(New Char() {":", " "})
Dim hours As Integer = Integer.Parse(time(0))
Dim minutes As Integer = Integer.Parse(time(1))
Dim ampm As Integer = 12
If time(2).ToLower() = "am" Then
ampm = 0
End If
Dim dt As DateTime = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes)
Have a look at DateTime.TryParse and DateTime.Today. Using them should be enough to do what you want.
Untested Code.
DateTime dt;
if (DateTime.TryParse(Dropdown1.SelectedValue, out dt))
{
DateTime result = DateTime.Today.AddHours(dt.Hour).AddMinutes(dt.Minute);
}
Basically, you just need to parse the time string. It will be automatically resolved to the current date.
Dim strTime As String = "8.30am"
Dim parsedTime As DateTime
If DateTime.TryParseExact(strTime, "h.mmtt", New System.Globalization.DateTimeFormatInfo(), Globalization.DateTimeStyles.None, parsedTime) = True Then
'Parse was successful.
Else
'Handle the error.
End If
Store as the value for each drop down item the number of minutes from midnight that the time represents. Then:-
valueToStore = DateTime.Today + TimeSpan.FromMinutes(Int32.Parse(value))
By storing using the value attribute of a HTML option to store a simple representation of the value you eliminate the codes dependancy on the actual format used to simply display the set of values. If it decided that the representation of the times be changed to use different format the rest of the code will continue to work unmodified.
var time = this.DropDownList1.SelectedValue.Split(':', ' ');
var hours = Int32.Parse(time[0]);
var minutes = Int32.Parse(time[1]);
var ampm = (time[2] == "PM") ? 12 : 0;
var dt = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes);
Parse your DropDownList for Hours and Minutes, then add them to DateTime.Today.
Read the parts of the time so you have hours and minutes, then use the following code:
DateTime myDate = DateTime.Now.Date;
myDate = myDate.AddHours(hours);
myDate = myDate.AddMinutes(minutes);
Use ParseExact so that you can specify the format that you are using.
h = hours in 12-hour clock format
. = literal character
mm = minutes as two digits
tt = AM/PM designator
Dim time As DateTime = DateTime.ParseExact(dropdown.SelectedValue, "h.mmtt", CultureInfo.InvariantCulture)
The components of the DateTime value that you don't specify in the string (year, month, date, seconds, time zone, era) uses DateTime.Today as default, which is exactly what you want in this case.
This always seems to work for me. May not be the most elegant way, but I have not had any issues so far.
dTime = DateTime.Now;
string time = this.DropDownList1.SelectedValue;
DateTime FormattedDateTime = Convert.ToDateTime(dTime.Date.ToShortDateString() +
" " + time);