Gashio Lee
Gashio Lee

Reputation: 129

How to fix error from formatting a Date from DB

I've encountered a problem when trying to parse a data from the DB.

The data I have for example is: 2019-04-19T00:00:00.000Z

I'm trying to get it to the format of dd/MM/yyyy but I'm encountering the error:

String was not recognized as a valid DateTime.

Here's my code block

string x = DateTime.ParseExact("2019-04-19T00:00:00.000Z","'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");

Am I specifying the wrong format? Or are there any other ways of doings this?

Upvotes: 1

Views: 179

Answers (4)

NDJ
NDJ

Reputation: 5194

you can also just parse it -

var x = DateTime.Parse("2019-04-19T00:00:00.000Z",
     CultureInfo.InvariantCulture, 
     DateTimeStyles.RoundtripKind).ToString("dd/MM/yyyy");

Upvotes: 0

Swati Keshri
Swati Keshri

Reputation: 9

Check this:

string x = DateTime.ParseExact("2019-04-19T00:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture).ToString("dd//yyyy");

Upvotes: 0

Milenko Jevremovic
Milenko Jevremovic

Reputation: 1056

DateTime.ParseExact("\"2019-04-19T00:00:00.000Z\"", "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'", null).ToString("dd/MM/yyyy");

that will give you 19/04/2019

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29026

Your format string should be "yyyy-MM-ddTHH:mm:ss.fffZ" instead for "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'" That is, the code should be like this example

string x = DateTime.ParseExact("2019-04-19T00:00:00.000Z","yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");

Upvotes: 1

Related Questions