AMDI
AMDI

Reputation: 973

getting issue with conversion from string to DateTime

I am getting issue while converting string to DateTime.

The value I am receiving as "08-26-2015 10:14:57.898Z".

I am trying to convert the above string to DateTime.

My Code:

DateTime.ParseExact(element.Value,"MM/dd/yyyy HH:mm:ss",CultureInfo.CurrentCulture);

Exception: String was not recognized as a valid DateTime.

Upvotes: 2

Views: 89

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use:

DateTime dt = DateTime.ParseExact("08-26-2015 10:14:57.898Z", "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);

If you use CultureInfo.CurrentCulture(or null) the slash / has a special meaning. It is replaced with the current culture's date separator. Since that is not - but / in US you get an exception. Read

Upvotes: 2

M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

You have string with different format than you trying for conversion.

Try this

var input = "08-26-2015 10:14:57.898Z";
var date = DateTime.ParseExact(input, "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);

Upvotes: 2

Dmitry VS
Dmitry VS

Reputation: 615

String s = "08-26-2015 10:14:57.898Z";
DateTime date;
DateTime.TryParse (s, out date);

Now date variable contains DateTime value you need.

Upvotes: 0

Pomme De Terre
Pomme De Terre

Reputation: 372

Have you tried Convert.ToDateTime ? I just tried with your string and it works fine :

var s = "08-26-2015 10:14:57.898Z";
var date = Convert.ToDateTime(s);

Upvotes: 0

Related Questions