我想在 dd/M/yyyy hh:mm:ss tt 中显示日期时间,但我收到错误 -
System.FormatException: 'String 未被识别为有效的 DateTime。'
样本数据 12/14/2018 8:11:30 PM
预计 14/12/2018 8:11:30 PM
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;
您需要稍微更改字符串格式,因为您使用的字符串无效。更改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
表示使用 1 位(如果可能)。你还设定tt
其显示AM/PM
与使用时可能会造成问题hh
。
编辑:(根据您的评论)如果updatedDate
是一个DateTime
对象,那么您可以这样做:
var time = updatedDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句