4

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

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Tony
  • 3,587
  • 8
  • 44
  • 77
  • 2
    Just do `var date = DateTime.FromFileTimeUtc(131733712713359180);`, which returns `2018-06-13 13:47:51` – Matthew Watson Aug 27 '18 at 14:02
  • @MatthewWatson You ought to make that an answer... – SPQR Aug 27 '18 at 14:04
  • Your Java code is using terrible legacy date-time classes that were supplanted years ago by the *java.time* classes. For .Net platform, use a library similar to *java.time* called [*NodaTime*](https://nodatime.org/), based on the predecessor to *java.time* called *Joda-Time* ported from Java to C#. – Basil Bourque Aug 28 '18 at 00:28
  • Yeah, that code has been in place for years now, and I hadn't looked at it until yesterday. I'll get it updated, thanks. – Tony Aug 28 '18 at 10:06

1 Answers1

5

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

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Yup, that got it! I can't believe I didn't see that, I was staring at it for over ten minutes. Thank you :) – Tony Aug 27 '18 at 14:06