Skip to content
Advertisement

Converting Epoch timestamp to DateTime

Hello i am experiencing a strange problem, my scenario is that i am reading the history of google chrome browser stored in sqlite database using c# language. every thing goes fine except the timestamp that chrome stores in epoch format i have to upload the data to server using php and store it in the MYSQL database. Now my problem is that i can’t manage to convert that epoch timestamp to MYSQL based datetime. for C# i tried following code

public static DateTime FromUnixTime(long unixTime)
{
    return epoch.AddSeconds(unixTime);
}

taken from here i tried all available solutions on that link but they did not worked in my case.

for PHP i tried the following code taken from here

echo date("Y-m-d H:i:s", substr($epoch, 0, 10));

but it converts correct if the timestamp is same as mentioned in example but it returns wrong year when executed with my epoch timestamp.

i even tried to solve this problem at MYSQL query level so i searched and tried the following solution taken from here

select from_unixtime(floor(1389422614485/1000));

it does work when i don’t replace the example epoch timestamp but when i put my own it did not work

kindly help me to get rid of this strange irritating problem does not matter at which layer you provide solution all are acceptable following languages are preferred

  1. C#
  2. PHP
  3. MYSQL Query

example epoch timestamp is foloowing

13209562668824233

i do know that with respect to length its not same as in examples but note that chrome does convert this efficiently.

Advertisement

Answer

As explained by this answer, the Chrome timestamp is not equal to Unix epoch time. This is why you’re not getting the results you expect from such methods. It’s actually microseconds since the 1st Jan, 1601 (as opposed to Unix epoch time’s seconds since 1st Jan, 1970).

You can test your WebKit timestamp here, where you’ll see it returns Tuesday, 6 August 2019 10:57:48 (UTC).

So to convert this in code, we should first subtract the difference between 1970 and 1601 (in microseconds) and then divde the value by 1 million to get seconds (C# solution):

public static DateTime ConvertWebKitTime(long webkitEpoch)
{
    const long epochDifferenceMicroseconds = 11644473600000000; // difference in microseconds between 1601 and 1970
    var epoch = (webkitEpoch - epochDifferenceMicroseconds) / 1000000; // adjust to seconds since 1st Jan 1970
    return DateTimeOffset.FromUnixTimeSeconds(epoch).UtcDateTime; // convert to datetime
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement