VBS中的日期格式

编程入门 行业动态 更新时间:2024-10-26 12:35:32
本文介绍了VBS中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-28 00:44:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1164494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   格式   VBS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!