date format in VBS - vbscript

I want to get a date in full format in my vbscript. For example, I put
DateParam = FormatDateTime(Date()-1, 2)
But it returns
3/8/2012
I need to function to return
03/08/2012 instead.
Does anyone knows how to fix this?

The FormatDateTime function is useless, because it depends on the user specific and global Regional Settings.
The best (most gain for least effort) solution - tapping into .NET - is flawed for dates; again because of the dependency on the Regional Settings.
If you want/need to roll your own function, start with something like fmtDate().
Dim g_oSB : Set g_oSB = CreateObject("System.Text.StringBuilder")
Function sprintf(sFmt, aData)
g_oSB.AppendFormat_4 sFmt, (aData)
sprintf = g_oSB.ToString()
g_oSB.Length = 0
End Function
Function fmtDate(dtX)
fmtDate = Join(Array( _
Right(100 + Month(dtX), 2) _
, Right(100 + Day(dtX), 2) _
, Year(dtX) _
), "/")
End Function
Dim dtYesterday : dtYesterday = Date() - 1
WScript.Echo "Yesterday:", dtYesterday, GetLocale()
WScript.Echo "sprintf (silly) =>", sprintf("{0:MM/dd/yyyy}", Array(dtYesterday))
WScript.Echo "sprintf (clumsy) =>", sprintf("{0:MM}/{0:dd}/{0:yyyy}", Array(dtYesterday))
WScript.Echo "fmtDate =>", fmtDate(dtYesterday)
output:
Yesterday: 08.03.2012 1033
sprintf (silly) => 03.08.2012
sprintf (clumsy) => 03/08/2012
fmtDate => 03/08/2012
On second thought:
Escaping the "/" helps to make sprintf() usable:
WScript.Echo "sprintf (silly me) =>", sprintf("{0:MM\/dd\/yyyy}", Array(dtYesterday))
output:
sprintf (silly me) => 03/08/2012
So don't bother with fmt* functions but use .NET formatting.

ThisDate = Date()
MyDate = Right("0" & CStr(Month(ThisDate)), 2) & "/" & _
Right("0" & CStr(Day(ThisDate)), 2) & "/" & CStr(Year(ThisDate))

Related

CDate format creating problems in diff date [duplicate]

I have last boot time from WMI and it looks as '20141103113859.220250+060'. i want to convert it to number of days and time from the current time.
is it possible?
From Help
Use the SWbemDateTime object to convert these to regular dates and times.
Windows 2000/NT and Windows 98/95: SWbemDateTime is not available. To convert WMI dates to FILETIME or VT_DATE format or to parse the date into component year, month, day, hours, and so on, you must write your own code.
Set dtmInstallDate = CreateObject( _
"WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject( _
"winmgmts:\\" & strComputer & "\root\cimv2")
Set objOS = objWMIService.ExecQuery( _
"Select * from Win32_OperatingSystem")
For Each strOS in objOS
dtmInstallDate.Value = strOS.InstallDate
Wscript.Echo dtmInstallDate.GetVarDate
Next
To get help.
http://msdn.microsoft.com/en-us/windows/hardware/hh852363
Install the Windows SDK but just choose the documentation.
Next simple function should work for any argument in valid CIM_DATETIME format.
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = ( Left(dtmDate, 4) _
& "/" & Mid(dtmDate, 5, 2) _
& "/" & Mid(dtmDate, 7, 2) _
& " " & Mid(dtmDate, 9, 2) _
& ":" & Mid(dtmDate,11, 2) _
& ":" & Mid(dtmDate,13, 2))
End Function
An example:
InstallDate (wmi): 20141205231553.000000+060
InstallDate: 2014/12/05 23:15:53
However, a wmi query could return Null, e.g. VarType(dtmDate)=1 for a particular instance of a date; in next script is the function modified:
option explicit
Dim strWmiDate
strWmiDate = "20141103113859.220250+060"
Wscript.Echo strWmiDate _
& vbNewLine & WMIDateStringToDate(strWmiDate) _
& vbNewLine & DateDiff("d", WMIDateStringToDate(strWmiDate), Now) _
& vbNewLine _
& vbNewLine & WMIDateStringToDate(Null) _
& vbNewLine & DateDiff("d", WMIDateStringToDate(Null), Now)
Function WMIDateStringToDate(byVal dtmDate)
If VarType(dtmDate)=1 Then
WMIDateStringToDate = FormatDateTime( Now) 'change to whatever you want
Else
'
' to keep script locale independent:
' returns ANSI (ISO 8601) datetime format (24 h)
'
' yyyy-mm-dd HH:MM:SS
'
WMIDateStringToDate = Left(dtmDate, 4) _
& "-" & Mid(dtmDate, 5, 2) _
& "-" & Mid(dtmDate, 7, 2) _
& " " & Mid(dtmDate, 9, 2) _
& ":" & Mid(dtmDate,11, 2) _
& ":" & Mid(dtmDate,13, 2)
End If
End Function
Output:
==>cscript 29535638.vbs
20141103113859.220250+060
2014-11-03 11:38:59
157
09.04.2015 15:36:38
0
#Serenity has given this same answer while i was writting, but ...
Option Explicit
WScript.Echo getLastBootUpTime()
WScript.Echo WMIDate2Date( "20141103113859.220250+060" )
WScript.Echo GetElapsedTime( getLastBootUpTime(), Now )
Function WMIDate2Date( ByVal WMIDate )
With WScript.CreateObject("WbemScripting.SWbemDateTime")
.Value = WMIDate
WMIDate2Date = .GetVarDate(False)
End With
End Function
Function getLastBootUpTime()
Dim oOS
For Each oOS In GetObject( "winmgmts:\\.\root\cimv2").ExecQuery("Select LastBootUpTime from Win32_OperatingSystem")
getLastBootUpTime = WMIDate2Date(oOS.LastBootUpTime)
Next
End Function
Function GetElapsedTime( ByVal Date1, ByVal Date2 )
Dim seconds, aLabels, aValues, aDividers, i
aLabels = Array( " days, ", ":", ":", "" )
aDividers = Array( 86400, 3600, 60, 1 )
aValues = Array( 0, 0, 0, 0 )
i = 0
seconds = Abs( DateDiff( "s", Date1, Date2 ))
Do While seconds > 0
aValues(i) = Fix( seconds / aDividers(i) )
seconds = seconds - aValues(i) * aDividers(i)
aValues(i) = CStr(aValues(i)) & aLabels(i)
i=i+1
Loop
GetElapsedTime = Join(aValues, "")
End Function
You won't get around splitting the WMI date string to make it to a date string that VBScript understands. Try this:
<%
wmiDate = "20141103113859.220250+060"
' note i am using date format: [m/d/Y H:m:s]
' if you prefer other format, i.e. [d.m.Y H:m:s] switch mid offsets
fromDate = Mid(wmiDate,5,2) & "/" & Mid(wmiDate,7,2) & "/" & Left(wmiDate,4)
fromTime = Mid(wmiDate,9,2) & ":" & Mid(wmiDate,11,2) & ":" & Mid(wmiDate,13,2)
toDate = Date & " " & Time
response.write(DateDiff("d",fromDate & " " & fromTime,toDate) & " Days<br />")
response.write(DateDiff("h",Date & " " & fromTime,toDate) & " Hours<br />")
%>
It uses Mid()and Left()functions to split WMI date into the needed parts for VBScript. Then the DateDiff() function will deliver the interval difference first for d= days and then for h= hours. You will notice when calculating hours i just used the time part of the WMI string, since we already calculated days difference, we only want hours left over.
Interesting article explaining VBScript Date and Time (Iso Formats)
As a comment was so kindly remarking the date format i used and the result of the hour calculation, i added a comment line explaining the date format i used (i used m/d/Y H:m:s but depending on your local, you might prefer d.m.Y H:m:s then you need to swap the Mid() offsets to get the right order). I also appended the current Time to the toDate and in the hour calculation prepended the current Date to calculate the correct time difference.

Classic Asp cookie expires date does not always get set

I am trying to set cookie with addheader -method in Classic Asp which is the only way of adding among other things HttpOnly and Secure -flags to cookies. All work with the below code - but there is one exception and its is the expiration date/time.
<%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & dateAdd("d", 365, Now()) & ";samesite=Strict;HostOnly"
%>
However, it seems to be browser-related issue. In firefox I can see in the Storage tab of developer tools that expiration time is set. But in Chrome it always stays as the default which is the expiration with the end of session. This same issue is with the Edge too.
Has anyone any experience with this issue?
The expected date format is documented here. You need to produce expiration date in that manner.
In Classic ASP, you can use server-side JavaScript to produce such dates easily.
<!--#include file="HTTPDate.asp"-->
<%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & HTTPDate(DateAdd("d", 365, Now())) & ";samesite=Strict;HostOnly"
%>
HTTPDate.asp
<script language="javascript" runat="server">
function HTTPDate(vbsDate){
return (new Date(vbsDate)).toGMTString().replace(/UTC/, "GMT");
}
</script>
Edit: Pure VBScript solution added.
<%
Function CurrentTZO()
With CreateObject("WScript.Shell")
CurrentTZO = .RegRead( _
"HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
End With
End Function
Function Pad(text)
Pad = Right("00" & text, 2)
End Function
Function HTTPDate(ByVal localDate)
localDate = DateAdd("n", CurrentTZO(), localDate)
' WeekdayName and MonthName functions relies on locale
' need to produce day and month name abbreviations in en-US locale
Dim locale : locale = SetLocale("en-US")
Dim out(5)
out(0) = WeekdayName(Weekday(localDate), True) & ","
out(1) = Pad(Day(localDate))
out(2) = MonthName(Month(localDate), True)
out(3) = Year(localDate)
out(4) = Join(Array(Pad(Hour(localDate)), Pad(Minute(localDate)), Pad(Second(localDate))), ":")
out(5) = "GMT"
SetLocale locale ' set original locale back
HTTPDate = Join(out, " ")
End Function
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & HTTPDate(DateAdd("d", 365, Now())) & ";samesite=Strict;HostOnly"
%>
In addition to the accepted solution of Kul-Tigin I want to add also a vbscript solution for those who are missing that too.
<%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & (New UTC).toUTCString(500,"d") & ";samesite=Strict;HostOnly;"
Class UTC
Public Function toUTCString(ByVal offSet, ByVal offsetType)
' ***********************************
' Converts vbScript datetime format to
' Universal datetime string format:
' Tue, 16 Feb 2021 13:39:24 GMT
'************************************
Dim dt: dt = dateAdd(offsetType, offSet, UTCDate(Now()))
Dim tdParts: tdParts = Split(dt, " ")
Dim tPart: tPart = CDate(tdParts(1) & " " & tdParts(2))
Dim dPart: dPart = CDate(tdParts(0))
Dim timeTo24: timeTo24 = _
Right("0" & Hour(tPart), 2) & ":" & _
Right("0" & Minute(tPart), 2) & ":" & _
Right("0" & Second(tPart), 2)
toUTCString = WeekdayName(Weekday(dPart), True) & ", " & _
Day(dPart) & " " & _
MonthName(Month(dPart), True) & " " & _
Year(dPart) & " " & _
timeTo24 & " GMT"
End Function
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
%>

Microsoft VBScript runtime error '800a000d' Type mismatch: 'LastID'

I do a function to assign an ID. But when I click button, this error comes out.
Microsoft VBScript runtime error '800a000d' Type mismatch: 'LastID'
Public function AssignSanctionID(DeptID,SectID,SanctionType)
REM obtain Transaction ID
dim CmdX
dim SQLX
dim RsX
dim Prefix
dim LastID
dim CurrID
dim NewCurrID
'- Set Connection
HariNi=now()
Tahun=year(HariNi)
Bulan=month(HariNi)
if len(bulan)=1 then
Bulan= "0" & Bulan
end if
If Cint(Tahun) < 2016 then
Pref1= DeptID & "/" & SectID & "/"
Prefix=DeptID & "/" & SectID & "/" & Tahun & "/" & Bulan & "/"
else
Pref1= DeptID & "/%/" & SectID
Prefix=DeptID & "/" & Tahun & "/" & Bulan & "/"
end if
set CmdX = server.CreateObject("ADODB.Command")
Set RSX = Server.CreateObject("ADODB.Recordset")
SQLX = " SELECT * FROM Sanction " _
& " WHERE SanctionID like '%" & Pref1 & "%' " _
& " ORDER BY ID DESC"
CmdX.ActiveConnection = objconn
CmdX.CommandText = SQLX
RsX.Open CmdX,,0,1
if not(RsX.BOF and RsX.EOF) then
If Cint(Tahun) < 2016 then
LastID = right(RsX("ID"),4)
else
LastID = mid(RsX("ID"),13,4)
end if
else
if Bulan="04" then
LastID=0
end if
end if
RsX.Close
set RsX = nothing
'Set ID
If LastID<>"" then
'CurrID = left(4)
CurrID=int(LastID)+1
end if
if len(currid)>0 then
select case len(currid)
case 1
newcurrid = "000" & currid
case 2
newcurrid = "00" & currid
case 3
newcurrid = "0" & currid
case 4
newcurrid = currid
end select
else
NewCurrID="0001"
end if
If Cint(Tahun) < 2016 then
NewCurrID=Prefix & NewCurrID
else
NewCurrID=Prefix & NewCurrID & "/" & SectID
end if
AssignSanctionID = NewCurrID
end function
Hard to help if I don't see the data.
From quick view of the code the issue is here:
CurrID=int(LastID)+1
You are trying to cast LastID but are you sure that it is convertible? Could list all possible values?
Short answer: CInt only works with Numerical values. If you have letters in your value, then Cint wont work.
Bit longer answer:
Having read the Blog that we should be more welcoming (https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/?cb=1), here is a very general answer, but that might lead you on the correct way to fix it yourself.
Type Mismatch is an error you can get when using a variable the wrong way. For example if you try to do numerical functions with Strings (which means the variable contains letters a-z etc) you will get "Type Mismatch" as you cant add or subtract text in a mathematical way... On the other hand you cant add Integer variables (the variable only contains a number AND isnt contained within "quote marks").
So below is a few ways to assigna a variable and what type it becomes:
LastID=1 'This makes LastID an INT (number)
LastID="1" 'This makes LastID a String but a CInt(LastID) can turn it into an INT because it ONLY contains numbers.
LastID="IT" 'This makes LastID a String that CANT in any way be cast to INT as it contains letters.
LastID=IT 'This row will either create an error except if you already have a variable called IT, then LastID will get the same value as the IT variable...
This should hopefully get you on your way to fix this issue...

vbscript: how to convert a date into days and time

I have last boot time from WMI and it looks as '20141103113859.220250+060'. i want to convert it to number of days and time from the current time.
is it possible?
From Help
Use the SWbemDateTime object to convert these to regular dates and times.
Windows 2000/NT and Windows 98/95: SWbemDateTime is not available. To convert WMI dates to FILETIME or VT_DATE format or to parse the date into component year, month, day, hours, and so on, you must write your own code.
Set dtmInstallDate = CreateObject( _
"WbemScripting.SWbemDateTime")
strComputer = "."
Set objWMIService = GetObject( _
"winmgmts:\\" & strComputer & "\root\cimv2")
Set objOS = objWMIService.ExecQuery( _
"Select * from Win32_OperatingSystem")
For Each strOS in objOS
dtmInstallDate.Value = strOS.InstallDate
Wscript.Echo dtmInstallDate.GetVarDate
Next
To get help.
http://msdn.microsoft.com/en-us/windows/hardware/hh852363
Install the Windows SDK but just choose the documentation.
Next simple function should work for any argument in valid CIM_DATETIME format.
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = ( Left(dtmDate, 4) _
& "/" & Mid(dtmDate, 5, 2) _
& "/" & Mid(dtmDate, 7, 2) _
& " " & Mid(dtmDate, 9, 2) _
& ":" & Mid(dtmDate,11, 2) _
& ":" & Mid(dtmDate,13, 2))
End Function
An example:
InstallDate (wmi): 20141205231553.000000+060
InstallDate: 2014/12/05 23:15:53
However, a wmi query could return Null, e.g. VarType(dtmDate)=1 for a particular instance of a date; in next script is the function modified:
option explicit
Dim strWmiDate
strWmiDate = "20141103113859.220250+060"
Wscript.Echo strWmiDate _
& vbNewLine & WMIDateStringToDate(strWmiDate) _
& vbNewLine & DateDiff("d", WMIDateStringToDate(strWmiDate), Now) _
& vbNewLine _
& vbNewLine & WMIDateStringToDate(Null) _
& vbNewLine & DateDiff("d", WMIDateStringToDate(Null), Now)
Function WMIDateStringToDate(byVal dtmDate)
If VarType(dtmDate)=1 Then
WMIDateStringToDate = FormatDateTime( Now) 'change to whatever you want
Else
'
' to keep script locale independent:
' returns ANSI (ISO 8601) datetime format (24 h)
'
' yyyy-mm-dd HH:MM:SS
'
WMIDateStringToDate = Left(dtmDate, 4) _
& "-" & Mid(dtmDate, 5, 2) _
& "-" & Mid(dtmDate, 7, 2) _
& " " & Mid(dtmDate, 9, 2) _
& ":" & Mid(dtmDate,11, 2) _
& ":" & Mid(dtmDate,13, 2)
End If
End Function
Output:
==>cscript 29535638.vbs
20141103113859.220250+060
2014-11-03 11:38:59
157
09.04.2015 15:36:38
0
#Serenity has given this same answer while i was writting, but ...
Option Explicit
WScript.Echo getLastBootUpTime()
WScript.Echo WMIDate2Date( "20141103113859.220250+060" )
WScript.Echo GetElapsedTime( getLastBootUpTime(), Now )
Function WMIDate2Date( ByVal WMIDate )
With WScript.CreateObject("WbemScripting.SWbemDateTime")
.Value = WMIDate
WMIDate2Date = .GetVarDate(False)
End With
End Function
Function getLastBootUpTime()
Dim oOS
For Each oOS In GetObject( "winmgmts:\\.\root\cimv2").ExecQuery("Select LastBootUpTime from Win32_OperatingSystem")
getLastBootUpTime = WMIDate2Date(oOS.LastBootUpTime)
Next
End Function
Function GetElapsedTime( ByVal Date1, ByVal Date2 )
Dim seconds, aLabels, aValues, aDividers, i
aLabels = Array( " days, ", ":", ":", "" )
aDividers = Array( 86400, 3600, 60, 1 )
aValues = Array( 0, 0, 0, 0 )
i = 0
seconds = Abs( DateDiff( "s", Date1, Date2 ))
Do While seconds > 0
aValues(i) = Fix( seconds / aDividers(i) )
seconds = seconds - aValues(i) * aDividers(i)
aValues(i) = CStr(aValues(i)) & aLabels(i)
i=i+1
Loop
GetElapsedTime = Join(aValues, "")
End Function
You won't get around splitting the WMI date string to make it to a date string that VBScript understands. Try this:
<%
wmiDate = "20141103113859.220250+060"
' note i am using date format: [m/d/Y H:m:s]
' if you prefer other format, i.e. [d.m.Y H:m:s] switch mid offsets
fromDate = Mid(wmiDate,5,2) & "/" & Mid(wmiDate,7,2) & "/" & Left(wmiDate,4)
fromTime = Mid(wmiDate,9,2) & ":" & Mid(wmiDate,11,2) & ":" & Mid(wmiDate,13,2)
toDate = Date & " " & Time
response.write(DateDiff("d",fromDate & " " & fromTime,toDate) & " Days<br />")
response.write(DateDiff("h",Date & " " & fromTime,toDate) & " Hours<br />")
%>
It uses Mid()and Left()functions to split WMI date into the needed parts for VBScript. Then the DateDiff() function will deliver the interval difference first for d= days and then for h= hours. You will notice when calculating hours i just used the time part of the WMI string, since we already calculated days difference, we only want hours left over.
Interesting article explaining VBScript Date and Time (Iso Formats)
As a comment was so kindly remarking the date format i used and the result of the hour calculation, i added a comment line explaining the date format i used (i used m/d/Y H:m:s but depending on your local, you might prefer d.m.Y H:m:s then you need to swap the Mid() offsets to get the right order). I also appended the current Time to the toDate and in the hour calculation prepended the current Date to calculate the correct time difference.

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