Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


September 11, 2006

Creating Date and Time Stamps

Scripts generate ISO 8601–format dates and times that you can use in filenames
RSS
View this exclusive article with VIP access -- click here to join |
See More VBScript Articles Here | Reprints | Or sign up for our VIP Monthly Pass!

Using Pure VBScript
As you may have noticed at callout A in Listing 1, VBScript is comfortable with dates and times expressed as numbers. VBScript contains native functions that can extract any component of a date/time value as a number—these are the appropriately named Year, Month, Day, Hour, Minute, and Second functions. Because these functions are present in all versions of VBScript no matter what the OS version, you can use them to help create a date- or timestamp in any version of Windows.

The VBScript date and time functions are not a solution by themselves, but if we look at the ISO 8601 standard, it becomes clear that we just need to do some formatting to get a stamp. Each element of the stamp must be a specific number of characters long: The year is four characters, and every other date and time element must be two characters long. If an element is fewer than the necessary number of characters, we add 0s to the left of it until it’s the correct length. . . .


Already a VIP member?
Please log on to view the full article

Why become a VIP member?

VIP-only online access
VIP CD delivered twice a year: offline access to the entire Windows IT Pro article library
Monthly issue of your choice of Windows IT Pro or SQL Server Magazine

Subscribe Now
Reader Comments
How about two lines that can be pasted in where needed:
wDate = Year(Now) & Right("00" & Month(Now), 2) & Right("00" & Day(Now), 2)
wTime = Right("00" & Hour(Now), 2) & Right("00" & Minute(Now), 2)

craigm3604 August 04, 2007 (Article Rating: )


Sorry - correction:
wDate = Year(Now) & Right("00" & Month(Now), 2) & Right("00" & Day(Now), 2)
wTime = Right("00" & Hour(Now), 2) & Right("00" & Minute(Now), 2) & Right("00" & Second(Now), 2)

craigm3604 August 04, 2007 (Article Rating: )


Craig,
using
Right("00" & <something>, 2)
is a very nice trick. I've adapted the two generic drop-in functions to use it, as shown below.

Function ToDateStamp(ByVal dt)
ToDateStamp = Year(dt) _
& Right("00" & Month(dt), 2) _
& Right("00" & Day(dt), 2)
End Function

Function ToTimeStamp(ByVal dt)
ToTimeStamp = Right("00" & Hour(dt), 2) _
& Right("00" & Minute(dt), 2) _
& Right("00" & Second(dt), 2)
End Function

Thanks for raising the point!

AlexKAngelopoulos August 10, 2007 (Article Rating: )


Without knowing it had a definition, I've been using ISO 8601 format for some time for just the advantages you listed, in particular that this format is easy to understand and read, and that it sorts very nicely.

From a CMD file, you can create an ISO 8601 compatible string for the date by using this:

FOR /F "tokens=2-4 delims=/ " %%f in ("%date%") do set ISO9601Date=%%h%%f%%g

Note that I'm using two delimiters here, a forward slash AND a space, the space is necessary to lop off the day of the week from the front of the date variable.

and for time, use

FOR /F "tokens=1-3 delims=:." %%f in ("%time: =0%") do set ISO9601Time=%%f%%g%%h


The %time: =0% (after the colon it is 'space equals 0' changes all the blanks in the time variable to 0, taking care of the single digit hour issue

(These were prepared on Windows XP Pro using English-US regional settings. Your configuration may require this code to be tweaked)

Jim

TheFormatter June 06, 2008 (Article Rating: )


what about an even easier approach?

wDate = CStr(Year(Now) * 10000 + Month(Now) * 100 + Day(Now))
wTime = Right(CStr(1000000 + Hour(Now) * 10000 + Minute(Now) * 100 + Second(Now)), 6)

to get an ISO date in a batch file just put the mathematical part of the aforementioned expressions (ie without the string functions) in a vbscript file and return the result with WScript.Quit, like

WScript.Quit(Year(Now) * 10000 + Month(dtNow) * 100 + Day(Now))

and retrieve the value by using %ErrorLevel%

OlliK June 06, 2008 (Article Rating: )


The standard gives several formats, and I find the format <YYYY><MM><DD>T<hh>:<mm>:<ss.ddd><timezoneletter> more readable. Unfortunately one has to define the format in the given language.
But it is defently worth the effort.

NielsGrove June 06, 2008 (Article Rating: )


Jim -
These look like they work on Vista with default US date/time settings as well. Unfortunately, I found the cmd approach doesn't work very well if the settings are already in an ISO8601 form (although it _should_ be possible to make a batch file that uses reg.exe to check the registry for the current date settings format and base parsing on that).

AlexKAngelopoulos June 11, 2008 (Article Rating: )


OlliK -
The approach you show is definitely more compact, but there actually is a case where it could be a problem due to the discrete amount of time it takes for each evaluation of Now().
If you're generating a date/time stamp right around the time when the year, month, day, hour, or minute is about to increment, you can get a bad value generated. It's going to be very rare of course, but it could be bizarre in the worst possible cases. As an example, suppose the code is running at approximately midnight on 2008 December 31. By evaluating Now() once, you get a specific value that may turn out to be
20081231 235959
or, if run milliseconds later,
20090101 000000
The first one is just before the beginning of the year, the second is just after the beginning of the year.
However, with multiple evaluations of Now(), wDate might be evaluated before midnight as 20081231 and wTime right after midnight, giving you
20081231 000000
which is 24 hours earlier! It could even happen within a line of code; VBScript evaluates right to left, so if the date changes immediately after the day is evaluated, then you would get
20091231 000000
which is almost a year off.
The code runs _very_ fast on modern machines so I would be very surprised to see this happen, but the mere possibility would qualify as a bug. That's why I use the longer way that evaluates Now() once.

AlexKAngelopoulos June 11, 2008 (Article Rating: )


You must be a registered user or online subscriber to comment on this article. Please log on before posting a comment. Are you a new visitor? Register now




Top Viewed ArticlesView all articles
Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

WinInfo Short Takes: Week of November 9, 2009

An often irreverent look at some of the week's other news, including some more Windows 7 sales momentum, some Sophos stupidity, Microsoft's cloud computing self-loathing, more whining from the browser makers, Zoho's "Fake Office," and much, much more ...

Understanding File-Size Limits on NTFS and FAT

A general confusion about files sizes on FAT seems to stem from FAT32's file-size limit of 4GB and partition-size limit of 2TB. ...


Scripting Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Related Events Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement