简体   繁体   English

字符串未被识别为有效的DateTime c#Xamarin

[英]String was not recognized as a valid DateTime c# Xamarin

 string createddate = "10/14/2016 11:46 AM";
 DateTime date = Convert.ToDateTime(createddate);

I am trying to convert string as a datetime format it is working some devices, some devices throwing above exception. 我正在尝试将字符串转换为日期时间格式,它正在某些设备上工作,某些设备抛出上述异常。 whys ? 为什么呢? please help me to resolve this issue. 请帮助我解决此问题。

The problem is that each device will potentially have a different culture . 问题在于,每种设备都可能具有不同的文化 You can ignore the culture and force it to recognize a specific date format in your string: 您可以忽略区域性,并强制其识别字符串中的特定日期格式:

DateTime date = DateTime.ParseExact(
    createddate , "MM/dd/yy HH:mm tt", CultureInfo.InvariantCulture);

See MSDN for standard date string formats and custom date string formats . 有关标准日期字符串格式自定义日期字符串格式,请参见MSDN。

Try this: 尝试这个:

 string createddate = "10/14/2016 11:46 AM";
   DateTime dateTime;
   DateTime.TryParse(createddate, out dateTime);

You need to define the date and time format when you convert a string to a DateTime value. string转换为DateTime值时,需要定义日期和时间格式。 Guessing the default format or hoping the format is correct will lead to diffent kind of bugs. 猜测默认格式或希望格式正确将导致各种各样的错误。 That's one of the most common sources of the bugs which can't be reproduced on the developer's machine . 这是无法在开发人员的机器上复制的错误的最常见来源之一。

Example to do it right: 正确执行的示例:

var date = DateTime.ParseExact("10/14/2016 11:46 AM", 
                               "MM/dd/yyyy HH:mm tt", 
                                CultureInfo.InvariantCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM