反向时间戳

iLe*_*ing 5 c# timestamp

我试图用时间戳将一些东西保存到日志表中,所以我首先这样做了:

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

然后我发现了一个这样的片段:

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

我开始想知道反向时间戳到底有什么用,然后看到了这篇文章

现在我的问题是:第二个片段是否正确?以及如何将其转换回“正常”时间戳或如何从中获取可读的日期时间信息?

dtb*_*dtb 3

转换前请确保DateTime已将其转换为世界时间,以避免时区问题:

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

DateTime您可以通过将 解析string为 a long、使用 from 计算并MaxValue - (MaxValue - x) = x构造一个新值来将值转换回值:DateTimeDateTimeKind.Utcx

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

例子:

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)
Run Code Online (Sandbox Code Playgroud)