A big headache for developers, particularly when it comes to database-driven applications, is the differing date formats across country borders, a classic example of which is the USA date format of mm/dd/yyyy versus the European use of dd/mm/yyyy (where dd=day, mm=month and yyyy=year).
This kind of difference leads to all sorts of problems when moving applications around on different servers, particularly when you are switching between global hosts. Now one of the solutions has always been to try and force the server to use your desired date format by forcing the Local Identifier (LCID) (Session.LCID = xxxx) to your region specific choice, but this isn’t a great solution when your application is hosted on a server in another country that uses a different code from your forced code!
A far better solution then is to make use of the ISO date format, a format that is not ambiguous even in different countries and comes with the added bonus of being naturally sorted in descending order. The ISO format is yyyy/mm/dd where yyyy=year, mm=month and dd=day, and it is important to note that days and months less than 10 must be prefixed with a leading zero. (So the first of July 2008 would be ‘2008/07/01’.)
So the question now is what is a good ASP function for creating ISO dates then?
Well, it is fairly simple actually. First we make use of the standard VBScript Day(), Month() and Year() functions to pull the day, month and year out of a given date (these functions ignore the location specific formatting) and then we pad the resulting numbers should they be less that two digits long. Of course, we could just use a simple ‘if length less than two’ statement to do the padding for us, but a far more interesting looking way is to simply add 100 to the day and month and then take the last two digits from the resulting numbers to give us the correctly formatted numbers.
So putting it all together, we get this little easy to use function that checks if the passed variable is really a date and then converts it to the ISO date format:
Function FormatISODate(dteDate)
If IsDate(dteDate) = True Then
Dim dteDay, dteMonth, dteYear
dteDay = Day(dteDate)
dteMonth = Month(dteDate)
dteYear = Year(dteDate)
FormatISODate = dteYear & "/" & Right(Cstr(dteMonth + 100),2) & "/" & Right(Cstr(dteDay + 100),2)
Else
FormatISODate = Null
End If
End Function