1

I am trying to convert a date that is returned to me with it in this format:

2022-02-09T14:43:32

I am trying to get it to look like this

2/9/2022 2:43PM

I tried this but it says it is not a valid format.

workRow["ShiftStart"] = DateTime.ParseExact(theTempsDataSet.Tables[0].Rows[i]["shiftStartTime"].ToString(), "dd/mm/yyyy hh:mmtt", CultureInfo.InvariantCulture).ToString();
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
KJM
  • 83
  • 1
  • 7
  • 2
    Note that `DateTime` does not have a format. Formats are just for the string representation of the date (parsing from or formatting to). So you just need to parse your `DateTime` with the correct format and then whenever you need to display it format it with the other format. – juharr Feb 10 '22 at 15:59
  • 1
    Why are you calling `.ToString()` on `theTempsDataSet.Tables[0].Rows[i]["shiftStartTime"]` only to parse it again. What type is `theTempsDataSet.Tables[0].Rows[i]["shiftStartTime"]`? – phuzi Feb 10 '22 at 16:09
  • 1
    Also, [DateTime.ToString()?](https://stackoverflow.com/q/11935584/215552), or any of the other questions asked about how to format a DateTime. – Heretic Monkey Feb 10 '22 at 16:09

3 Answers3

0

ParseExact should have date format to parse date from file. So, it should have "yyyy-MM-ddTHH:ss:mm" date format. After parsing it will be in DateTime type. To convert it back to string, you can call .ToString("dd/mm/yyyy hh:mmtt") on that. Where "dd/mm/yyyy hh:mmtt" is your custom date format

Serhii
  • 723
  • 1
  • 4
  • 12
0

try this

var dtStr="2022-02-09T14:43:32";
var dt=  DateTime.Parse(dtStr);
dtStr = dt.ToString("M/d/yyyy h:mmtt", CultureInfo.InvariantCulture);

or who loves in one line

var dt=  DateTime.Parse("2022-02-09T14:43:32").ToString("M/d/yyyy h:mmtt", CultureInfo.CreateSpecificCulture("en-US"));
Serge
  • 40,935
  • 4
  • 18
  • 45
  • The one line solution works thank you. I had to change the HH to h but beyond that it worked great. Again thank you. – KJM Feb 10 '22 at 19:41
  • You are welcome! I guess h works better for you. I fixed the answer – Serge Feb 10 '22 at 19:43
-1

You just have to use the right datetime format :

DateTime date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500); Console.WriteLine(date1.ToString("MM/dd/yyyy hh:mm tt",CultureInfo.CreateSpecificCulture("en-US")));

Read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#tSpecifier

Rivo R.
  • 351
  • 2
  • 8