开发者

How to format a datetime with minimal separators and timezone in VBScript?

开发者 https://www.devze.com 2023-01-10 17:32 出处:网络
I have the following code in C#: DateTime dt = GetDateTime(); string formatted = dt.ToString(\"yyyyMMddTHHmmsszz\");

I have the following code in C#:

DateTime dt = GetDateTime();
string formatted = dt.ToString("yyyyMMddTHHmmsszz");

which returns a date in the following format:

20100806T112917+01

I would like to be able to get the same results in VBScript (for a legacy ASP applica开发者_开发问答tion). It is especially important that I get the UTC offset information, or have the time converted to UTC.

How do I do that?


For date formatting, I like using the .NET StringBuilder class from VBScript:

Option Explicit

Dim sb : Set sb = CreateObject("System.Text.StringBuilder")
sb.AppendFormat "{0:yyyyMMddTHHmmsszz}", Now()
Response.Write sb.ToString()

The above returns:

20100806T201139-07

This assumes that you have .NET installed on your web server.


Here's my own attempt. Better solutions will be graciously accepted!

Function ToDateTimeStringMinimalSeparators(dateTime)

    ' --------------------------------------------------------------------------
    '  F O R M A T   T H E   U T C   O F F S E T
    ' --------------------------------------------------------------------------

    Dim oShell, activeTimeBias
    Set oShell = CreateObject("WScript.Shell")
    activeTimeBias = oShell.RegRead("HKEY_LOCAL_MACHINE\System\" & _
        "CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")

    Dim sign
    sign = "-"
    If activeTimeBias < 0 Then
        sign = "+"
        ' Make it positive while we're doing calculations
        activeTimeBias = activeTimeBias * -1
    End If

    Dim atbHours, atbMins
    atbHours = Right("00" & Int(activeTimeBias / 60), 2)
    atbMins = Right("00" & (activeTimeBias Mod 60), 2)
    If atbMins = "00" Then
        atbMins = ""
    End If

    Dim utcOffset
    utcOffset = sign & atbHours & atbMins

    ' --------------------------------------------------------------------------
    '  F O R M A T   T H E   M A I N   D A T E
    ' --------------------------------------------------------------------------

    Dim dateBody
    dateBody = Right("0000" & Year(dateTime), 4) & _
        Right("00" & Month(dateTime), 2) & _
        Right("00" & Day(dateTime), 2) & _
        "T" & _
        Right("00" & Hour(dateTime), 2) & _
        Right("00" & Minute(dateTime), 2) & _
        Right("00" & Second(dateTime), 2)

    ToDateTimeStringMinimalSeparators = dateBody & utcOffset

End Function
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号