如何在C#中将日期与'T'转换为/从字符串转换

And*_*ron 11 c# datetime

我使用以下函数DateTime从/转换为string:

DATE_OBJ.ToString(DATE_FORMAT);

DateTime.ParseExact(Date_string, DATE_FORMAT, null);
Run Code Online (Sandbox Code Playgroud)

现在我必须使用以下格式 2012-03-20T14:18:25.000+04:00

我应该使用哪种格式将其正确转换为stringstringDateTime对象生成?

Mor*_*iya 14

你可以从DateTime转到那种格式

DateTime dt = new DateTime();
dt.ToString("o");
Run Code Online (Sandbox Code Playgroud)

从那种格式到DateTime with

DateTimeOffset.Parse(dateString);
Run Code Online (Sandbox Code Playgroud)

以下是DateTime格式的更多信息:http: //www.dotnetperls.com/datetime-format


Hab*_*bib 6

你最好使用DateTimeOffSet,如:

string str = " 2012-03-20T14:18:25.000+04:00";
DateTimeOffset dto = DateTimeOffset.Parse(str);
//Get the date object from the string. 
DateTime dtObject = dto.DateTime; 

//Convert the DateTimeOffSet to string. 
string newVal = dto.ToString("o");
Run Code Online (Sandbox Code Playgroud)