如何在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);

输出:

000101010000000000

我想要类似的东西:

20140112180244

我做错了什么?

您的错误是使用 new DateTime(),它返回0001年1月1日00:00:00.000而不是当前日期,并且时间.获取当前日期和时间的正确语法是

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

对此:

String timeStamp = GetTimestamp(DateTime.Now);