[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?

This question is related to c# timestamp

The answer is


var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

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

Int32 unixTimestamp = (Int32)(TIME.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

"TIME" is the DateTime object that you would like to get the unix timestamp for.


var timestamp = DateTime.Now.ToFileTime();

//output: 132260149842749745

This is an alternative way to individuate distinct transactions. It's not unix time, but windows filetime.

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:

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