-1

I have a string like this

"10/22/2012 9:13:15 PM". 

I want to parse it to DateTime Format like this format

"2012-10-22T21:13:15+00:00"

This is my code.

string startTime = "10/22/2012 9:13:15 PM";

Datetime date = DateTime.ParseExact(
  startTime, 
 "yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK", 
  CultureInfo.InvariantCulture, 
  DateTimeStyles.None);

But it generates this exception.

System.FormatException: String '10/22/2012 5:00:00 PM' was not recognized as a valid DateTime.

How to solve it?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Your format specifies all characters that MUST be in the string. Your string input must look like `"2012’-‘10’-‘20’T’09’:’13’:’15.fffffffK"` ... and whatever fffffffK is - look UP the format strings and fix it to suit your given input. – Patrick Artner Apr 12 '23 at 05:37
  • When it's a `DateTime`, it *doesn't have a format*. It instead is just wrapping an integer counting the number of 100ns intervals since its epoch date. Don't confuse *data* with *presentation*. – Damien_The_Unbeliever Apr 12 '23 at 05:47

2 Answers2

3

You should ParseExact string into date using existing format:

string startTime = "10/22/2012 9:13:15 PM";
  
DateTime date = DateTime.ParseExact(
  startTime, 
 "M/d/yyyy h:m:s tt", // <- given format 
  CultureInfo.InvariantCulture, 
  DateTimeStyles.None);

And only then format the date while using desired format:

// format we want
var result = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

you can use DateTime.Parse instead of DateTime.ParseExact

here is code

string dateInput = "10/22/2012 9:13:15 PM";
var parsedDate = DateTime.Parse(dateInput);
  • 1
    Note, that `Parse` uses `CultureInfo.CurrentCulture` which vary from workstation to workstation, so your solution will work on some computers only – Dmitry Bychenko Apr 12 '23 at 05:46