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:
<%@LANGUAGE=VBSCRIPT" LCID=2057%>
There is also a [url=http://www.microsoft.com/globaldev/reference/lcid-all.mspx]complete list of valid locales[/url] 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()
function UDate(oldDate)
UDate = DateDiff("s", "01/01/1970 00:00:00", oldDate)
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.
intCurrent_Unix_Time = UDate(Now())
unUDate()
function unUDate(intTimeStamp)
unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
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:
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.
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" & 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

66 Comments
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
#1, Sarah, Australia, 30 March 2004. Reply to this.
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???
#2, Brent, United States, 9 April 2004. Reply to this.
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
#3, dandin, Canada, 17 April 2004. Reply to this.
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" & 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))
#4, Emlyn, Switzerland, 27 April 2004. Reply to this.
Sorry that code isn't easy to read. How do I insert line breaks? <br> will <br> this <br> work?
#5, Emlyn, Switzerland, 27 April 2004. Reply to this.
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.
#6, Dave Child, United Kingdom, 28 April 2004. Reply to this.
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.
#7, Noodles, New Zealand, 25 May 2004. Reply to this.
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
#8, Micha, United States, 27 July 2004. Reply to this.
thanks a lot Micha, that fixed it for me!!
#9, John, United States, 28 September 2004. Reply to this.
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. :(
#10, Tony, Sweden, 17 November 2004. Reply to this.
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. :(
#11, Tony, Sweden, 18 November 2004. Reply to this.
This is all the code added together and with a print statement at the end of it so it displays on the page.
<%
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" & 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
strDateTime = formatDate("%j %M %Y", UDate(Now()))
response.Write(strDateTime)
%>
#12, Peter Samuel, United Kingdom, 30 November 2004. Reply to this.
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?
#13, Evan Barrett, United States, 26 March 2005. Reply to this.
Great script. One problem - %G seems to do leading zeros for PM. Just remove the left("0" * bit from that line..
#14, Derek, United States, 30 March 2005. Reply to this.
Dear Dave, 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]'"
#15, Richard Starr, United Kingdom, 22 June 2005. Reply to this.
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)
#16, B. Jenkins, United States, 27 June 2005. Reply to this.
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)
#17, B. Jenkins, United States, 27 June 2005. Reply to this.
' 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
#18, Jamsey, United Kingdom, 15 July 2005. Reply to this.
Thanx a lot Micha! The cInt errors were driving me crazy hehe
#19, andufo, Ecuador, 19 July 2005. Reply to this.
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
#20, What a PAIN!!!, United States, 8 August 2005. Reply to this.
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
#21, Dan, United States, 26 August 2005. Reply to this.
thanks Dan :)
#22, Paul, United Kingdom, 26 August 2005. Reply to this.
awesome, I've hated the lack of unix timestamps in my ASP, cheers.
#23, wibblewobble, United Kingdom, 9 September 2005. Reply to this.
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.
#24, Ev, United States, 30 November 2005. Reply to this.
Please post the latest code correction on your main page
it's dan's comment #21
thanks
#25, kobi, Israel, 7 December 2005. Reply to this.
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/
#26, Chris Bloom, United States, 15 December 2005. Reply to this.
It doesn't take into considderation that it has to convert the date to UTC first...
#27, HarmJan, Netherlands, 11 January 2006. Reply to this.
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
#28, HarmJan, Netherlands, 11 January 2006. Reply to this.
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)
#29, theking2, Switzerland, 26 January 2006. Reply to this.
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)
#30, tesdev, United Kingdom, 17 February 2006. Reply to this.
Brilliant! Thank you.
#31, Nick Dunn, United Kingdom, 22 February 2006. Reply to this.
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.
#32, dizastor, United States, 17 March 2006. Reply to this.
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
#33, SiN0420, United States, 29 June 2006. Reply to this.
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()
#34, Vennie, Netherlands, 17 July 2006. Reply to this.
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
#35, Ryan Putman, United States, 26 July 2006. Reply to this.
$d - Day with leading zeroes (01 - 31)
should read:
%d - Day with leading zeroes (01 - 31)
#36, lemsx1, United States, 1 September 2006. Reply to this.
Great function. Yeah the $d/%d thing threw for a sec too.
#37, Puppy, United Kingdom, 10 October 2006. Reply to this.
Thanks this came in handy !
#38, TOM, United States, 14 November 2006. Reply to this.
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
#39, Anil, United States, 28 November 2006. Reply to this.
Nice script. Thanks to Micha for CINT fix.
#40, David, United States, 1 December 2006. Reply to this.
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!
#41, Matt, United Kingdom, 5 January 2007. Reply to this.
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)
#42, Stoney, Unknown, 15 January 2007. Reply to this.
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.
#43, Stoney, Unknown, 15 January 2007. Reply to this.
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...
#44, Stoney, Unknown, 15 January 2007. Reply to this.
Another One... The test for PM is off. >12 wouldn;t make noon a PM, needs to be >= 12
#45, Stoney, Unknown, 15 January 2007. Reply to this.
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))
#46, unseen, Unknown, 31 January 2007. Reply to this.
and it works for all lcid
#47, unseen, Unknown, 31 January 2007. Reply to this.
Brilliant script. Thank you
#48, Jon, United Kingdom, 8 February 2007. Reply to this.
Great Script thanks, this really helps a lot
#49, SeaDea, Netherlands, 23 February 2007. Reply to this.
This is a fantastic script, but for some reason your "code" window isn't registering lien breaks when you copy and paste it :(
#50, Adam H, Canada, 1 March 2007. Reply to this.
Muy buen código, pana. ¡Como ayuda!! // Great code, buddy! Quite helpful!
#51, Fhaidel, Venezuela, 24 March 2007. Reply to this.
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.
#52, Ray, Netherlands, 24 March 2007. Reply to this.
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?
#53, Ray, Netherlands, 24 March 2007. Reply to this.
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()?
#54, Ray, Netherlands, 24 March 2007. Reply to this.
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
#55, Randy Syring, Unknown, 3 April 2007. Reply to this.
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
#56, Pisu, Italy, 12 June 2007. Reply to this.
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
#57, Pisu, Italy, 12 June 2007. Reply to this.
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
#58, Hugh Abbott, United Kingdom, 26 June 2007. Reply to this.
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
#59, Matt in Richmond, Virginia, United States, 1 August 2007. Reply to this.
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
#60, Randy Syring, Unknown, 15 August 2007. Reply to this.
Matts code works for me. Thank you
#61, Nerijus, Lithuania, 2 January 2008. Reply to this.
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.
#62, Steven Cheshire, Unknown, 10 February 2008. Reply to this.
tnx very much, very useful!!
sem
#63, seamus, Italy, 22 May 2008. Reply to this.
Hi All,
Is there any function in VB that takes in date as input and returns me a numeric value? I need to compare two dates and say which one is older (or the other way round).. I do not want to take Year/month/day/mins/secs separately and find it out..
Thanks in Advance
#64, Shwetha, Unknown, 20 July 2009. Reply to this.
Dear Matt,
It works nice accept the format of the M.
for example MM (01 to 12) works. but not M (1 to12) works. can some one tell me why?
thanks Matt for the sharing. :)
#65, Tibet News, Canada, 10 September 2009. Reply to this.
Looks like there are a few bugs in the script that Matt provided. Specifically on the lines that deal with the singular format characters(ie. m, d, h, etc.).
#66, Davin Studer, US, 9 December 2009. Reply to this.