问题描述
限时送ChatGPT账号..我想在我的 vbscript 中获取完整格式的日期.例如,我把DateParam = FormatDateTime(Date()-1, 2)
I want to get a date in full format in my vbscript. For example, I put
DateParam = FormatDateTime(Date()-1, 2)
但它返回
3/8/2012
我需要函数返回03/08/2012
代替.
有人知道如何解决这个问题吗?
Does anyone knows how to fix this?
推荐答案
FormatDateTime 函数没用,因为它取决于用户特定的和全局的区域设置.
The FormatDateTime function is useless, because it depends on the user specific and global Regional Settings.
最好的(以最少的努力获得最大的收益)解决方案——利用 .NET——在日期方面存在缺陷;再次是因为对区域设置的依赖.
The best (most gain for least effort) solution - tapping into .NET - is flawed for dates; again because of the dependency on the Regional Settings.
如果您想/需要推出自己的函数,请从 fmtDate() 之类的东西开始.
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)
输出:
Yesterday: 08.03.2012 1033
sprintf (silly) => 03.08.2012
sprintf (clumsy) => 03/08/2012
fmtDate => 03/08/2012
再三考虑:
转义/"有助于使 sprintf() 可用:
Escaping the "/" helps to make sprintf() usable:
WScript.Echo "sprintf (silly me) =>", sprintf("{0:MM\/dd\/yyyy}", Array(dtYesterday))
输出:
sprintf (silly me) => 03/08/2012
所以不要理会 fmt* 函数,而是使用 .NET 格式.
So don't bother with fmt* functions but use .NET formatting.
这篇关于VBS中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论