[英]Dynamically formatting date to a datetime object directly from MySQL database
I have a MySQL database with a DATETIME
formatted column, which is populated with the date of the row entry. 我有一个带有
DATETIME
格式的列的MySQL数据库,其中填充了行条目的日期。 This data is formatted in my project as "dd/MM/yyyy hh:mm:ss tt"
. 在我的项目中,此数据的格式为
"dd/MM/yyyy hh:mm:ss tt"
。
I want to convert this date to a datetime object dynamically (from each database entry), but I currently receive the error 我想将此日期动态地(从每个数据库条目中)转换为datetime对象,但是我目前收到此错误
"String was not recognized as a valid DateTime."
“字符串未被识别为有效的DateTime。”
However, if I use the actual outputted string of the date, it does work: 但是,如果我使用日期的实际输出字符串,则可以正常工作:
using System.Globalization;
var date = DateTime.ParseExact("11/12/2013 11:13:45 PM",
"dd/MM/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
But if I dynamically add the date, it doesn't work: 但是,如果我动态添加日期,它将无法正常工作:
using System.Globalization;
var dt = item.Timestamp;
var date = DateTime.ParseExact(dt,
"dd/MM/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
If I were to output the dt
variable it would display as "11/13/2013 11:13:21 PM"
. 如果我要输出
dt
变量,它将显示为"11/13/2013 11:13:21 PM"
。
Can anyone see why my dynamic dates aren't being recognised? 谁能看到为什么我的动态日期未被识别?
Actually, your problem is the day-month order. 实际上,您的问题是日月订单。
At the end you said the date displays as "11/13/2013 11:13:21 PM"
. 最后,您说日期显示为
"11/13/2013 11:13:21 PM"
。
In this case, you need to parse in this correct order; 在这种情况下,您需要以正确的顺序进行解析。 it errors because there's no month 13.
因为没有月份13而出现错误。
So, make the format be "MM/dd/yyyy hh:mm:ss tt"
. 因此,将格式设置为
"MM/dd/yyyy hh:mm:ss tt"
。
In other words, you wouldn't have noticed this problem yesterday! 换句话说,您昨天不会注意到这个问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.