MartGriff
MartGriff

Reputation: 2851

Convert String to Datetime C#

I have a string value which is a datetime : "20100825161500" and I want to convert this to a System Datetime. I have tried Convert.ToDateTime and DateTime.Parse and these do not work.

Upvotes: 5

Views: 537

Answers (3)

Giorgi
Giorgi

Reputation: 30873

You can use DateTime.ParseExact to pass the format you need.

Here is an example:

var parsed = DateTime.ParseExact("20100825161500","yyyyMMddHHmmss", null);

Possible format values are listed at Standard Date and Time Format Strings and Custom Date and Time Format Strings

Upvotes: 14

Jonathan
Jonathan

Reputation: 12025

Try to use something like this

Datetime D = DateTime.ParseExact("20100825161500","yyyymmdd...",null)

here you have a link about how to make you "format" string

Upvotes: 4

Emidee
Emidee

Reputation: 1275

Because this string hasn't a format recognized by these 2 functions.

DateTime.Parse and Convert.ToDateTime require your string to be correctly formatted : http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

http://msdn.microsoft.com/en-us/library/xhz1w05e.aspx

You will have to write your custom parser for this kind of conversion

Upvotes: -2

Related Questions