Skip Navigation

VBScript Date Format Functions

VBScript's date formatting doesn't offer a huge number of options compared to PHP's date() function. While it's relatively easy to just write small snippets of code every time you need to format a date a specific way, life would be much easier if there was a function you could call on time and again to do the work for you.

Below, you will find three date format functions, all of which make some use of Unix timestamps, a concept most ASP developers will not be familiar with. Unix timestamps are defined as the number of seconds since the epoch, 00:00:00 01/01/1970, and are a very sensible way to store dates and times in a database, in my opinion. They are very easy to work with, especially when selecting data from a database, and once you are used to them, they can make life much much simpler.

NOTE: These functions were updated on the 15th March 2004 to fix a couple of known bugs. In addition, any scripts using these functions may need to be tweaked to take account of your locale. Each locale will use a slightly different date and time format, so please check yours before using these functions, or simply set your locale to UK. To set your locale to UK, you can use the code below:

  1. <%@LANGUAGE=VBSCRIPT" LCID=2057%>

There is also a complete list of valid locales on the Microsoft website, with the values in the right hand column being the ones you will want.

Finally, the "monthname" function is VBScript is not present in every version, so may need to be defined manually. Please see comments on this article for an example.

The first function, UDate(), will convert a normal date into a Unix timestamp. The second function, unUDate(), simply does the reverse, converting any timestamp into a readable date. The last function takes a date and a format string, and returns a formatted date according to what you put into the formatting string.

UDate()

  1. function UDate(oldDate)
  2. UDate = DateDiff("s", "01/01/1970 00:00:00", oldDate)
  3. end function

In practice, UDate is very easy to use. For example, if you want to know the current Unix time (the number of seconds since the epoch), you would use something like the following, which would give intCurrent_Unix_Time a value of 1069916571 at the time of writing.

  1. intCurrent_Unix_Time = UDate(Now())

unUDate()

  1. function unUDate(intTimeStamp)
  2. unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
  3. end function

unUDate is as easy to use as UDate. Simply feed in an integer, and it will return a matching date. It will treat the integer as the number of seconds between the epoch and the desired date, and will return a properly formatted date for normal use in VBScript accordingly.

formatDate()

Now here's where it starts to get tricky. formatDate is also quite easy to use, but only once you get the hang of how it works. As you can see from the below, formatDate requires two values to be passed to it. The first, format, is a string telling the function how you would like the date formatted, and the second, intTimeStamp, can be either a Unix timestamp (preferred) or a normal VBScript date.

The format of the string is what we want to make use of to lay out our dates exactly as we would like, and perhaps this is best shown with an example. I would like a date displayed on my site in the following format: "7:11am, Thursday 27th November, 2003". In normal VBScript that would be a pain to format - I'd probably just end up giving up and using the normal VBLongTime and VBLongDate to display something similar. I would prefer complete control though...

The format string for formatDate can include a whole selection of characters to represent certain date or time entities. There's a table of the ones included in this function just below here. The format string needs to include these entities where it wants them to be replaced by the correct time or date value. To get the above formatted date and time, then, I could use the following:

  1. strDateTime = formatDate("%g:%i%a, %l %j%O %F, %Y", UDate(Now()))

That looks a lot harder than it actually is. To tell the function we are aiming to replace a specific entity in the string with a time or date element, we use a symbol made up of a percent sign (%) and a letter. It is a case sensitive function, so be careful you form your format strings correctly. Without further ado, here's a list of the entities you can include in the format string (anything in the string that is not an entity from the list below will still be in the string when it has been processed).

  • %A - AM or PM
  • %a - am or pm
  • %m - Month with leading zeroes (01 - 12)
  • %n - Month without leading zeroes (1 - 12)
  • %F - Month name (January - December)
  • %M - Three letter month name (Jan - Dec)
  • $d - Day with leading zeroes (01 - 31)
  • %j - Day without leading zeroes (1 - 31)
  • %H - Hour with leading zeroes (12 hour)
  • %h - Hour with leading zeroes (24 hour)
  • %G - Hour without leading zeroes (12 hour)
  • %g - Hour without leading zeroes (24 hour)
  • %i - Minute with leading zeroes (01 to 60)
  • %I - Minute without leading zeroes (1 to 60)
  • %s - Second with leading zeroes (01 to 60)
  • %S - Second without leading zeroes (1 to 60)
  • %L - Number of day of week (1 to 7)
  • %l - Name of day of week (Sunday to Saturday)
  • %D - Three letter name of day of week (Sun to Sat)
  • %O - Ordinal suffix (st, nd rd, th)
  • %U - UNIX Timestamp
  • %Y - Four digit year (2003)
  • %y - Two digit year (03)

You can include any of the above in the format string at any point. I would recommend not using a percentage sign if you can help it (except obviously as part of one of the elements above), and in the same vein, using ordinals anywhere except after a number is slightly foolish.

If you would like to see anything else added to the list, above, please email me and I will see what I can do.

The below is the formatDate function itself. To use, simply copy and paste it into a script or include file and call it as above, with whichever format string you require.

  1. function formatDate(format, intTimeStamp)
  2. dim unUDate, A
  3.  
  4. ' Test to see if intTimeStamp looks valid. If not, they have passed a normal date
  5. if not (isnumeric(intTimeStamp)) then
  6. if isdate(intTimeStamp) then
  7. intTimeStamp = DateDiff("S", "01/01/1970 00:00:00", intTimeStamp)
  8. else
  9. response.write "Date Invalid"
  10. exit function
  11. end if
  12. end if
  13. if (intTimeStamp=0) then
  14. unUDate = now()
  15. else
  16. unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
  17. end if
  18.  
  19. unUDate = trim(unUDate)
  20.  
  21. dim startM : startM = InStr(1, unUDate, "/", vbTextCompare) + 1
  22. dim startY : startY = InStr(startM, unUDate, "/", vbTextCompare) + 1
  23. dim startHour : startHour = InStr(startY, unUDate, " ", vbTextCompare) + 1
  24. dim startMin : startMin = InStr(startHour, unUDate, ":", vbTextCompare) + 1
  25.  
  26. dim dateDay : dateDay = mid(unUDate, 1, 2)
  27. dim dateMonth : dateMonth = mid(unUDate, startM, 2)
  28. dim dateYear : dateYear = mid(unUDate, startY, 4)
  29. dim dateHour : dateHour = mid(unUDate, startHour, 2)
  30. dim dateMinute : dateMinute = mid(unUDate, startMin, 2)
  31. dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":", vbTextCompare) + 1, 2)
  32.  
  33. format = replace(format, "%Y", right(dateYear, 4))
  34. format = replace(format, "%y", right(dateYear, 2))
  35. format = replace(format, "%m", dateMonth)
  36. format = replace(format, "%n", cint(dateMonth))
  37. format = replace(format, "%F", monthname(cint(dateMonth)))
  38. format = replace(format, "%M", left(monthname(cint(dateMonth)), 3))
  39. format = replace(format, "%d", dateDay)
  40. format = replace(format, "%j", cint(dateDay))
  41. format = replace(format, "%h", mid(unUDate, startHour, 2))
  42. format = replace(format, "%g", cint(mid(unUDate, startHour, 2)))
  43.  
  44. if (cint(dateHour) > 12) then
  45. A = "PM"
  46. else
  47. A = "AM"
  48. end if
  49. format = replace(format, "%A", A)
  50. format = replace(format, "%a", lcase(A))
  51.  
  52. if (A = "PM") then format = replace(format, "%H", left("0" & dateHour - 12, 2))
  53. format = replace(format, "%H", dateHour)
  54. if (A = "PM") then format = replace(format, "%G", left("0" & cint(dateHour) - 12, 2))
  55. format = replace(format, "%G", cint(dateHour))
  56.  
  57. format = replace(format, "%i", dateMinute)
  58. format = replace(format, "%I", cint(dateMinute))
  59. format = replace(format, "%s", dateSecond)
  60. format = replace(format, "%S", cint(dateSecond))
  61. format = replace(format, "%L", WeekDay(unUDate))
  62. format = replace(format, "%D", left(WeekDayName(WeekDay(unUDate)), 3))
  63. format = replace(format, "%l", WeekDayName(WeekDay(unUDate)))
  64. format = replace(format, "%U", intTimeStamp)
  65. format = replace(format, "11%O", "11th")
  66. format = replace(format, "1%O", "1st")
  67. format = replace(format, "12%O", "12th")
  68. format = replace(format, "2%O", "2nd")
  69. format = replace(format, "13%O", "13th")
  70. format = replace(format, "3%O", "3rd")
  71. format = replace(format, "%O", "th")
  72.  
  73. formatDate = format
  74.  
  75. end function

63 comments

Sarah
Australia #1: March 30, 2004
I pasted it as an include file, and imported it as usual, and I get the following error: Microsoft VBScript runtime (0x800A0005) Invalid procedure call or argument: 'monthname' /usermanagement/inc_formatdate.asp, line 34 Could you tell me why this is? Thanks muchly. sarah_rulez69@hotmail.com
Brent
United States #2: April 9, 2004
I've used the formatDate function and it's worked great until I tried using it in the following way. I've tried to use the following... <% Dim hr hr = UDate("01/01/2004 00:00:00") For i = 0 To 23 normhr = formatDate("%H %a", hr) milHr = formatDate("%g", hr) hr = hr + 3600 %> <option value="<%= milHr %>"><%= normhr %></option> <% Next %> ... to print the following <option value="0">12 am</option> <option value="1">1 am</option> <option value="2">2 am</option> <option value="3">3 am</option> <option value="4">4 am</option> <option value="5">5 am</option> <option value="6">6 am</option> <option value="7">7 am</option> <option value="8">8 am</option> <option value="9">9 am</option> <option value="10">10 am</option> <option value="11">11 am</option> <option value="12">12 pm</option> <option value="13">1 pm</option> <option value="14">2 pm</option> <option value="15">3 pm</option> <option value="16">4 pm</option> <option value="17">5 pm</option> <option value="18">6 pm</option> <option value="19">7 pm</option> <option value="20">8 pm</option> <option value="21">9 pm</option> <option value="22">10 pm</option> <option value="23">11 pm</option> but instead I get... <option value="1">01 am</option> <option value="1">01 am</option> <option value="2">02 am</option> <option value="3">03 am</option> <option value="4">04 am</option> <option value="5">05 am</option> <option value="6">06 am</option> <option value="7">07 am</option> <option value="8">08 am</option> <option value="9">09 am</option> <option value="10">10 am</option> <option value="11">11 am</option> <option value="12">12 am</option> <option value="13">01 pm</option> <option value="14">02 pm</option> <option value="15">03 pm</option> <option value="16">04 pm</option> <option value="17">05 pm</option> <option value="18">06 pm</option> <option value="19">07 pm</option> <option value="20">08 pm</option> <option value="21">09 pm</option> <option value="22">01 pm</option> <option value="23">01 pm</option> Any ideas???
dandin
Canada #3: April 17, 2004
I'm getting the same error than Sarah. Error Type: Microsoft VBScript runtime (0x800A0005) Invalid procedure call or argument: 'monthname' /nouvelles/date.asp, line 46 I'm running IIS 5.1, the one that comes with XP Pro
Emlyn
Switzerland #4: April 27, 2004
To get it to work, I needed to define monthname before the function like this: Dim monthname() : Redim monthname(12) monthname(1) = "January" : monthname(2) = "February" monthname(3) = "March" : monthname(4) = "April" monthname(5) = "May" : monthname(6) = "June" monthname(7) = "July" : monthname(8) = "August" monthname(9) = "September" : monthname(10) = "October" monthname(11) = "November" : monthname(12) = "December" Also the 4 lines replacing %G and %H had a bug, replace them with: if (A = "PM") then format = replace(format, "%H", right("0" &amp; dateHour - 12, 2)) format = replace(format, "%H", dateHour) if (A = "PM") then format = replace(format, "%G", cint(dateHour) - 12) format = replace(format, "%G", cint(dateHour))
Emlyn
Switzerland #5: April 27, 2004
Sorry that code isn't easy to read. How do I insert line breaks? <br> will <br> this <br> work?
Many thanks Emlyn. It seems from your post and a few of the emails I have received that the monthname function does not always work. Which is strange. I'll update the function when I've run a few tests on your suggested changes, but thankyou again.
Noodles
New Zealand #7: May 25, 2004
Hi, I had some problems with trying to get this script to work, i fixed them by adding "session.lcid=2057" at the top of the page which forces asp to use the UK date format.
Micha
United States #8: July 27, 2004
I had problems with the script.
I'm not using it as an ASP script but just as a usual VBScript in an application.

It complained with a type mismatch on some (not all) Cint statements that are used.

The problem with this script is that it uses string parsing to unravel the days, months, etc from a date.

However, the locale that I use does not display the month of July as 07 but as JUL. JUL is not a valid integer and therefore can't be converted to an Int.

To be really locale-independent you could probably use VBScript's DateDiff or other locale-independent date functions but a good programmer is a lazy programmer so what I did was change the default locale that is used to the UK locale using the VBScript SetLocale statement.

If you alter the script like this:

function formatDate(format, intTimeStamp)
dim unUDate, A

dim OriginalLocale
dim res
OriginalLocale = GetLocale
res = SetLocale("en-gb")

'/* rest of script unchanged */

res = SetLocale(OriginalLocale)

end function

It will always work because it always uses the same locale. At least, it worked for me!

I hope some people can use this tip.

Regards,
Micha
John
United States #9: September 28, 2004
thanks a lot Micha, that fixed it for me!!
Great script! Since I already have unixtime in my database it seems natural to also implement it into the scripts :)
One thing I miss is the function for counting weeks, datepart("ww") doesn't work as expected with the rules that first day of week is monday, and next year is when the week contains atleast 4 days of next year. :(
Great script! Since I already have unixtime in my database it seems natural to also implement it into the scripts :)
One thing I miss is the function for counting weeks, datepart("ww") doesn't work as expected with the rules that first day of week is monday, and next year is when the week contains atleast 4 days of next year. :(
This is all the code added together and with a print statement at the end of it so it displays on the page.

&lt;%

function UDate(oldDate)

UDate = DateDiff("s", "01/01/1970 00:00:00", oldDate)

end function



intCurrent_Unix_Time = UDate(Now())



function unUDate(intTimeStamp)

unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")

end function



function formatDate(format, intTimeStamp)

dim unUDate, A



' Test to see if intTimeStamp looks valid. If not, they have passed a normal date

if not (isnumeric(intTimeStamp)) then

if isdate(intTimeStamp) then

intTimeStamp = DateDiff("S", "01/01/1970 00:00:00", intTimeStamp)

else

response.write "Date Invalid"

exit function

end if

end if



if (intTimeStamp=0) then

unUDate = now()

else

unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")

end if



unUDate = trim(unUDate)



dim startM : startM = InStr(1, unUDate, "/", vbTextCompare) + 1

dim startY : startY = InStr(startM, unUDate, "/", vbTextCompare) + 1

dim startHour : startHour = InStr(startY, unUDate, " ", vbTextCompare) + 1

dim startMin : startMin = InStr(startHour, unUDate, ":", vbTextCompare) + 1



dim dateDay : dateDay = mid(unUDate, 1, 2)

dim dateMonth : dateMonth = mid(unUDate, startM, 2)

dim dateYear : dateYear = mid(unUDate, startY, 4)

dim dateHour : dateHour = mid(unUDate, startHour, 2)

dim dateMinute : dateMinute = mid(unUDate, startMin, 2)

dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":", vbTextCompare) + 1, 2)



format = replace(format, "%Y", right(dateYear, 4))

format = replace(format, "%y", right(dateYear, 2))

format = replace(format, "%m", dateMonth)

format = replace(format, "%n", cint(dateMonth))

format = replace(format, "%F", monthname(cint(dateMonth)))

format = replace(format, "%M", left(monthname(cint(dateMonth)), 3))

format = replace(format, "%d", dateDay)

format = replace(format, "%j", cint(dateDay))

format = replace(format, "%h", mid(unUDate, startHour, 2))

format = replace(format, "%g", cint(mid(unUDate, startHour, 2)))



if (cint(dateHour) > 12) then

A = "PM"

else

A = "AM"

end if

format = replace(format, "%A", A)

format = replace(format, "%a", lcase(A))



if (A = "PM") then format = replace(format, "%H", left("0" &amp; dateHour - 12, 2))

format = replace(format, "%H", dateHour)

if (A = "PM") then format = replace(format, "%G", left("0" &amp; cint(dateHour) - 12, 2))

format = replace(format, "%G", cint(dateHour))



format = replace(format, "%i", dateMinute)

format = replace(format, "%I", cint(dateMinute))

format = replace(format, "%s", dateSecond)

format = replace(format, "%S", cint(dateSecond))

format = replace(format, "%L", WeekDay(unUDate))

format = replace(format, "%D", left(WeekDayName(WeekDay(unUDate)), 3))

format = replace(format, "%l", WeekDayName(WeekDay(unUDate)))

format = replace(format, "%U", intTimeStamp)

format = replace(format, "11%O", "11th")

format = replace(format, "1%O", "1st")

format = replace(format, "12%O", "12th")

format = replace(format, "2%O", "2nd")

format = replace(format, "13%O", "13th")

format = replace(format, "3%O", "3rd")

format = replace(format, "%O", "th")



formatDate = format



end function



strDateTime = formatDate("%j %M %Y", UDate(Now()))



response.Write(strDateTime)

%&gt;
Evan Barrett
United States #13: March 26, 2005
I'm using this function in a vbscript and it seems to convert everything to UTC/GMT. Which for me throws everything off by seven hours. Anyone have a way to adjust the time based on the systems time zone settings?
Derek
United States #14: March 30, 2005
Great script. One problem - %G seems to do leading zeros for PM. Just remove the left("0" * bit from that line..
Richard Starr
United Kingdom #15: June 22, 2005
Dear iLoveJackDaniels, did you get round to fixing the monthname bug? I have implimented the change as suggested by Emlyn but i now have an error "Subscript out of range: '[number: 22]'"
B. Jenkins
United States #16: June 27, 2005
Well, I was having the same problem with the "monthname" error. After testing to see what was being passed by the function, I found that the starting points for the month, day, etc. weren't dynamic (meaning they didn't take into account leading zeroes).

You have to check to see where the starting points are and adjust your code accordingly. See my changes below. The function works beautifully for me now.

Please note, that this is an "English US" version that works with ASP and SQL2000.

dim startM : startM = 1
dim startD : startD = InStr(startM, unUDate, "/")+1
dim startY : startY = InStr(startD, unUDate, "/")+1
dim startHour : startHour = InStr(startY, unUDate, " ")+1
dim startMin : startMin = InStr(startHour, unUDate, ":")+1
dim startSec : startSec = InStr(startMin+1, unUDate, ":")+1

dim dateMonth
if startD = 3 then
dateMonth = mid(unUDate, 1, 1)
else
dateMonth = mid(unUDate, 1, 2)
end if

dim dateDay
if startY = 7 then
dateDay = mid(unUDate, startD, 2)
else
dateDay = mid(unUDate, startD, 1)
end if

dim dateYear : dateYear = mid(unUDate, startY, 4)

dim dateHour
if startMin = 15 then
dateHour = mid(unUDate, startHour, 2)
else
dateHour = mid(unUDate, startHour, 1)
end if

dim dateMinute : dateMinute = mid(unUDate, startMin, 2)
dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":") + 1, 2)
B. Jenkins
United States #17: June 27, 2005
Scratch my post above. It must have been the JD talking.

This code should work. If it doesn't, you can shoot me (just kidding).

dim startM : startM = 1
dim startD : startD = InStr(startM, unUDate, "/")+1
dim startY : startY = InStr(startD, unUDate, "/")+1
dim startHour : startHour = InStr(startY, unUDate, " ")+1
dim startMin : startMin = InStr(startHour, unUDate, ":")+1
dim startSec : startSec = InStr(startMin+1, unUDate, ":")+1
dim dateMonth : dateMonth = mid(unUDate, 1, ((startD - 1) - 1))
dim dateDay : dateDay = mid(unUDate, startD, ((startY - 1) - startD))
dim dateYear : dateYear = mid(unUDate, startY, 4)
dim dateHour : dateHour = mid(unUDate, startHour, ((startMin - startHour) - 1))
dim dateMinute : dateMinute = mid(unUDate, startMin, 2)
dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":") + 1, 2)
Jamsey
United Kingdom #18: July 15, 2005
' returns present date in ISO form bare numeric string yyyymmdd
Function buildDateTime()
Dim y
Dim m
Dim d
Dim s
Dim h
Dim min

Dim nowDate
Dim nowTime

nowDate = Date()
nowTime = Time()

logMessage "TimeStamp : " & nowDate, True

y = DatePart("yyyy", nowDate)
m = DatePart("M", nowDate):If Len(m) = 1 Then m = "0" & m
d = DatePart("d", nowDate):If Len(d) = 1 Then d = "0" & d

h = DatePart("h", nowTime):If Len(h) = 1 Then h = "0" & h
min = DatePart("n", nowTime):If Len(min) = 1 Then min = "0" & min
s = DatePart("s", nowTime):If Len(s) = 1 Then s = "0" & s

buildDateTime = y & m & d & h & min & s
End function
Thanx a lot Micha! The cInt errors were driving me crazy hehe
What a PAIN!!!
United States #20: August 8, 2005
Ok guys, here's the script. Copy paste this, it includes all the corrections you need...I hope!! The author should correct his script on his webpage so people dont need to hunt the comments for bug fixes!!!

function formatDate(format, intTimeStamp)
Dim monthname()
Redim monthname(12)
monthname(1) = "January"
monthname(2) = "February"
monthname(3) = "March"
monthname(4) = "April"
monthname(5) = "May"
monthname(6) = "June"
monthname(7) = "July"
monthname(8) = "August"
monthname(9) = "September"
monthname(10) = "October"
monthname(11) = "November"
monthname(12) = "December"

dim unUDate, A

dim OriginalLocale
dim res
OriginalLocale = GetLocale
res = SetLocale("en-gb")

' Test to see if intTimeStamp looks valid. If not, they have passed a normal date
if not (isnumeric(intTimeStamp)) then
if isdate(intTimeStamp) then
intTimeStamp = DateDiff("S", "01/01/1970 00:00:00", intTimeStamp)
else
response.write "Date Invalid"
exit function
end if
end if

if (intTimeStamp=0) then
unUDate = now()
else
unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
end if

unUDate = trim(unUDate)

dim startM : startM = 1
dim startD : startD = InStr(startM, unUDate, "/")+1
dim startY : startY = InStr(startD, unUDate, "/")+1
dim startHour : startHour = InStr(startY, unUDate, " ")+1
dim startMin : startMin = InStr(startHour, unUDate, ":")+1
dim startSec : startSec = InStr(startMin+1, unUDate, ":")+1
dim dateMonth : dateMonth = mid(unUDate, 1, ((startD - 1) - 1))
dim dateDay : dateDay = mid(unUDate, startD, ((startY - 1) - startD))
dim dateYear : dateYear = mid(unUDate, startY, 4)
dim dateHour : dateHour = mid(unUDate, startHour, ((startMin - startHour) - 1))
dim dateMinute : dateMinute = mid(unUDate, startMin, 2)
dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":") + 1, 2)

format = replace(format, "%Y", right(dateYear, 4))
format = replace(format, "%y", right(dateYear, 2))
format = replace(format, "%m", dateMonth)
format = replace(format, "%n", cint(dateMonth))

' Response.Write CStr(cint(dateMonth))
' Response.Flush

format = replace(format, "%F", monthname(cint(dateMonth)))
format = replace(format, "%M", left(monthname(cint(dateMonth)), 3))
format = replace(format, "%d", dateDay)
format = replace(format, "%j", cint(dateDay))
format = replace(format, "%h", mid(unUDate, startHour, 2))
format = replace(format, "%g", cint(mid(unUDate, startHour, 2)))

if (cint(dateHour) > 12) then
A = "PM"
else
A = "AM"
end if
format = replace(format, "%A", A)
format = replace(format, "%a", lcase(A))

if (A = "PM") then format = replace(format, "%H", left("0" & dateHour - 12, 2))
format = replace(format, "%H", dateHour)
if (A = "PM") then format = replace(format, "%G", left("0" & cint(dateHour) - 12, 2))
format = replace(format, "%G", cint(dateHour))

format = replace(format, "%i", dateMinute)
format = replace(format, "%I", cint(dateMinute))
format = replace(format, "%s", dateSecond)
format = replace(format, "%S", cint(dateSecond))
format = replace(format, "%L", WeekDay(unUDate))
format = replace(format, "%D", left(WeekDayName(WeekDay(unUDate)), 3))
format = replace(format, "%l", WeekDayName(WeekDay(unUDate)))
format = replace(format, "%U", intTimeStamp)
format = replace(format, "11%O", "11th")
format = replace(format, "1%O", "1st")
format = replace(format, "12%O", "12th")
format = replace(format, "2%O", "2nd")
format = replace(format, "13%O", "13th")
format = replace(format, "3%O", "3rd")
format = replace(format, "%O", "th")

formatDate = format
res = SetLocale(OriginalLocale)

end function
Dan
United States #21: August 26, 2005
Being used to the Format fuction in VB6/VBA I changed things around a bit. It makes it much easier for me to remember what the parameters are.

function formatDate(format, intTimeStamp)
'Months and Minutes are case sensitive, everything else is not..
'...am/pm needs to be all caps or no caps one or the other..
' Example for January 3, 2005 5:08:43 PM
'%YYYY 2007
'%YY 07
'%MMMM January Case Sensitive
'%MMM Jan Case Sensitive
'%MM 01 Case Sensitive
'%M 1 Case Sensitive
'%DDDD Monday
'%DDD Mon
'%DD 03
'%D 3
'%hh 05
'%h 5
'%mm 08 Case Sensitive
'%m 8 Case Sensitive
'%ss 43
'%s 43
'%AM/PM PM
'%am/pm pm

dim unUDate, A
' Test to see if intTimeStamp looks valid. If not, they have passed a normal date
if not (isnumeric(intTimeStamp)) then
if isdate(intTimeStamp) then
intTimeStamp = DateDiff("S", "01/01/1970 00:00:00", intTimeStamp)
else
response.write "Date Invalid"
exit function
end if
end if

if (intTimeStamp=0) then
unUDate = now()
else
unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
end if

dim dateYear : dateYear = year(unUdate)
dim dateMonth : dateMonth = month(unUdate)
dim dateDay : dateDay = day(unUdate)
dim dateHour : dateHour = hour(unUdate)
dim dateMinute : dateMinute = minute(unUdate)
dim dateSecond : dateSecond = second(unUdate)
dim dateDoW : dateDoW = weekday(unUdate)

'Convert to 24h if am/pm not passed to function then assume 24h format
if dateHour < 13 then
if instr(1,unUdate, "pm",1) <> 0 then
A="PM"
if instr(1,format,"am/pm",1) = 0 then dateHour=dateHour + 12
else
A="AM"
end if
else
A="PM"
if instr(1,format,"am/pm",1) <> 0 then dateHour=dateHour - 12
end if

'make month/day/hour/min/sec 2 digits if not already
if len(cstr(dateMonth)) < 2 then dateMonth="0" & dateMonth
if len(cstr(dateDay)) < 2 then dateDay="0" & dateDay
if len(cstr(dateHour)) < 2 then dateHour="0" & dateHour
if len(cstr(dateMinute)) < 2 then dateMinute="0" & dateMinute
if len(cstr(dateSecond)) < 2 then dateSecond="0" & dateSecond

format = replace(format, "%YYYY", dateYear,1,-1,1)
format = replace(format, "%YY", right(dateYear,2),1,-1,1)

'Months = M (Upper case)
format = replace(format, "%MMMM", monthname(cint(dateMonth)))
format = replace(format, "%MMM", monthname(cint(dateMonth), true))
format = replace(format, "%MM", dateMonth)
format = replace(format, "%M", cint(dateMonth))
format = replace(format, "%DDDD", weekdayname(dateDoW,false,1),1,-1,1)
format = replace(format, "%DDD", weekdayname(dateDoW,true,1),1,-1,1)
format = replace(format, "%DD", dateDay,1,-1,1)
format = replace(format, "%D", cint(dateDay),1,-1,1)
format = replace(format, "%hh", dateHour,1,-1,1)
format = replace(format, "%h", cint(dateHour),1,-1,1)

'Minutes = m (Lower case)
format = replace(format, "%mm", dateMinute)
format = replace(format, "%m", cint(dateMinute))
format = replace(format, "%ss", dateSecond,1,-1,1)
format = replace(format, "%s", cint(dateSecond),1,-1,1)

'AM/PM case returned will be same as case passed
format = replace(format, "%AM/PM", A)
format = replace(format, "%am/pm", lcase(A))

'Ordinal
format = replace(format, "11%O", "11th",1,-1,1)
format = replace(format, "1%O", "1st",1,-1,1)
format = replace(format, "12%O", "12th",1,-1,1)
format = replace(format, "2%O", "2nd",1,-1,1)
format = replace(format, "13%O", "13th",1,-1,1)
format = replace(format, "3%O", "3rd",1,-1,1)
format = replace(format, "%O", "th",1,-1,1)

formatDate = format

end function
Paul
United Kingdom #22: August 26, 2005
thanks Dan :)
wibblewobble
United Kingdom #23: September 9, 2005
awesome, I've hated the lack of unix timestamps in my ASP, cheers.
Ev
United States #24: November 30, 2005
I never have been able to get this to work, even after all the fixes from the comments.

I still get

Invalid procedure call or argument: 'mid'

Ugh. Seems like it would have been great, but I don't have time to troubleshoot it now.
Please post the latest code correction on your main page
it's dan's comment #21
thanks
I wrote a similar formatting function that contain about 98% of the formatting options in PHP's date() function. I came across this posting afterwards and referenced your UDate function for timestamp formatting. You can find my version at http://www.csb7.com/whyblogwhy/index.php/2005/12/15/php-date-style-formatting-for-asp/
HarmJan
Netherlands #27: January 11, 2006
It doesn't take into considderation that it has to convert the date to UTC first...
HarmJan
Netherlands #28: January 11, 2006
I modified it, this one does:

' Function to convert Date Time to Unix Date Time
' Takes locale into consideration
function UDate(oldDate)
'Convert Date to UTC
set oShell = CreateObject("WScript.Shell")
atb = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\" &_
"Control\TimeZoneInformation\ActiveTimeBias"
offsetMin = oShell.RegRead(atb)
utcDate = dateadd("n", offsetMin, oldDate)

'Calculate the difference since 01/01/1970 in seconds
UDate = DateDiff("s", "01/01/1970 00:00:00", utcDate)
end function
theking2
Switzerland #29: January 26, 2006
Odd, for some reason is the date function return only 2 digits for the year at our hoster (swiss german the en-gb locale does not seem to have an influence). Use the Year(unUDate) instead to have a 4 digit year:
dim dateYear : dateYear = Year(unUDate)
tesdev
United Kingdom #30: February 17, 2006
Used code from comment #20

needed to change from
dim dateMonth : dateMonth = mid(unUDate, 1, ((startD - 1) - 1))

dim dateDay : dateDay = mid(unUDate, startD, ((startY - 1) - startD))

to

dim dateMonth : dateMonth = mid(unUDate, startD, ((startY - 1) - startD))

dim dateDay : dateDay = mid(unUDate, 1, ((startD - 1) - 1))

Worked on servers with both US and GB locales.

Used in the form...

formatDate("%Y-%m-%d %H:%i",item.DateLastModified)
Brilliant! Thank you.
Any idea how to get this working in rails?

I have user input from select_datetime which I'd like to convert into a unix integer for saving in the DB. Can't seem to find any info on how to do that in ruby, or rails.
SiN0420
United States #33: June 29, 2006
Can anyone tell me how to just randomly select a month? This is what I tried to copy from this thread:

function getRndMonth()

Dim monthname()
Redim monthname(12)
monthname(1) = "January"
monthname(2) = "February"
monthname(3) = "March"
monthname(4) = "April"
monthname(5) = "May"
monthname(6) = "June"
monthname(7) = "July"
monthname(8) = "August"
monthname(9) = "September"
monthname(10) = "October"
monthname(11) = "November"
monthname(12) = "December"
Randomize
'monthname'
max=12
min=1
mn1 = Int((max-min+1)*Rnd+min)
getRndMonth = mn1
end function
function getRndMonth()

Dim monthname()
Redim monthname(12)
monthname(1) = "January"
monthname(2) = "February"
monthname(3) = "March"
monthname(4) = "April"
monthname(5) = "May"
monthname(6) = "June"
monthname(7) = "July"
monthname(8) = "August"
monthname(9) = "September"
monthname(10) = "October"
monthname(11) = "November"
monthname(12) = "December"
Randomize
'monthname'
max=12
min=1
mn1 = Int((max-min+1)*Rnd+min)
' getRndMonth = mn1
MsgBox monthname(mn1)
end function


getRndMonth()
Ryan Putman
United States #35: July 26, 2006
First off, as other US Citizens before me have said, the date formatting for this assumes the DD/MM/YYYY format.

It screws up on MM/DD/YYYY (typical US format) and really messes up M/D/YYYY (where there's no inforced 0 in the month part or the day part). Same goes for hours with no forced 0.

Also, if you just want the formatDate and dont care about Unix time, you can scrap about the first 20 lines of code.
Here's what I use.
function formatDate(format, intTimeStamp)
dim unUDate, A

unUDate = trim(intTimeStamp)
dim startM : startD = InStr(1, unUDate, "/", vbTextCompare) + 1
dim startY : startY = InStr(startD, unUDate, "/", vbTextCompare) + 1
dim startHour : startHour = InStr(startY, unUDate, " ", vbTextCompare) + 1
dim startMin : startMin = InStr(startHour, unUDate, ":", vbTextCompare) + 1

dim dateMonth
if startD = 2 then
dateMonth = mid(unUDate, 1, 2)
else
dateMonth = mid(unUDate,1,1)
end if
dim dateDay : dateDay = mid(unUDate, startD, 2)
dim dateYear : dateYear = mid(unUDate, startY, 4)
dim dateHour
if startMin - startHour > 2 then
dateHour = mid(unUDate, startHour, 2)
else
dateHour = mid(unUDate,startHour,1)
end if
dim dateMinute : dateMinute = mid(unUDate, startMin, 2)
dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":", vbTextCompare) + 1, 2)

format = replace(format, "%Y", right(dateYear, 4))
format = replace(format, "%y", right(dateYear, 2))
format = replace(format, "%m", dateMonth)
format = replace(format, "%n", cint(dateMonth))
format = replace(format, "%F", getMonthName(cint(dateMonth),false))
format = replace(format, "%M", getMonthName(cint(dateMonth), true))
format = replace(format, "%d", dateDay)
format = replace(format, "%j", cint(dateDay))
format = replace(format, "%h", dateHour)
format = replace(format, "%g", cint(dateHour))

if (cint(dateHour) > 12) then
A = "PM"
else
A = "AM"
end if
format = replace(format, "%A", A)
format = replace(format, "%a", lcase(A))

if (A = "PM") then format = replace(format, "%H", left("0" & dateHour - 12, 2))
format = replace(format, "%H", dateHour)
if (A = "PM") then format = replace(format, "%G", left("0" & cint(dateHour) - 12, 2))
format = replace(format, "%G", cint(dateHour))

format = replace(format, "%i", dateMinute)
format = replace(format, "%I", cint(dateMinute))
format = replace(format, "%s", dateSecond)
format = replace(format, "%S", cint(dateSecond))
format = replace(format, "%L", WeekDay(unUDate))
format = replace(format, "%D", left(WeekDayName(WeekDay(unUDate)), 3))
format = replace(format, "%l", WeekDayName(WeekDay(unUDate)))
format = replace(format, "%U", intTimeStamp)
format = replace(format, "11%O", "11th")
format = replace(format, "1%O", "1st")
format = replace(format, "12%O", "12th")
format = replace(format, "2%O", "2nd")
format = replace(format, "13%O", "13th")
format = replace(format, "3%O", "3rd")
format = replace(format, "%O", "th")

formatDate = format

end function


Function getMonthName(intMonth_IN,blnShort_IN)
dim strMonthNames,arrMonthNames,strMyMonth,arrMyMonth
strMonthNames = "January,JAN|February,FEB|March,MAR|April,APR|May,MAY|June,JUN|July,JUL|August,AUG|September,SEP|October,OCT|November,NOV|December,DEC"
on error resume next
arrMonthNames = split(strMonthNames,"|")
strMyMonth = arrMonthNames(intMonth_IN-1)
arrMyMonth = split(strMyMonth,",")
if err.number <> 0 then
Response.Write("<p class='boldText'>Error getting Month infomation for value (" & intMonth_IN & ")</p>")
Response.end
end if
on error goto 0
if blnShort_IN then
getMonthName = arrMyMonth(1)
else
getMonthName = arrMyMonth(0)
end if
End Function
$d - Day with leading zeroes (01 - 31)

should read:

%d - Day with leading zeroes (01 - 31)
Puppy
United Kingdom #37: October 10, 2006
Great function. Yeah the $d/%d thing threw for a sec too.
TOM
United States #38: November 14, 2006
Thanks this came in handy !
Anil
United States #39: November 28, 2006
I have an time stamp.In Which i want to select the current system date.
Script is like this.
HTMLAnchor("Caption=" & 28).Click
Here 28 is taking.But when i want to execute it should take the current system date
Nice script. Thanks to Micha for CINT fix.
Matt
United Kingdom #41: January 5, 2007
Thanks theking2 @ #29. I was getting a two digit year too until I tried your code.
The rest of the code worked great for me - thanks!
Stoney
Unknown #42: January 15, 2007
Ummm, Instead of all the InStr that are causing so much trouble, why not use some Split Functions???

Dim strDateSplit

strDateSplit = Split(unUDate, " ")

Dim strDate
Dim strTime

strDate = Split(strDateSplit(0), "/")
strTime = Split(strDateSplit(1), ":")

dateMonth = strDate(0)
dateDay = strDate(1)
dateYear = strDate(2)
dateHour = strTime(0)
dateMinute = strTime(1)
dateSecond = strTime(2)
Stoney
Unknown #43: January 15, 2007
An, the base logic for adding leading zeroes is a bit off...

instead of

Left("0" & dateHour - 12, 2))

it should be

Right("00" & dateHour - 12, 2))

Take this example. The dateHour is 22...

Using the first code line with left, you get the 2 left characters of this string "010" Obviously not quite what you want.

Using the second correct form with Right you get the right two characters of this string "0010". Exactly what you want.
Stoney
Unknown #44: January 15, 2007
Also, %H, %h are with leading zeroes and %G, %g is without according to instructions. However the code itself gives the following

%H - with
%h - without
%G - with
%g - without

I had to swith them...
Stoney
Unknown #45: January 15, 2007
Another One... The test for PM is off. >12 wouldn;t make noon a PM, needs to be >= 12
unseen
Unknown #46: January 31, 2007
why so complicated??

dim dateDay : dateDay = DatePart("d",unUDate)
dim dateMonth : dateMonth = DatePart("m",unUDate)
dim dateYear : dateYear = DatePart("yyyy",unUDate)
dim dateHour : dateHour = DatePart("h",unUDate)
dim dateMinute : dateMinute = DatePart("m",unUDate)
dim dateSecond : dateSecond = DatePart("s",unUDate)

format = replace(format, "%Y", right(dateYear, 4))
format = replace(format, "%y", right(dateYear, 2))
format = replace(format, "%m", dateMonth)
format = replace(format, "%n", cint(dateMonth))
format = replace(format, "%F", monthname(cint(dateMonth)))
format = replace(format, "%M", left(monthname(cint(dateMonth)), 3))
format = replace(format, "%d", dateDay)
format = replace(format, "%j", cint(dateDay))
format = replace(format, "%h", dateHour)
format = replace(format, "%g", cint(dateHour))
unseen
Unknown #47: January 31, 2007
and it works for all lcid
Jon
United Kingdom #48: February 8, 2007
Brilliant script. Thank you
SeaDea
Netherlands #49: February 23, 2007
Great Script thanks, this really helps a lot
Adam H
Canada #50: March 1, 2007
This is a fantastic script, but for some reason your "code" window isn't registering lien breaks when you copy and paste it :(
Muy buen código, pana. ¡Como ayuda!! // Great code, buddy! Quite helpful!
Ray
Netherlands #52: March 24, 2007
It doesn't seem to work at exactly midnight. E.g. 3/25/2007 00:00:00 will become 3:03:03, Sunday 25th March, 2007.
Ray
Netherlands #53: March 24, 2007
I fixed the midnight problem by adding the following line just above the dim statements:

If (Len(unUDate) <= 11) Then unUDate = Trim(unUDate) & " 00:00:00"

But, doesn't the month come before the day in UK notation?
Like 03/25/2007?
Ray
Netherlands #54: March 24, 2007
Why not just use the built-in functions like Month(unUDate), Day(unUDate), Year(unUDate), Hour(unUDate), Minute(unUDate), Second(unUDate)?

And why would you use a Unix Date if you unUDate it in formatDate()?
As best as I can tell, here is the function with all the updates from the comments:


function formatDate(format, intTimeStamp)
Dim monthname()
Redim monthname(12)
monthname(1) = "January"
monthname(2) = "February"
monthname(3) = "March"
monthname(4) = "April"
monthname(5) = "May"
monthname(6) = "June"
monthname(7) = "July"
monthname(8) = "August"
monthname(9) = "September"
monthname(10) = "October"
monthname(11) = "November"
monthname(12) = "December"

dim unUDate, A

dim OriginalLocale
dim res
OriginalLocale = GetLocale
res = SetLocale("en-gb")

' Test to see if intTimeStamp looks valid. If not, they have passed a normal date
if not (isnumeric(intTimeStamp)) then
if isdate(intTimeStamp) then
intTimeStamp = DateDiff("S", "01/01/1970 00:00:00", intTimeStamp)
else
response.write "Date Invalid"
exit function
end if
end if

if (intTimeStamp=0) then
unUDate = now()
else
unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
end if

unUDate = trim(unUDate)

'bug fix for midnight problems
If (Len(unUDate) <= 11) Then unUDate = Trim(unUDate) & " 00:00:00"

dim startM : startM = 1
dim startD : startD = InStr(startM, unUDate, "/")+1
dim startY : startY = InStr(startD, unUDate, "/")+1
dim startHour : startHour = InStr(startY, unUDate, " ")+1
dim startMin : startMin = InStr(startHour, unUDate, ":")+1
dim startSec : startSec = InStr(startMin+1, unUDate, ":")+1
dim dateMonth : dateMonth = mid(unUDate, startD, ((startY - 1) - startD))
dim dateDay : dateDay = mid(unUDate, 1, ((startD - 1) - 1))
dim dateYear : dateYear = Year(unUDate)
dim dateHour : dateHour = mid(unUDate, startHour, ((startMin - startHour) - 1))
dim dateMinute : dateMinute = mid(unUDate, startMin, 2)
dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":") + 1, 2)

format = replace(format, "%Y", right(dateYear, 4))
format = replace(format, "%y", right(dateYear, 2))
format = replace(format, "%m", dateMonth)
format = replace(format, "%n", cint(dateMonth))

' Response.Write CStr(cint(dateMonth))
' Response.Flush

format = replace(format, "%F", monthname(cint(dateMonth)))
format = replace(format, "%M", left(monthname(cint(dateMonth)), 3))
format = replace(format, "%d", dateDay)
format = replace(format, "%j", cint(dateDay))
format = replace(format, "%h", mid(unUDate, startHour, 2))
format = replace(format, "%g", cint(mid(unUDate, startHour, 2)))

if (cint(dateHour) > 12) then
A = "PM"
else
A = "AM"
end if
format = replace(format, "%A", A)
format = replace(format, "%a", lcase(A))

if (A = "PM") then format = replace(format, "%H", Right("00" & dateHour - 12, 2))
format = replace(format, "%H", dateHour)
if (A = "PM") then format = replace(format, "%G", left("0" & cint(dateHour) - 12, 2))
format = replace(format, "%G", cint(dateHour))

format = replace(format, "%i", dateMinute)
format = replace(format, "%I", cint(dateMinute))
format = replace(format, "%s", dateSecond)
format = replace(format, "%S", cint(dateSecond))
format = replace(format, "%L", WeekDay(unUDate))
format = replace(format, "%D", left(WeekDayName(WeekDay(unUDate)), 3))
format = replace(format, "%l", WeekDayName(WeekDay(unUDate)))
format = replace(format, "%U", intTimeStamp)
format = replace(format, "11%O", "11th")
format = replace(format, "1%O", "1st")
format = replace(format, "12%O", "12th")
format = replace(format, "2%O", "2nd")
format = replace(format, "13%O", "13th")
format = replace(format, "3%O", "3rd")
format = replace(format, "%O", "th")

formatDate = format
res = SetLocale(OriginalLocale)

end function
I found a problem: Unix timestamp is UTC (timezone GMT without daylight saving), ASP Date is localized... So in example in Italy (GMT+1) in daylight saving period, the function "unUDate" give me a result 2 hour in advance... I found this solution (you have to set your offset from GMT...):

function UDate(oldDate)
Dim od, offset, nd, startDST, endDST
UDate = DateDiff("s", "01/01/1970 00:00:00", oldDate)
od = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
' fill in your known bias here!
offset = 1
' find first Sunday in April
for i = 1 to 7
if weekday("4/" & i & "/" & year(od))=1 then
startDST = cdate("4/" & i & "/" & year(od))
exit for
end if
next
' find last Sunday in October
for i = 31 to 25 step -1
if weekday("10/" & i & "/" & year(od))=1 then
endDST = cdate("10/" & i & "/" & year(od))
exit for
end if
next
' subtract hour from offset if within DST
if cdate(od) >= startDST and cdate(od) < endDST then
offset = offset + 1
end if
nd = dateadd("h", offset*(-1), od)
unUDate = nd
end function

function unUDate(intTimeStamp)
Dim od, offset, nd, startDST, endDST
od = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
' fill in your known bias here!
offset = 1
' find first Sunday in April
for i = 1 to 7
if weekday("4/" & i & "/" & year(od))=1 then
startDST = cdate("4/" & i & "/" & year(od))
exit for
end if
next
' find last Sunday in October
for i = 31 to 25 step -1
if weekday("10/" & i & "/" & year(od))=1 then
endDST = cdate("10/" & i & "/" & year(od))
exit for
end if
next
' subtract hour from offset if within DST
if cdate(od) >= startDST and cdate(od) < endDST then
offset = offset + 1
end if
nd = dateadd("h", offset, od)
unUDate = nd
end function
Sorry UDate fuction was wrong...

function UDate(oldDate)
Dim od, offset, nd, startDST, endDST
od = oldDate
' fill in your known bias here!
offset = 1
' find first Sunday in April
for i = 1 to 7
if weekday("4/" & i & "/" & year(od))=1 then
startDST = cdate("4/" & i & "/" & year(od))
exit for
end if
next
' find last Sunday in October
for i = 31 to 25 step -1
if weekday("10/" & i & "/" & year(od))=1 then
endDST = cdate("10/" & i & "/" & year(od))
exit for
end if
next
' subtract hour from offset if within DST
if cdate(od) >= startDST and cdate(od) < endDST then
offset = offset + 1
end if
nd = dateadd("h", offset*(-1), od)
UDate = DateDiff("s", "01/01/1970 00:00:00", nd)
end function
Worked for me - love it!
Also - really like the clean design of your site - simple, clean, bit of colour - loved it!

Keep it up.
Hugh Abbott
hugh.abbott@bespokelearningtools.com
Matt in Richmond, Virginia
United States #59: August 1, 2007
I like the idea, but decided to modify it to use traditional VB date/time formatting. Here is what I've come up with. I have only tested it as a standalone vbscript, but it should be fairly robust and bullet proof.

You pass usrFormatDateTime two parameters:

* A date (preferably a valid one or it will default to Now()).
* A standardized date/time format, e.g. ddd mm/dd/yyyy

The script uses regular expressions to trap the correct sequences and return a properly formatted date.

Example:

usrFormatDateTime("03/17/2007","dddd MMMM dd, yyyy")

returns Saturday, March 17, 2007


Function usrFormatDateTime(dtmInputDate,strDateTimeFormat)
'Required Parameters:
'
'dtmInputDate : A Date String or Date Value.
'strDateTimeFormat : A String specifying the desired format using Microsoft MSDN standards.
'
'Date/Time Standard Formats - Case-Sensitive.
'********************************************
'M : Months 1-12
'MM : Months 01-12
'MMM : Month Names in three-char abbreviated format
'MMMM : Month Names
'd : Days 1-31
'dd : Days 01-31
'ddd : Day Names in three-char abbreviated format
'dddd : Day Names
'yy : Two-digit Year
'yyyy : Four-digit Year
'h : Hours 1-12, 12-hour format
'hh : Hours 01-12, 12-hour format
'H : Hours 0-23, 24-hour format
'HH : Hours 00-23,24-hour format
'm : Minutes 0-59
'mm : Minutes 00-59
's : Seconds 0-59
'ss : Seconds 00-59
't : AM or PM

'Use Current Date and Time if value passed is not a date.
If Not IsDate(dtmInputDate) then
dtmInputDate = Now()
End if

Dim strFormattedDateTime

'Prepare a regular expression object to manage search and replace of formatting strings.
Dim objFormattedDateRegExp
Set objFormattedDateRegExp = New RegExp
objFormattedDateRegExp.IgnoreCase = False
objFormattedDateRegExp.Global = True

strFormattedDateTime = strDateTimeFormat

'The following presume that Sunday is first day of the week.
'Refer to documentation on the WEEKDAYNAME() and WEEKDAY() functions, to adjust if needed.
Dim intMonth
Dim intDay
Dim intYear
Dim intHour
Dim intMinute
Dim intSecond
Dim strWeekday
Dim strMonth
Dim strAMPM

intMonth = Month(dtmInputDate)
intDay = Day(dtmInputDate)
intYear = Year(dtmInputDate)
intHour = Hour(dtmInputDate)
intMinute = Minute(dtmInputDate)
intSecond = Second(dtmInputDate)
strWeekday = WeekdayName(Weekday(dtmInputDate))
strMonth = MonthName(intMonth)
strAMPM = "AM"

'Replace the Month format.
'************************
objFormattedDateRegExp.Pattern = "MMMM"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, strMonth)
objFormattedDateRegExp.Pattern = "MMM"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, UCase(Left(strMonth,3)))
objFormattedDateRegExp.Pattern = "MM"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, Right("0" & intMonth,2))
'Watch out for m's in the month name or month name abbrev.
objFormattedDateRegExp.Pattern = "(M(?=[^AaBbOo])|M$)~^([Ee]M)"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, intMonth)

'Replace the Day format.
'************************
objFormattedDateRegExp.Pattern = "dddd"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, strWeekday)
objFormattedDateRegExp.Pattern = "ddd"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, UCase(Left(strWeekday,3)))
objFormattedDateRegExp.Pattern = "dd"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, Right("0" & intDay,2))
'Watch out for m's in the day name or day name abbrev.
objFormattedDateRegExp.Pattern = "(d(?=[^EeAaNn])|d$)^([Nn]d|[Ss]d|[Ii]d|[Rr]d)"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, intDay)

'Replace the Year format.
'************************
objFormattedDateRegExp.Pattern = "yyyy"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, intYear)
objFormattedDateRegExp.Pattern = "yy"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, Right(intYear,2))

'Replace the Hour format.
'************************
'24-Hour format
objFormattedDateRegExp.Pattern = "HH"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, Right("0" & intHour,2))
objFormattedDateRegExp.Pattern = "(H(?=[^Uu])|H$)^([Cc]H|[Tt]H)"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, intHour)

'12-Hour format
'At this point, you are done with the intHour formatted in 24-hour time, so drop it to a 12-Hour format.
If intHour > 12 Then
intHour = intHour - 12
strAMPM = "PM"
End If
If intHour = 0 Then
intHour = 12
End If
objFormattedDateRegExp.Pattern = "hh"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, Right("0" & intHour,2))
objFormattedDateRegExp.Pattern = "(h(?=[^Uu])|h$)^([Cc]h|[Tt]h)"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, intHour)

'Replace the Minute format.
'************************
objFormattedDateRegExp.Pattern = "mm"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, Right("0" & intMinute,2))
objFormattedDateRegExp.Pattern = "(m(?=[^AaBbOo])|m$)^([Ee]m)"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, intMinute)

'Replace the Second format.
'************************
objFormattedDateRegExp.Pattern = "ss"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, Right("0" & intSecond,2))
objFormattedDateRegExp.Pattern = "(s(?=[^TtEeUuDdAa])|s$)^([Uu]s|[Ee]s|[Rr]s)"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, intSecond)

'Replace the AM/PM format.
'************************
objFormattedDateRegExp.Pattern = "(t(?=[^HhUuEeOo])|t$)^([Ss]t|[Aa]t|[Pp]t|[Cc]t)"
strFormattedDateTime = objFormattedDateRegExp.Replace(strFormattedDateTime, strAMPM)

usrFormatDateTime = strFormattedDateTime

End Function
Note that in my summary function above, there is a bug that can set the local incorrectly.

' Test to see if intTimeStamp looks valid. If not, they have passed a normal date
if not (isnumeric(intTimeStamp)) then
if isdate(intTimeStamp) then
intTimeStamp = DateDiff("S", "01/01/1970 00:00:00", intTimeStamp)
else
formatDate = ""
'RETURN LOCALE TO ORIGINAL SETTING
SetLocale(OriginalLocale)
exit function
end if
end if
Nerijus
Lithuania #61: January 2, 2008
Matts code works for me. Thank you
Steven Cheshire
Unknown #62: February 10, 2008
I'm trying to call a function in ASP VBScript

<%=Month(Now())%>
Which qives the result for the current month as
1, 2, 3 etc to 12 depending upon the current month.

However, I need the month to be returned as a double number... i.e February to be returned as 02 as opposed to 2 which happens with <%=Month(Now())%>

Any help much appreciated.
seamus
Italy #63: May 22, 2008
tnx very much, very useful!!
sem

Post Your Comment

· Comments with keywords instead of a name have their URLs removed.
· Your email address will not be displayed or shared.

Live Comment Preview

 United States #64: 1 minute ago