简体   繁体   English

如何在C#中获得正确的时间戳

[英]How to get correct timestamp in C#

I would like to get valid timestamp in my application so I wrote:我想在我的应用程序中获得有效的时间戳,所以我写道:

public static String GetTimestamp(DateTime value)
{
    return value.ToString("yyyyMMddHHmmssffff");
}
//  ...later on in the code
String timeStamp = GetTimestamp(new DateTime());
Console.WriteLine(timeStamp);

output:输出:

000101010000000000

I wanted something like:我想要这样的东西:

20140112180244

What have I done wrong?我做错了什么?

Your mistake is using new DateTime() , which returns January 1, 0001 at 00:00:00.000 instead of current date and time.您的错误是使用new DateTime() ,它返回 0001 年 1 月 1 日 00:00:00.000 而不是当前日期和时间。 The correct syntax to get current date and time is DateTime.Now , so change this:获取当前日期和时间的正确语法是DateTime.Now ,因此更改此:

String timeStamp = GetTimestamp(new DateTime());

to this:对此:

String timeStamp = GetTimestamp(DateTime.Now);
var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
var timestamp = DateTime.Now.ToFileTime();

//output: 132260149842749745

This is an alternative way to individuate distinct transactions.这是区分不同交易的另一种方法。 It's not unix time, but windows filetime.这不是unix时间,而是windows文件时间。

From the docs :文档

A Windows file time is a 64-bit value that represents the number of 100- 
nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 
A.D. (C.E.) Coordinated Universal Time (UTC).

For UTC :对于UTC

string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

For local system :对于本地系统

string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Int32 unixTimestamp = (Int32)(TIME.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

“TIME”是您想要获取其 Unix 时间戳的 DateTime 对象。

internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
    DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
    return ConvertedUnixTime.ToString(ConvertFormat);
}

int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

Usage:用法:

UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM