【问题标题】:Convert mm/dd/yyyy to yyyymmdd (VB.NET)将 mm/dd/yyyy 转换为 yyyymmdd (VB.NET)
【发布时间】:2011-10-15 02:12:52
【问题描述】:

有什么方法可以将日期格式:dd/mm/yyyy 转换为 yyyymmdd 格式?例如:从 25/07/2011 到 20110725?在 VB.NET 中?

【问题讨论】:

    标签: vb.net vb.net-2010


    【解决方案1】:

    日期本身并没有 格式。您可以将字符串解析为DateTime,方法是使用dd/MM/yyyy 格式解析它,然后使用yyyyMMdd 格式将其转换为字符串:

    DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
                                        CultureInfo.InvariantCulture);
    
    string reformatted = date.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
    

    或者在 VB 中:

    Dim date as DateTime = DateTime.ParseExact(text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
    Dim reformatted as String = date.ToString("yyyyMMdd", CultureInfo.InvariantCulture)
    

    (并确保您有 System.Globalization 的导入。)

    但是,理想情况下,您应该尽可能长时间地将其保留为 DateTime(或类似名称)。

    【讨论】:

    • 乔恩,只是好奇这个。为什么他不能使用String.Format方法?
    • @reggie:第二行?他可以,但这将是 IMO 的更多工作。当您只想格式化单个值时,为什么要指定复合字符串格式说明符?
    • 感谢您的提示,我错过了第二行!
    • 我在 vb.net 中完全没有成就,所以请不要将此视为批评,因为这只是一个问题..可能是我遗漏的东西。从语义的角度来看,我对整个文化部分所指的内容有所了解,但从句法的角度来看,它似乎完全......当我尝试将其输入到 .net 的 SSIS IDE 时,它似乎完全不被接受。我错过了什么?
    • @Isaac:我对 SSIS IDE 一无所知,但最初的答案只有 C#,而不是 VB。我现在也提供了一个VB版本。确保您已导入 System.Globalization 命名空间。
    【解决方案2】:
     CDate(Datetext).ToString("yyyyMMdd")
    

    【讨论】:

    • 这个答案可能会失败,具体取决于文化。这就是为什么乔恩的答案比这个更好。例如,如果没有 ParseExact,如何确定 10/12/2017 是 12 月 10 日还是 10 月 12 日?
    【解决方案3】:

    使用DateTime.ParseExact方法解析日期,然后使用DateTimeObj.ToString("yyyyMMdd")

    DaTeTime.ParseExact

    【讨论】:

      【解决方案4】:
      Public Function DateFormateYYYYMMDD(ByVal Dtp As DateTimePicker) As String
      
         Try
            Dim StrDate, StrYear, StrMonth, StrDay As String
            StrDate = FormatDateTime(Dtp.Value, DateFormat.ShortDate)
            StrMonth = Month(Dtp.Value)
            StrDay = Convert.ToString(Dtp.Value.Day)
            StrYear = Year(Dtp.Value)
            StrDate = StrYear + "-" + StrMonth + "-" + StrDay
      
            Return StrDate
         Catch ex As Exception
      
         End Try
      End Function
      

      此函数可用于将日期时间选择器值格式转换为 yyyyMMdd

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2011-04-09
        相关资源
        最近更新 更多