Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse timestamp

Tags:

c#

timestamp

I was trying to save some stuff to the Log table with timestamp so I first did this:

public static string TimeStamp(
   this DateTime datetime, string timestamptFormat = "yyyyMMddHHmmssffff")
   {
     return datetime.ToString(timestamptFormat);
   }

And then I found a snippet like this:

static public string ToReverseTimestamp(this DateTime dateTime)
{
return string.Format("{0:10}", DateTime.MaxValue.Ticks - dateTime.Ticks);
}

I started wondering what the heck is reverse timestamp is useful for, and came across this article

Now my question is: if the second snippet is even correct? And how do you convert it back to "normal" timestamp or how do you get readable datetime information from it?

like image 603
iLemming Avatar asked Oct 22 '22 22:10

iLemming


1 Answers

Make sure that the DateTime is converted to universal time before conversion to avoid time-zone problems:

public static string ToReverseTimestamp(this DateTime dateTime)
{
    return (long.MaxValue - dateTime.ToUniversalTime().Ticks).ToString();
}

You can convert the value back to a DateTime value by parsing the string to a long, calculating MaxValue - (MaxValue - x) = x and constructing a new DateTime with DateTimeKind.Utc from x:

public static DateTime FromReverseTimestamp(string timestamp)
{
    return new DateTime(long.MaxValue - long.Parse(timestamp), DateTimeKind.Utc);
}

Example:

var input = DateTime.Now;                      // {17/05/2012 16:03:17} (Local)
var timestamp = ToReverseTimestamp(input);     // "2520650302020786038"
var result = FromReverseTimestamp(timestamp);  // {17/05/2012 18:03:17} (Utc)
like image 180
dtb Avatar answered Nov 15 '22 04:11

dtb