Spiek
Spiek

Reputation: 11

Parsing format to DateTime

I want to format a DateTime to the following format yyyy-MM-ddTHH:mm:ssZ but keeping it in DateTime.

This is what I tried:

string t = Convert.ToString(DateTime.UtcNow);
DateTime d2 = DateTime.ParseExact(t, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);

But I am getting the following error :

System.FormatException: 'The string was not recognized as a valid DateTime value.'

this is the result where I want to get: 2018-09-05T09:29:56Z

How can I solve this problem?

Upvotes: 0

Views: 440

Answers (2)

Antoine V
Antoine V

Reputation: 7204

DateTime is just a primitive type, and you rather convert it to the format you want.

The format is just a presentation of your DateTime type

string t = Convert.ToString(DateTime.UtcNow); // it gives you a string like 9/5/2018 9:38:40 AM
DateTime d2 = DateTime.ParseExact(t, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);

Obliviously, the format you put doesn't correspond with the string t

Try this

//to have the right format
var t = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); //it gives 2018-09-05T09:44:14Z

//to convert a string with a format given
DateTime.ParseExact("2018-09-09:38:40Z", "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29006

No you cannot do that, If your requirement is to display the Date object in localized format, then you can make use of the Overrided .ToString() method like the following:

string formatString = "yyyy-MM-ddTHH:mm:ssZ";
DateTime utcDate = DateTime.UtcNow;
string formatedDate = utcDate.ToString(formatString) 

Read more about Standard Date and Time Format Strings

Upvotes: 1

Related Questions