Timestamp

I tried to save some things in a log table with a timestamp, so I did this first:

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

And then I found this snippp:

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

I began to wonder why it is useful to use a reverse timestamp, and came across in this article

Now my question is: if the second snippet is correct? And how do you convert it back to a β€œnormal” timestamp, or how do you get readable time and time information from it?

+4
source share
1 answer

Make sure that DateTime converted to universal time before conversion to avoid problems with time zones:

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

You can convert the value back to the DateTime value by analyzing the string to long , MaxValue - (MaxValue - x) = x and constructing a new DateTime using 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) 
+2
source

Source: https://habr.com/ru/post/1413013/


All Articles