DateTime 从当前文化中获取代表日、月、年的字母

DateTime get the letters representing day, month, year from the currentculture

我想编写一个方法,根据日期时间格式为我提供 3 个字母 - 代表日、月、年。

所以在 en-US 文化中,我想要的 return 值是(加上分隔符)

在de-DE中同样的方法应该return

我查看了 DateTimeFormatInfo class form CurrentCulture 但只能找到分隔符 你知道我怎样才能得到其余的吗?

var culture = Thread.CurrentThread.CurrentCulture;
Console.WriteLine(culture.DateTimeFormat.DateSeparator);

我需要这个,因为 Excel 中的 TEXT 函数不接受来自 InvariantCulture 的格式,只处理它来自当前文化。

所以这样的东西在德语 Excel 版本中无效:

=TEXT(NOW();"dd.MM.yyyy")

这个需要设置

=TEXT(NOW();"TT.MM.JJJJ")

(如果用 VBA 完成并不重要,它不会被翻译) 你可以看看下面的http://www.rondebruin.nl/win/s9/win013.htm

字符串格式可以是任何格式,用户可以随意输入,我需要将其翻译成当前的文化。

您可以在 VBA 中执行此操作: DateTimeStrings 将 return 日期代码和分隔符的数组。

Option Explicit
Function DateTimeStrings() As Variant
    Dim s(3)
    With Application
        s(0) = .International(xlDayCode)
        s(1) = .International(xlMonthCode)
        s(2) = .International(xlYearCode)
        s(3) = .International(xlDateSeparator)
    End With

DateTimeStrings = s

Debug.Print s(0), s(1), s(2), s(3)

End Function

编辑: 我不确定你想如何使用它,但是,例如,插入一个类似于你上面的公式,(例如:=TEXT(A1,"dd/mm/yyy") 在 B1 和适当的语言中,您可以 select A1 和 运行 以下宏:

=============================================

Sub AddTextFunction()
    Dim R As Range, C As Range
    Dim sFormula As String
    Dim V As Variant
     Dim D As String, M As String, Y As String, sep As String

Set R = Selection

For Each C In R
    V = DateTimeStrings()
        D = V(0)
        M = V(1)
        Y = V(2)
        sep = V(3)

    sFormula = "=text(RC[-1],""" & D & D & sep & M & M & sep & Y & Y & Y & """)"
    C.Offset(0, 1).FormulaR1C1 = sFormula
Next C

End Sub

============================================= ======