【问题标题】:What is the proper date format for this value?该值的正确日期格式是什么?
【发布时间】:2015-07-04 16:40:54
【问题描述】:

我知道如何使用 ParseExact,它将日期作为字符串传递,并将日期格式作为字符串传递。我似乎无法为我的约会找出正确的格式,希望能得到一些帮助。

首先是代码:

For Each row In qryDays

   Dim strFloweredDate As String = row.Field(Of String)("FloweredDate")
   MessageBox.Show(strFloweredDate)
   Dim FloweringDate As Date
   FloweringDate = Date.ParseExact(strFloweredDate, "M/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)

   ' Also tried the following formats
   ' Dim FloweringDate As Date
   ' FloweringDate = Date.ParseExact(strFloweredDate, "M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture)
   ' Dim FloweringDate As Date
   ' FloweringDate = Date.ParseExact(strFloweredDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)
   ' Dim FloweringDate As Date
   ' FloweringDate = Date.ParseExact(strFloweredDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)
   ' Dim FloweringDate As DateTime
   ' FloweringDate = DateTime.ParseExact(strFloweredDate, "M/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture)
   ' Dim FloweringDate As DateTime
   ' FloweringDate = DateTime.ParseExact(strFloweredDate, "M/dd/yyyy h:mm:ss", System.Globalization.CultureInfo.InvariantCulture)
   ' ETC ETC ETC

Next

现在有两张照片。一个显示日期的Messagebox结果,另一个是错误:

如果有人能帮助我选择正确的日期/时间格式,我将不胜感激。

谢谢!

【问题讨论】:

  • 如果你使用ParseExact,你必须指定exact格式。文本清楚地包含一个所有格式字符串都忽略的时间段。使用TryParse 并让它尝试解析为给定文化定义的可能 100 多种格式可能会很好。 How to convert date format in vb.net? 的可能重复项
  • Plutonix 最后两个例子展示了使用 DateTime 而不是 date,我添加了一个时间部分。为什么我知道如何转换它却声称重复,我只是没有你没有提供的特定格式?
  • 抱歉,我的意思是时间部分不完整 - 没有上午/下午

标签: vb.net date datetime datetime-format


【解决方案1】:

我会说:

M/d/yyyy hh:mm:ss tt

tt 是 AM/PM 指示符。

见:Custom Date and Time Format Strings

为了确保您正确处理 d/M M/d 问题,您还可以使用 TryParse 并传递正确的文化:

DateTime result;
culture = CultureInfo.CreateSpecificCulture("en-US");
styles = DateTimeStyles.None;
if (DateTime.TryParse(dateString, culture, styles, out result)) {
   ...
}

【讨论】:

  • 你是 MAN Olivier Jascot-Descombes!谢谢楼主!
【解决方案2】:

您没有告诉我们row 是什么,但鉴于它来自qryDays,我猜它来自数据库中的一条记录。可能是System.Data.DataRow。如果是这样,很有可能您的数据已经属于DateTime 类型,因此您不应该通过String 来使用它。

试试:

Dim FloweredDate As DateTime = row.Field(Of DateTime)("FloweredDate");

请记住,VB.net 中的 Date 关键字是 System.DateTime 的别名,因此这些类型是等价的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 2021-11-30
    • 2013-10-16
    相关资源
    最近更新 更多