简体   繁体   English

如何将字符串转换为特定的DateTime格式?

[英]How to convert string to a particular DateTime format?

Hi I'm converting a string to DateTime variable but getting exception. 嗨,我正在将字符串转换为DateTime变量,但出现异常。 Please tell me what is wrong in this method? 请告诉我这种方法有什么问题?

string str = "24-04-2014T15:18:18";
DateTime dtStartDateTime = DateTime.ParseExact(stime, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);

Exception is: 例外是:

String was not recognized as a valid DateTime. 无法将字符串识别为有效的DateTime。

Use dd-MM-yyyyTHH:mm:ss format instead. 请改用dd-MM-yyyyTHH:mm:ss格式。 Your string and format doesn't match exactly. 您的字符串和格式不完全匹配。

From DateTime.ParseExact method DateTime.ParseExact方法

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. 使用指定的格式和特定​​于区域性的格式信息,将日期和时间的指定字符串表示形式转换为其等效的DateTime。 The format of the string representation must match the specified format exactly. 字符串表示形式的格式必须与指定的格式完全匹配。

string str = "24-04-2014T15:18:18";
DateTime dtStartDateTime = DateTime.ParseExact(str,
                                    "dd-MM-yyyyTHH:mm:ss",
                                     CultureInfo.InvariantCulture);

Here a demonstration . 这里有demonstration

By the way, I think your stime should be str :) 顺便说一句,我认为你的stime应该是str :)

OK, so if I am understanding the question, I think this is what you need: 好的,如果我理解这个问题,我认为这是您需要的:

string str = "24-04-2014T15:18:18";
DateTime dtStartDateTime = DateTime.ParseExact(str, "dd-MM-yyyyTHH:mm:ss", CultureInfo.InvariantCulture);
string stime = dtStartDateTime.ToString("yyyy-MM-ddTHH:mm:ss");

This will take the text from the first format and give you the second format. 这将采用第一种格式的文本,并为您提供第二种格式。

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

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