Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# DateTime parses two date strings milliseconds apart incorrectly and gives negative unix time

I’m trying to convert date strings to Unix time using dotnet 6 and during my testing, I found a strange result between two timestamps that are milliseconds apart. My conversion code is (commented out bits are the variations I’ve tried and the results are the same):

static long convert_to_unix_time(DateTime date){ 
    return new DateTimeOffset(date, TimeSpan.Zero).ToUnixTimeMilliseconds();
}
    
static DateTime convert_to_timestamp(string date, string format) {
    string[] param = new string[1];
    param[0] = format;
        
    var final = new DateTime();
    var parsed_time = DateTime.TryParseExact(
        date,
        param,
        CultureInfo.GetCultureInfo("en-ZA"), //CultureInfo.CurrentCulture, //CultureInfo.Invariant, 
        DateTimeStyles.None,
        out final);
        return final;
    }

Running this:

var date1 = "20201214 13:00:04.156";
var date2 = "20201214 12:59:59.999";
string format = "yyyyMMdd hh:mm:ss.fff";
        
var final1 = convert_to_timestamp(date1, format);
var unix_time1 = convert_to_unix_time(final1);
        
Console.WriteLine("final1 is: {0}", final1.ToString(format));
Console.WriteLine("unix time1 is: {0}", unix_time1);
        
var final2 = convert_to_timestamp(date2, format);
var unix_time2 = convert_to_unix_time(final2);
        
Console.WriteLine("final2 is: {0}", final2.ToString(format));
Console.WriteLine("unix time2 is: {0}", unix_time2);

The output I get is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

final1 is: 00010101 12:00:00.000
unix time1 is: -62135596800000
final2 is: 20201214 12:59:59.999
unix time2 is: 1607907599999

I can’t for the life of me figure out what’s causing this error, or even what to call it or search for.

Is there a way to get the correct result?

dotnet fiddle

>Solution :

Uppercase "H" indicates a 24-hour time and lowercase "h" indicates 12-hour time. More information on string formats here.

You are sending a 24h string to a 12h format.

Updated code: https://dotnetfiddle.net/Widget/wkYoQY

string format = "yyyyMMdd HH:mm:ss.fff";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading