Sachin Kainth
Sachin Kainth

Reputation: 46740

DateTime.Parse date format

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

Upvotes: 12

Views: 16091

Answers (3)

SLaks
SLaks

Reputation: 887285

You need to specify a format:

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

Upvotes: 16

Jacek
Jacek

Reputation: 12053

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
}

Upvotes: 4

Khan
Khan

Reputation: 18142

Try DateTime.ParseExact

var dt = DateTime.ParseExact("20130116154407", "yyyyMMddhhmmss", CultureInfo.InvariantCulture);

Upvotes: 2

Related Questions