Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Parse date format

Tags:

c#

datetime

I have a date represented as a string thus

20130116154407

I called DateTime.Parse on this but it failed. How can I convert this to a DateTime? Incidentally the timezone is CET.

EDIT

The solutions provided are very useful, so far but it seems they do not support 24 hour clocks, still looking for a solution that does.

EDIT 2

The correct format is

DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)

Thanks,

Sachin

like image 560
Sachin Kainth Avatar asked Jan 16 '13 14:01

Sachin Kainth


People also ask

What formats does DateTime parse?

Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.sssZ ) is explicitly specified to be supported.

How do I convert DateTime to date format?

You can convert a DATETIME to a DATE using the CONVERT function. The syntax for this is CONVERT (datetime, format). This shows the date only and no time.

What is DateTime parsing?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

What is DateTime ParseExact in C#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.


2 Answers

You need to specify a format:

DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)
like image 86
SLaks Avatar answered Sep 27 '22 20:09

SLaks


Use this code

string DATE_FORMAT= "yyyyMMddhhmmss";

DateTime date;
if(DateTime.TryParseExact(str, DATE_FORMAT, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out date))
{
//success
//you can use date
}else
{
//fail
}
like image 27
Jacek Avatar answered Sep 27 '22 19:09

Jacek