Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert date with 'T' to/from string in C#

Tags:

c#

datetime

I used following functions to convert DateTime from/into string:

DATE_OBJ.ToString(DATE_FORMAT);

DateTime.ParseExact(Date_string, DATE_FORMAT, null);

Now I've got to work with follow format 2012-03-20T14:18:25.000+04:00

Which format should I use to convert it correctly to string and generate string like that from DateTime object?

like image 338
Andron Avatar asked Jan 10 '13 06:01

Andron


People also ask

What is the T in a DateTime string?

The T is just a literal to separate the date from the time, and the Z means “zero hour offset” also known as “Zulu time” (UTC). If your strings always have a “Z” you can use: SimpleDateFormat format = new SimpleDateFormat( “yyyy-MM-dd'T'HH:mm:ss).

How do I convert a date to a string in SQL?

In order to convert a DateTime to a string, we can use CONVERT() and CAST() function. These functions are used to converts a value(of any datatype) into a specified datatype.


3 Answers

You cannot do this from DateTime, as DateTime holds no TimeZone info.

This is close: string.Format("{0:s}", dt) will give 2012-03-20T14:18:25. See: http://www.csharp-examples.net/string-format-datetime/

You could extend this to: string.Format("{0:s}.{0:fff}", dt), which will give 2012-03-20T14:18:25.000

But you better have a look at DateTimeOffset: DateTime vs DateTimeOffset

(Not advisable, but to fake it and still use DateTime: string.Format("{0:s}.{0:fff}+04:00", dt))

like image 155
Jacco Avatar answered Oct 08 '22 23:10

Jacco


You can go from DateTime to that format with

DateTime dt = new DateTime();
dt.ToString("o");

and from that format to DateTime with

DateTimeOffset.Parse(dateString);

Here is some more info on DateTime format: http://www.dotnetperls.com/datetime-format

like image 16
Moriya Avatar answered Oct 10 '22 02:10

Moriya


You are better of using DateTimeOffSet like:

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");
like image 8
Habib Avatar answered Oct 10 '22 03:10

Habib