-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?

2
  • 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. Commented Apr 12, 2023 at 5: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. Commented Apr 12, 2023 at 5:47

2 Answers 2

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");
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Note, that Parse uses CultureInfo.CurrentCulture which vary from workstation to workstation, so your solution will work on some computers only

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.