0
votes

We are getting some data from feed where date is something like "28-07-2020 09:11:57 AM" when i am trying to convert it it is always giving error that

"String was not recognized as a valid DateTime."

I have used many methods like Convert.ToDateTime, DateTIme.Parse , DateTime.parseExact but all are having same error.

string s = "28-07-2020 09:09:57 AM"; var dt= DateTime.ParseExact(s,"M/d/yyyy h:mm:ss tt",CultureInfo.InvariantCulture);

DateTime dt2= Convert.ToDateTime(s);

DateTime dt3=DateTime.Parse(s);

Can someone please suggest what is the issue in date format. We need to change it regardless culture as it is a window application and running on diff machines.

4
Could you edit your question to include examples of you using these methods? Also, if you're not specifying the culture explicitly when calling these methods, what is the current culture on the machine where the code is running?Joe Sewell
None of them is going to work - this is a very strange custom format. You'll have to use DateTime.ParseExact with a pattern that matches this format. Are you sure the data shouldn't be reversed? The de-facto standard for date literals (ie strings) is the ISO8601 format. I'd expect any feed or HTTP API to return dates as 2020-07-28 09:11:57, possibly with a timezone offsetPanagiotis Kanavos

4 Answers

0
votes

You were close, this works for me:

string s = "08-07-2020 09:09:57 AM"; 
var dt = DateTime.ParseExact(s, "M-d-yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

Note matching dashes instead of slashes in pattern.

0
votes

After many try and combination below worked

string s = "28-07-2020 09:09:57 AM";

var dt = DateTime.ParseExact(s, "d-MM-yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

0
votes

This works for me (https://dotnetfiddle.net/MqwLLb):

Input:

using System;
using System.Globalization;
                    
public class Program
{
    public static void Main()
    {
        string s = "28-07-2020 09:09:57 AM";
        var dt= DateTime.ParseExact(s,"dd-MM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
        
        Console.WriteLine("dt => " + dt);
    }
}

Output:

dt => 7/28/2020 9:09:57 AM
0
votes

You can use TryParseExact method, it is quite useful if you are not sure about the incoming string value, also it is giving the result of parsing process as a boolean which makes easier to check if everything is right, and you can play with DateTimeStyles for adjusting output.

 string s = "28-07-2020 09:09:57 AM";
 var dt = new DateTime();
 var result = DateTime.TryParseExact(s, "dd-MM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal,out dt);