【问题标题】:Force date to US format regardless of locale settings无论区域设置如何,都将日期强制为美国格式
【发布时间】:2024-01-06 03:03:01
【问题描述】:

我有一个带有这一行的 VB6 程序:

strDate = Format(Date, "ddmmmyyyy")

根据英语(美国)Windows 的文化设置,我需要它始终以这种格式出现:

17Jul2012

不幸的是,当文化设置为其他内容时,例如法语,我明白了:

17juil2012

有没有办法让日期格式始终使用美式英文格式?

【问题讨论】:

标签: date vb6 localization formatting cultureinfo


【解决方案1】:

与其试图强制执行一种特定于文化的格式,不如将月份名称硬编码成一个简单的函数,如下所示:

Private Function GetEnglishDate(ByVal d As Date) As String
    Dim monthNames
    monthNames = Array("", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
    GetEnglishDate = Day(d) & monthNames(Month(d)) & Year(d)
End Function

用法:

strDate = GetEnglishDate(myDate)

【讨论】:

  • 谢谢,这是一个非常优雅的解决方案。
【解决方案2】:

使用内置的Windows日期格式化功能:

Option Explicit

Private Type SYSTEMTIME
    wYear           As Integer
    wMonth          As Integer
    wDayOfWeek      As Integer
    wDay            As Integer
    wHour           As Integer
    wMinute         As Integer
    wSecond         As Integer
    wMilliseconds   As Integer
End Type

Private Declare Function GetDateFormat Lib "Kernel32" Alias "GetDateFormatW" ( _
    ByVal Locale As Long, _
    ByVal dwFlags As Long, _
    ByRef lpDate As SYSTEMTIME, _
    ByVal lpFormat As Long, _
    ByVal lpDateStr As Long, _
    ByVal cchDate As Long _
) As Long

Private Declare Function VariantTimeToSystemTime Lib "OleAut32.dll" ( _
    ByVal vtime As Date, _
    ByRef lpSystemTime As SYSTEMTIME _
) As Long

Private Sub Command_Click()

    ' Use French Canadian date - should display "mer., juil. 18 12" for today!
    Label.Caption = FormatDateWithLocale("ddd',' MMM dd yy", Now, 3084)

    ' Use United States date - should display "Wed, July 18 12" for today!
    Labe2.Caption = FormatDateWithLocale("ddd',' MMM dd yy", Now, 1033)

End Sub

Private Function FormatDateWithLocale(ByRef the_sFormat As String, ByVal the_datDate As Date, ByVal the_nLocale As Long) As String

    Dim uSystemTime                 As SYSTEMTIME
    Dim nBufferSize                 As Long

    ' Convert to standard Windows time format.
    If VariantTimeToSystemTime(the_datDate, uSystemTime) = 1 Then

        ' Run "GetDateFormat" just to get the size of the output buffer.
        nBufferSize = GetDateFormat(the_nLocale, 0&, uSystemTime, StrPtr(the_sFormat), 0&, 0&)

        If nBufferSize > 0 Then

            ' The buffer size includes the terminating null char, but all VB strings always include this, therefore allocate a buffer with one less character.
            ' Then rerun the GetDateFormat.
            FormatDateWithLocale = Space$(nBufferSize - 1)
            GetDateFormat the_nLocale, 0&, uSystemTime, StrPtr(the_sFormat), StrPtr(FormatDateWithLocale), nBufferSize

        End If

    End If

End Function

只需使用不同的语言环境编号(请参阅http://www.dotnetindex.com/articles/990-List-of-Locale-ID--LCID--Values-as-Assigned-by-Microsoft.asp

日期格式与VB稍有不同(M为月):

http://msdn.microsoft.com/en-us/library/dd317787.aspx

【讨论】: