DateAdd() in Special Format

后端 未结 3 635
星月不相逢
星月不相逢 2020-12-07 06:02

I\'ve tried all the ways I see to add a month to a certain date then return that in a specific format but I\'m at a loss. Here\'s my code but I need to format it:

3条回答
  •  离开以前
    2020-12-07 06:31

    When working with dates, it's especially important to take care of the proper data (sub)types. Feeding a string to a function that expects a date (and relying on 'VBScript - and your local settings - will do the right thing') is dangerous.

    Using replace will never change the order of the date parts.

    FormatDateTime depends on the local/regional settings and should be avoided as a sure path to disaster.

    One way to solve this problem + most of all other problems concerning fancy formatting in VBScript is to use a .Net System.Text.StringBuilder:

    Given Lib.vbs:

    ' Lib.vbs - simple VBScript library/module
    ' use
    '  ExecuteGlobal goFS.OpenTextFile().ReadAll()
    ' to 'include' Lib.vbs in you main script
    
    Class ToBeAShamedOf
      Public a
      Public b
    End Class ' ToBeAShamedOf
    
    Class cFormat
      Private m_oSB
      Private Sub Class_Initialize()
        Set m_oSB = CreateObject("System.Text.StringBuilder")
      End Sub ' Class_Initialize
      Public Function formatOne(sFmt, vElm)
        m_oSB.AppendFormat sFmt, vElm
        formatOne = m_oSB.ToString()
        m_oSB.Length = 0
      End Function ' formatOne
      Public Function formatArray(sFmt, aElms)
        m_oSB.AppendFormat_4 sFmt, (aElms)
        formatArray = m_oSB.ToString()
        m_oSB.Length = 0
      End Function ' formatArray
    End Class ' cFormat
    

    and main.vbs:

    ' main.vbs - demo use of library/module Lib.vbs
    
    ' Globals
    Dim gsLibDir : gsLibDir = ".\"
    Dim goFS     : Set goFS = CreateObject("Scripting.FileSystemObject")
    
    ' LibraryInclude
    ExecuteGlobal goFS.OpenTextFile(goFS.BuildPath(gsLibDir, "Lib.vbs")).ReadAll()
    
    WScript.Quit demoDateFormat()
    WScript.Quit main()
    
    Function main()
      Dim o : Set o = New ToBeAShamedOf
      o.a = 4711
      o.b = "whatever"
      WScript.Echo o.a, o.b
      main = 1 ' can't call this a success
    End Function ' main
    
    Function demoDateFormat()
      Dim sD   : sD       = "2012-05-16 01:02:03" ' near future; not yyyyy!
      Dim dtD  : dtD      = CDate(sD)
      Dim dtDM : dtDM     = DateAdd("m", 1, dtD)
      Dim oFmt : Set oFmt = New cFormat
      WScript.Echo oFmt.formatArray( _
          "   sD: {1}{0}  dtD: {2}{0} dtDM: {3}{0}dtDM': {4}" _
        , Array(vbCrLf, sD, dtD, dtDM, oFmt.formatOne("{0:yyyy-MM-dd hh:mm:ss}", dtDM)))
      demoDateFormat = 0 ' seems to be decent
    End Function ' demoDateFormat
    

    you'll get:

    cscript main.vbs
       sD: 2012-05-16 01:02:03
      dtD: 16.05.2012 01:02:03
     dtDM: 16.06.2012 01:02:03
    dtDM': 2012-06-16 01:02:03
    

    (to be seen in the context of this answer)

提交回复
热议问题