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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With