Creating Date and Time Stamps

Scripts generate ISO 8601–format dates and times that you can use in filenames

Alex Angelopoulos

September 10, 2006

8 Min Read
ITPro Today logo in a gray background | ITPro Today


Administrators occasionally need unambiguous datestamps and timestamps usablein file and folder names, but how to createthem isn’t immediately obvious. VBScript’sdate-manipulation tools generate dates andtimes that are formatted according to localeand that usually include characters that youcan’t use in filenames.

The ISO 8601 standard is a goodchoice for a date- and timestamp format—I’ll explain why and then show you how togenerate ISO 8601 stamps easily, even onpre–Windows XP systems that don’t provide some convenient stamping tools.

The ISO 8601 Format
If you want to insert a date or time into a logfile, you can use almost any format youwant. However, you have more restrictionsif you want to use a date- or timestamp asa name or part of a name for a file; the ubiquitous forward slash and colon are bothreserved characters, and removing themcan make a date or time that doesn’t includeleading zeroes ambiguous.

The simplest solution I’ve foundthat generally works is to representdates and times in the widely adoptedISO 8601 standard’s basic format fordisplaying calendar dates.

The ISO 8601 standard providesguidance for representing dates andtimes in an unambiguous form. Thebasic format is all-numeric; there isalso an extended format in which elements are separated with delimitingcharacters.

A datestamp in the basic format iseight numeric digits in the patternyyyymmdd, where yyyy is the four-digit year, mm is the two-digit month,and dd is the two-digit day of themonth. You must pad any month orday that has only one digit with a leading 0. In this scheme, February 1,2005 is 20050201.

A timestamp that uses the ISO8601 basic format is six digits in theform hhmmss, where hh is the two-digit hour of the day in 24-hour format,mm is the two-digit minute, and ss isthe two-digit second. Using this format, 9:05 A.M. is 090500; 9:05 P.M. is210500.

Why this particular format? Themost crucial issue is that we settle onsome format. We can’t generally useraw numeric dates and expect themto be useful. Suppose we just choppunctuation out of a date string to geta stamp such as 1122005. In the United States, that might refer toeither January 12, 2005 or November2, 2005.

If you’re in a multinational organization, things are even more confusing. Most of the world uses day/month/year ordering; thus, 1122005could also refer to December 1, 2005or February 11, 2005. Even with themissing leading 0 in place in thisstamp, this format is ambiguous inmultinational organizations because01122005 could still refer to eitherJanuary 12 or December 1.

The ISO 8601 basic format, incontrast, has a variety of simpleadvantages that add up:

  • The format is friendly with most file systems. All the characters are allowed in file and folder names and don’t need to be escaped. If you’re using stamps as the complete folder names or file base names, there’s no risk of them being truncated if the files are copied to a volume that supports only 8.3 filenames.

  • The meaning of the format is difficult to misinterpret. This is one of the important features of the ISO 8601 standard. Dates are generally very ambiguous because some regions use month first and others use day first for common display. However, the first four characters of an ISO 8601 date string are always clearly the year portion of a date, and every format that begins with the year uses month/day order following it. Technically oriented people often find the format instinctive because the year/month/day order is similar to the greater-to-lesser order used in numbers.

  • If you sort ISO 8601 date- or timestamps alphabetically, they’re also sorted chronologically. For example, you might use the stamps 20060501 and 20061130 as names for folders. Regardless of when the folders were created or modified last, if you sort the folder names alphabetically, they’ll be ordered by the date reference in the stamp.

  • The individual date and time elements are short enough to be apparent even without punctuation.

  • The format might be familiar even to those who don’t know about ISO 8601. Windows Management Instrumentation (WMI) uses a similar datestamp format that’s based on ISO 8601. The standard is also widely accepted and used informally, even by people who have no clue that it’s a standard.

If we want to use this ISO 8601 format, the next question is: How do weactually generate a stamp that complies with it?

Using WMI
Generating an ISO 8601 date- ortimestamp is easy on XP and laterWindows versions. WMI’s SWbemDateTime class wraps up a bunch offunctionality for easily translatingdates and times between what Microsoft calls an OLE DateTime or VarDate—the kind of date and timeobject that VBScript uses—and othersignificant forms, including WMI’sown time string format. Bobby Malikpreviously discussed some aspects ofthis class in “WMI Time Bewilderment” (September 2002, InstantDocID 26030). I’ll show you how to doone simple thing: put in a VBScriptdate and get back a WMI date/timestring.

Listing 1 shows the code for thistask. Note that at callout A in Listing1, the first line of code, which wouldnormally generate a script date andtime, is commented out. For testingpurposes, the second line of codesupplies a VBScript date corresponding to 3:26:58 P.M. on August 18,2005.

SWbemDateTime doesn’t have adate or time when you set it up; itsrole is really just that of a translatorbetween different time formats. To initialize it, the code at callout B in Listing 1 passes it the referenceTimevalue by using the SetVarDatemethod. Then the code can get thedate and time back as a WMIdate/time string by reading the valuenamed Value in this class.

On my system, the echo statementin callout B shows this:

20050818152658.000000-300 

On your particular system, the last fourcharacters might be different becausethey correspond to the number ofminutes offset from Coordinated Universal Time (UTC), but everythingbefore that should be identical.

The beauty of using SWbemDateTime is that we get our stamps by justcutting the string contained in Valueinto pieces. As shown at callout C in Listing 1, we get a datestamp byextracting the first eight characters ofthe string and a timestamp by extracting the six-character sequence thatstarts with the ninth character in thestring.

Unfortunately, for the substantialportion of working PCs that have apre-XP OS, this technique won’t work.We can get everything we need byusing pure VBScript, though; it justtakes a little bit of work.

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.

Listing 2 shows the entire process. Although several lines of code are required, the lines are simple and repetitive.

The code assumes that the year portion of the string is four characters long. VBScript always returns a complete year, not an abbreviated, two-digit year, so the only VBScript-generated date range the code won’t produce an accurate date/time stamp for is the interval from A.D. 100 through A.D. 999. Arguably, the code could be “fixed” to handle this range, but you likely won’t encounter dates in this range in your day-to-day work.

Callout A in Listing 2 shows how we get the other two date elements in proper form. Each element will always be a number represented with one or two characters. If it’s only one character, we preface it with a 0.

Once we have the elements padded, we just join them together, as shown at callout B in Listing 2. The WScript.Echo statements will then display the following output:

datestamp: 20050815timestamp: 155658 

Although this code works, rewriting it every time you need a date- or timestamp isn’t so much fun. The best way to simplify generating date- and timestamps is to wrap the code up in functions that you can drop into your own scripts. Listing 3 shows the code in Listing 2 reworked as two drop-in functions, ToDateStamp and ToTimeStamp. Both functions generate strings from a VBScript date because this is the most flexible way to handle stamps. Most code that needs to generate a stamp bases it on the current date and/or time, and you can use VBScript’s Now function to get a complete date and time usable in both functions.

Dating Advice
Generally, you should avoid the VBScript functions Date and Time. Although they generate a valid current date and time respectively, the Date function doesn’t retain time information, so if you pass a date generated from Date to the ToTimeStamp function, it will always return the string “000000”. VBScript’s Time function returns only the current time of day with the actual date chopped out, so although it technically still contains date data, using it with ToDateString will always return the string “18991230”. This peculiar result is because VBScript’s dates are actually a count of days from December 30, 1899.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like