Date issue in vb script [duplicate] - vbscript

This question already has an answer here:
Format current date and time in VBScript
(1 answer)
Closed 4 years ago.
My issue is when I retrieve date back it gives me in this format:
lastseenstatus=rsprefobj("lastseentstamp")
19-07-2014 15:31:32
I want it in 7/19/2014 3:31:32 PM format with AM/PM intact.
Please help..

First and foremost you need to determine the data type of rsprefobj("lastseentstamp"):
MsgBox TypeName(rsprefobj("lastseentstamp"))
If it's a string, you need to convert it to a datetime value first:
lastseenstatus = CDate(rsprefobj("lastseentstamp"))
If you want the date formatted according to the system's regional settings, use the FormatDateTime() function as #John suggested:
MsgBox FormatDateTime(lastseenstatus)
If you need a distinct date format regardless of the system's regional settings you have to either build the formatted string yourself:
Function LPad(v) : LPad = Right("00" & v, 2) : End Function
Function FormatDate(d)
formattedDate = Month(d) & "/" & LPad(Day(d)) & "/" & Year(d) & " " & _
((Hour(d) + 23) Mod 12 + 1) & ":" & LPad(Minute(d)) & ":" & _
LPad(Second(d))
If Hour(d) < 12 Then
formattedDate = formattedDate & " AM"
Else
formattedDate = formattedDate & " PM"
End If
FormatDate = formattedDate
End Function
MsgBox FormatDate(lastseenstatus)
or use the .Net StringBuilder class:
Set sb = CreateObject("System.Text.StringBuilder")
sb.AppendFormat "{0:M\/dd\/yyyy h:mm:ss tt}", lastseenstatus
MsgBox sb.ToString()
In my tests I wasn't able to get the tt format specifier to work, though, so you may have to resort to something like this:
Set sb = CreateObject("System.Text.StringBuilder")
If Hour(lastseenstatus) < 12 Then
am_pm = "AM"
Else
am_pm = "PM"
End If
sb.AppendFormat_5 Nothing, "{0:M\/dd\/yyyy h:mm:ss} {1}", _
Array(lastseenstatus, am_pm)
MsgBox sb.ToString()

I'm assuming you are using VBScript and not VB.NET like you have tagged.
Use FormatDateTime(lastseenstatus).
That should give you the format "2/16/2010 1:45:00 PM".

Related

Classic ASP / VBSCRIPT 12 Hour Format from FormatDateTime()

I sure would appreciate some help. I was able to hack away at getting my time formatted as 8:53 AM from a value such as this 7/31/2020 08:53:20 AM with the following.
replace(replace(formatdatetime(formatdatetime(myRS("dateTime"),4)),":00 AM"," AM"),":00 PM"," PM")
But I would think there is a more efficient approach no?
<%#LANGUAGE="VBScript"%>
<%
' The actual LCID.
Response.LCID = 2057
Response.CodePage = 65001
Function AM_PM_Time(TheTime, ZeroPad)
Dim actual_LCID, time_formatted, time_split_1, time_split_2
' Make sure the the date or time being passed is valid.
If NOT isDate(TheTime) Then Exit Function
' Make a note of the actual LCID.
actual_LCID = Response.LCID
' Change the LCID to 1033 so time is formatted as 00:00:00 AM/PM.
' If your LCID is already 1033 you can delete the LCID code.
Response.LCID = 1033
' Format the current date / time.
time_formatted = FormatDateTime(TheTime,3)
' Split the time stamp.
time_split_1 = Split(time_formatted,":")
' Split the AM / PM.
time_split_2 = Split(time_formatted," ")
' Revert the LCID back to its original value.
Response.LCID = actual_LCID
' [Optional]
' Zero-pad the first number of the timestamp, for example: "07:45 PM" rather than "7:45 PM"
If ZeroPad Then
If Len(time_split_1(0)) = 1 Then time_split_1(0) = cStr("0" & time_split_1(0))
End If
' Output the newly formatted time.
AM_PM_Time = time_split_1(0) & ":" & time_split_1(1) & " " & time_split_2(1)
End Function
Response.Write AM_PM_Time(Now(),True) & "<br>"
Response.Write AM_PM_Time("2020-08-17 09:00:00",False) & "<br>"
Response.Write AM_PM_Time("14:55:00",True)
%>
Example output:
07:45 PM9:00 AM02:55 PM
Set speech = CreateObject("sapi.spvoice")
Speech.speak "Here's one way it sets the locale to New Zealand which is 12 hours - it does NOT set time zone"
SetLocale("en-nz")
speech.speak now()
speech.speak "Here's another way" 'if locale is 12 hours it does nothing
Do
If Hour(Now) < 12 then
Var = Hour(Now) & " AM"
else
Var = Hour(Now) - 12 & " PM"
End If
speech.Speak Var & " and " & Minute(Now) & " minutes and " & Second(Now) & " seconds"
wscript.sleep 5
Loop
As you can see it speaks the comments.

Format Time up to Milliseconds to use in log files [duplicate]

This question already has answers here:
Find time with millisecond using VBScript
(3 answers)
Closed 5 years ago.
My VBScript has a log file which logs information with current date and time using FormatDateTime Function.
I like to format time up to milliseconds and also in the following format:
MM/DD/YY hh:mm:ss:mss AM/PM
But, unfortunately FormatDateTime doesn't let to format time in this way.
After searching for this, I found this answer and it is about how to use Timer function, So I can't log time to log files using it again and again.
As W3schools states,
The Timer function returns the number of seconds since 12:00 AM.
But I want my log file to log time in above format even before 12:00 AM, So using Timer Function isn't the best option for this.
Please let me know a way to do this specially in log files correctly.
The vbscript function Now() will return the current system date and time in this format - 5/2/2017 9:45:34 AM, however if you need to add milliseconds you can use Timer - Timer math from here
'capture the date and timer together so if the date changes while
'the other code runs the values you are using don't change
t = Timer
dateStr = Date()
temp = Int(t)
milliseconds = Int((t-temp) * 1000)
seconds = temp mod 60
temp = Int(temp/60)
minutes = temp mod 60
hours = Int(temp/60)
label = "AM"
If hours > 12 Then
label = "PM"
hours = hours-12
End If
'format it and add the date
strTime = LeftPad(hours, "0", 2) & ":"
strTime = strTime & LeftPad(minutes, "0", 2) & ":"
strTime = strTime & LeftPad(seconds, "0", 2) & "."
strTime = strTime & LeftPad(milliseconds, "0", 3)
WScript.Echo dateStr & " " & strTime & " " & label
'this function adds characters to a string to meet the desired length
Function LeftPad(str, addThis, howMany)
LeftPad = String(howMany - Len(str), addThis) & str
End Function
Another way to do the same thing, with a bit less code. In this code, we're splitting Now() into an array so we can use it for everything except the milliseconds.:
WScript.Echo PrintTimeStamp()
Function PrintTimeStamp()
nowParts = SPLIT(Now(), " ")
timePart = nowParts(1)
t = Timer
milliseconds = Int((t-Int(t)) * 1000)
PrintTimeStamp = nowParts(0) & " " & LeftPad(nowParts(1), "0", 8) & "." & LeftPad(milliseconds, "0", 3) & " " & nowParts(2)
End Function
Function LeftPad(str, addThis, howMany)
LeftPad = String(howMany - Len(str), addThis) & str
End Function

How to search between dates?

iam using ms access database and i want to get data between two dates
stdate= starting date
edate=end date
iam using the code below.
Private Sub Label3_Click()
DataGrid1.Visible = True
Dim stdate As Date
Dim edate As Date
Format = stdate("mm/dd/yyyy")
Format = edate("mm/dd/yyyy")
stdate = Text1.Text
edate = Text2.Text
Adodc1.RecordSource = "SELECT * FROM sales_info WHERE date BETWEEN &stdate& and &edate& "
Adodc1.Refresh
End Sub
errors iam getting are:
syntax error expected array(in format statement)
missing operator in query expression date.
thanks
plz help
iam a beginner
This code should work-
Private Sub Label3_Click()
DataGrid1.Visible = True
Dim stdate As String
Dim edate As String
stdate = Format(Text1.Text, "mm/dd/yyyy")
edate = Format(Text2.Text, "mm/dd/yyyy")
Adodc1.RecordSource = "SELECT * FROM [sales_info] WHERE [date] BETWEEN #" & stdate & " and " & edate & "]"
Adodc1.Refresh
End Sub
I also agree with #Joe in that you should not use date for your column name as it is typically a reserved word. The [] get around that, but it will make life tougher in the long run.
try to change name of your field because date is a reserved keyword.
After change the format of your date to use a format compliant to VB6 (with #)
The lines Format = stdate("mm/dd/yyyy") and Format = edate("mm/dd/yyyy")
don't look like valid VB6 to me.
You will need to build the query string by gluing the bits together, the interpreter cannot see inside the quotation marks to understand that you want a variable there
"SELECT * FROM sales_info WHERE date BETWEEN #" & stdate & "# and #" & edate &"#"
Try if this works. :)
Adodc1.RecordSource = = "SELECT * " & "FROM tbl " & _
"WHERE Date >= #" & stdate & "# AND Date <= #" & edate & "# "
Adodc1.Requery
Table_1BindingSource.Filter="DateColumnName>=# & DateTimePicker1.text & "# and DateColumName<=#" & DateTimePicker2.text & "#"

UTC Time Assignment in VBScript

Does anyone have a simple means in VBScript to get the current time in UTC?
Thanx,
Chris
I use a simple technique
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate (now())
wscript.echo "Local Time: " & dateTime
wscript.echo "UTC Time: " & dateTime.GetVarDate (false)
More info on SWbemDateTime
If you wanted to convert UTC back to local time do this:
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate now(),false REM Where now is the UTC date
wscript.echo cdate(dateTime.GetVarDate (true))
There are lots of examples out there. If you can access the registry this one will work for you:
od = now()
set oShell = CreateObject("WScript.Shell")
atb = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\" &_
"Control\TimeZoneInformation\ActiveTimeBias"
offsetMin = oShell.RegRead(atb)
nd = dateadd("n", offsetMin, od)
Response.Write("Current = " & od & "<br>UTC = " & nd)
From http://classicasp.aspfaq.com/date-time-routines-manipulation/how-do-i-convert-local-time-to-utc-gmt-time.html
You can get time bias from Win32_TimeZone WMI class.
myDate = "9/4/2013 17:23:08"
For Each objItem In GetObject(_
"winmgmts:\\.\root\cimv2").ExecQuery(_
"Select * from Win32_TimeZone")
bias = objItem.Bias
Next
myDate = DateAdd("n", bias, myDate)
WScript.Echo myDate
With SetVarDate the offset change due to transition to daylight saving time (from +060 to +120) occurred one hour too soon. The RegRead(HKLM\..\ActiveTimeBias) method was spot-on. If reproduction is desired, just put the pc clock on a time just before and just after the expected transition time and check the results.
Here is an example that formats the date to UTC as well. Note that you cannot format to a millesecond level with this.
Dim formattedDate
Dim utcDate
Set objShell = WScript.CreateObject("WScript.Shell")
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate(now())
utcDate = dateTime.GetVarDate(false)
wscript.echo "Local Time: " & dateTime
wscript.echo "UTC Time: " & utcDate
formattedDate = DatePart("yyyy",utcDate) & "-" & Right("0" & DatePart("m",utcDate), 2) & "-" & Right("0" & DatePart("d",utcDate), 2)
& "T" & Right("0" & DatePart("h",utcDate), 2) & ":" & Right("0" & DatePart("n",utcDate), 2)
& ":" & Right("0" & DatePart("s",utcDate), 2) & ".000+0000"
wscript.echo formattedDate
'results in a format that looks like this: 1970-01-01T00:00:00.000+0000
set dateTime=Nothing
set objShell=Nothing
Based on above functions - returns a delta-value to be added to the current time to return UTC.
Or call it with DATE+TIME to return UTC.
Call it once and store in a global variable to offset any date/time to UTC.
Conversely Subtract it from any UTC to get the time in the current time zone.
The additional ROUND towards the bottom is an attempt to compensate for floating point errors in the conversion to the nearest second.
Function Time_add_To_get_UTC(Optional DateTime = 0) ''as double
'' Returns value to add to current time to get to UTC
''Based on above functions : )
''return offset from current time to UTC
''https://stackoverflow.com/questions/15887700/utc-time-assignment-in-vbscript/22842128
Dim SWDT ''As SWbemDateTime
Dim dt ''As Date
Set SWDT = CreateObject("WbemScripting.SWbemDateTime")
dt = Date + Time()
SWDT.SetVarDate (dt)
Time_add_To_get_UTC = CDbl(SWDT.GetVarDate(False)) - CDbl(SWDT.GetVarDate(True))
Time_add_To_get_UTC = CDbl(Round(Time_add_To_get_UTC * 24 * 60 * 60, 0) / 24 / 60 / 60)
Time_add_To_get_UTC = DateTime + Time_add_To_get_UTC
End Function

Vbscript Month and Second Function to 3 decimal places

I am trying to write a vbscript that will write the date and time into a config file in specific way. I have been researching the web and have not been able to locate how to format the seconds function correctly. Not even sure if it is possible. Any help or references would be greatly appreciated. My question is, Is there a way to format the Month and Seconds Function so that month will display as MM if single number month and second will display 3 decimal places?
Here is what I have tried so far but it is invalid.
myDate = (Year(Now) & "-" & Month(date) & "-" & day(date) & "T" & Hour(Time) & ":" & Minute(time) & ":" & Second(time) ' Displays as YYYY-MM-DDTHH:MM:SS
second = FormatNumber(Second, 3)
write.write(myDate)
I need it to display as YYYY-MM-DDTHH:MM:SS.SSS. Thanks in advance.
Now() Accuracy in VBScript
It seems in vbscript the "Now()" function can be converted to double to provide this type of precision.
Use a pad function to pad with extra zero's. Use the timer for capturing the milliseconds.
Option Explicit
Dim timerNow, myNow, myDate
timerNow = cStr(cdbl(timer))
myNow = now()
myDate = (Year(myNow) & "-" & _
zeropad(Month(myNow),2) & "-" & _
zeroPad(day(myNow),2) & "T" & _
zeroPad(Hour(myNow),2) & ":" & _
zeroPad(Minute(myNow),2) & ":" & _
zeroPad(Second(myNow),2) & "." & _
left(split(timerNow, ".")(1),3)) ' Displays as YYYY-MM-DDTHH:MM:SS.SSS
Private Function zeroPad(byval strInput, byval padCount)
If len(strInput) < padCount Then
zeroPad = string(padCount - len(strInput), "0") & strInput
Else
zeroPad = strInput
End If
End Function
One thing could go wrong here: When the time is just jumping from n.999 to n+1.000 when myNow and timerNow are retrieved. Idealiter you would extract myNow from timerNow, but that is left as an exercize for the reader.
CStr(Year(Date())) & "-" & Right("0" & CStr(Month(Date())), 2) & "-" & Right("0" & CStr(Day(Date())), 2)
This code will create YYYY-MM-DD
I think you get the idea and will be able to add the time component yourself

Resources