Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

vbscript - date format in VBS

I want to get a date in full format in my . For example, I put
DateParam = FormatDateTime(Date()-1, 2)

But it returns

3/8/2012
I need to function to return
03/08/2012 instead.

Does anyone knows how to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The FormatDateTime function is useless, because it depends on the user specific and global Regional Settings.

The best (most gain for least effort) solution - tapping into .NET - is flawed for dates; again because of the dependency on the Regional Settings.

If you want/need to roll your own function, start with something like fmtDate().

Dim g_oSB : Set g_oSB = CreateObject("System.Text.StringBuilder")

Function sprintf(sFmt, aData)
   g_oSB.AppendFormat_4 sFmt, (aData)
   sprintf = g_oSB.ToString()
   g_oSB.Length = 0
End Function

Function fmtDate(dtX)
  fmtDate = Join(Array(           _
       Right(100 + Month(dtX), 2) _
     , Right(100 +   Day(dtX), 2) _
     ,              Year(dtX)     _
  ), "/")
End Function

Dim dtYesterday : dtYesterday = Date() - 1
WScript.Echo "Yesterday:", dtYesterday, GetLocale()
WScript.Echo "sprintf (silly)  =>", sprintf("{0:MM/dd/yyyy}", Array(dtYesterday))
WScript.Echo "sprintf (clumsy) =>", sprintf("{0:MM}/{0:dd}/{0:yyyy}", Array(dtYesterday))
WScript.Echo "fmtDate          =>", fmtDate(dtYesterday)

output:

Yesterday: 08.03.2012 1033
sprintf (silly)  => 03.08.2012
sprintf (clumsy) => 03/08/2012
fmtDate          => 03/08/2012

On second thought:

Escaping the "/" helps to make sprintf() usable:

WScript.Echo "sprintf (silly me)  =>", sprintf("{0:MM/dd/yyyy}", Array(dtYesterday))

output:

sprintf (silly me)  => 03/08/2012

So don't bother with fmt* functions but use .NET formatting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...