User987
User987

Reputation: 3825

Converting string date into specific date time format

I have a date time format in a string like following:

start date:

2018/06/30 23:00

and end date:

2018/07/01 19:32

And now I would like to convert this string into format like this:

2017-02-11T19:58:18.918Z

Both the start and end date should be in this date - string format

I have tried something like this:

   var properStart = DateTimeOffset.ParseExact(startdate, "yyyy-MM-dd'T'HH:mm:sszzz",
                                                       CultureInfo.InvariantCulture).ToString();
   var properEnd = DateTimeOffset.ParseExact(enddate, "yyyy-MM-dd'T'HH:mm:sszzz",
                                                CultureInfo.InvariantCulture).ToString();

But this gives me an error like following:

Additional information: String was not recognized as a valid DateTime.

What am I doing wrong here??

Upvotes: 0

Views: 118

Answers (1)

David
David

Reputation: 219127

You're trying to parse this string:

"2018/06/30 23:00"

Specifying this format:

"yyyy-MM-dd'T'HH:mm:sszzz"

That format doesn't match that string, so the parsing fails. Parse from the format that the input is in:

var properStart = DateTimeOffset.ParseExact(startdate, "yyyy/MM/dd HH:mm",
                                                   CultureInfo.InvariantCulture)

Then output into the format you want:

var properStartOutput = properStart.ToString("yyyy-MM-dd'T'HH:mm:sszzz");

Or, if you really want it all in one line:

var properStart = DateTimeOffset.ParseExact(startdate, "yyyy/MM/dd HH:mm",
                                                   CultureInfo.InvariantCulture).ToString("yyyy-MM-dd'T'HH:mm:sszzz").

The point is that parsing input and formatting output are two different operations.

Upvotes: 3

Related Questions