【问题标题】:how to convert mm/dd/yyyy format to dd/mm/yyyy in c# [duplicate]如何在c#中将mm/dd/yyyy格式转换为dd/mm/yyyy [重复]
【发布时间】:2019-05-15 15:50:26
【问题描述】:

我想在 dd/M/yyyy hh:mm:ss tt 中显示日期时间,但我收到错误 -

System.FormatException: '字符串未被识别为有效 日期时间。'

样本数据 2018 年 12 月 14 日晚上 8:11:30

预期操作 2018 年 12 月 14 日晚上 8:11:30

C#代码

DateTime dt = DateTime.ParseExact(data.updatedDate.ToString(), "MM/dd/yyyy hh:mm:ss tt",CultureInfo.InvariantCulture);
                string time = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
                ViewBag.attendance_time = time;

【问题讨论】:

  • 解析日期时使用h:mm:ss而不是hh:mm:ss格式字符串。
  • DateTime dt = DateTime.ParseExact("12/14/2018 8:11:30 PM", "MM/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); string time = dt.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
  • data.updatedDate的类型是什么?
  • 数据类型 - 日期时间
  • @krishnamohanrao 那你只需要string time = data.updatedDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

标签: c# datetime


【解决方案1】:

您需要稍微更改字符串格式,因为您使用的字符串无效。将hh 更改为h

DateTime dt = DateTime.ParseExact(data.updatedDate.ToString(), "MM/dd/yyyy h:mm:ss tt",CultureInfo.InvariantCulture);

如果您传递的字符串可以包含单个数字的月份或日期,那么您应该使用以下内容:

"M/d/yyyy h:mm:ss tt"

如果月份和日期总是有 2 位数字,那么您可以使用:

"MM/dd/yyyy h:mm:ss tt"

hh 表示每小时使用 2 位数字,h 表示使用一位(如果可能)。您还设置了tt,它显示AM/PM,当与hh 一起使用时可能会导致问题。

编辑:(来自您的 cmets)如果 updatedDateDateTime 对象,那么您可以这样做:

var time = updatedDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

【讨论】:

  • 时间出现错误 - 2018 年 12 月 8 日下午 12:43:12
  • 您正在使用 ParseExact... 您需要传递您传入的日期字符串的确切格式。如果日期可以是单个数字,则应使用 "MM/d/yyyy h:mm:ss tt"
【解决方案2】:

使用 h:m:s 代替 hh:mm:ss。 “hh”表示小时应写为 2 位数字。所以它期望 08 而不是 8。分钟和秒相同。

【讨论】:

  • 字符串未被识别为有效的日期时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多