javac#windowsfiletime

FileTime to string


I'm reading some Microsoft FileTime values, stored as a long, and I'm trying to convert it into a human readable date.

For instance, the value 131733712713359180 converts to: Wednesday, June 13, 2018 1:47:51pm. This was done using the online tool, here: Online time convertor

I've got it working in Java fine, but when I try to do it in C#, I'm getting the wrong year. The output I get is: 13/06/0418 13:47:51.

The code I'm using to do the conversion is:

public string CalculateTimestamp(Int64 epoch)
{
    DateTime date = DateTime.Now;

    try
    {
        date = new DateTime(epoch);
        DateTime filetime = new DateTime(date.ToFileTime());
        result = filetime.ToString();
    }
    catch (Exception uhoh)
    {
        result = "failedtoparsetimestamp";
    }

    return result;
}

When doing the conversion in Java, this is the code I'm using.

public String calculateTimeStamp(long epoch) {

    if (epoch == 0) {
        return "--";
    }

    long unixDifference = 11644473600000L;

    long timeStamp = (epoch / (10 * 1000)) - unixDifference;

    Date date = new Date(timeStamp);

    return date.toString();
}

I guessed that the C# conversion should be more straight forward, but I can't figure out why the year is wrong. I've tried both UInt64 and Int64, both give the same (wrong) result.

Any suggestions would be greatly appreciated.

Thanks


Solution

  • This is built-in to DateTime so there's no need to do any adjustments:

    var date = DateTime.FromFileTimeUtc(131733712713359180);
    

    This returns 2018-06-13 13:47:51