将字符串转换为日期时间C#

时间:2015-08-03 12:53:03

标签: c# .net string datetime

我是c#的新手,如何将输入字符串转换为DateTime。

_toDate = 5/22/2015

我不能用

DateTime.ParseExact(_toDate, "yyyy-MM-dd", null);

Convert.ToDateTime(_toDate)

抛出异常字符串未被识别为有效的DateTime。

注意:字符串shold与上面相同。

感谢您的回复

1 个答案:

答案 0 :(得分:9)

显然,您的字符串和格式不匹配。

来自documentation;

  

将指定的日期和时间字符串表示形式转换为它   DateTime等效。字符串表示的格式必须   匹配指定格式完全

您需要将M/dd/yyyy/作为DateSeparator InvariantCulture的文化一起使用。

string _toDate = "5/22/2015";
DateTime myDate = DateTime.ParseExact(_toDate, "M/dd/yyyy", CultureInfo.InvariantCulture);

当您使用null作为IFormatProvider时,如果CurrentCulture CurrentCulture没有/作为DateSeparator,则表示FormatException }},您将获得<!-- language: lang-java --> @ResponseStatus(OK) @RequestMapping(value = {"/v1/transform"}, method = RequestMethod.POST) @ResponseBody public TransformIdDTO transformFile(@RequestPart("file") MultipartFile [] multipartFile, @RequestParam("from") String from, @RequestParam("to") String to,final HttpServletResponse response) throws IOException, MessagingException { } ,因为/ custom format specifier具有特殊含义,因为将我替换为当前文化或提供的文化日期分隔符

相关问题