How to format a datetime with minimal separators a

2019-05-08 21:18发布

问题:

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 application). It is especially important that I get the UTC offset information, or have the time converted to UTC.

How do I do that?

回答1:

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.



回答2:

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