Search code examples
c#timestamp

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?


Solution

  • 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());
    

    to this:

    String timeStamp = GetTimestamp(DateTime.Now);