Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

c# datetime to unix timestamp milliseconds

  1. User

    c# datetime to unix timestamp milliseconds

  2. Assistant

    You can convert a C# DateTime to Unix timestamp (milliseconds) using this formula:

    long unixTimestamp = (long)(yourDateTime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
    

    Explanation:

    • yourDateTime is the DateTime you want to convert to Unix timestamp.
    • new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) is the Unix epoch time, which is January 1, 1970, at 00:00:00 UTC.
    • yourDateTime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)) calculates the time difference between yourDateTime and the Unix epoch time.
    • TotalMilliseconds converts the time difference to the total number of milliseconds.
    • (long) converts the double result to a long, as Unix timestamp is a 64-bit integer.

    Here's an example usage:

    DateTime myDateTime = new DateTime(2021, 9, 5, 10, 5, 30);
    long unixTimestamp = (long)(myDateTime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
    Console.WriteLine(unixTimestamp);
    

    Output:

    1630844730000
    

    The output is the Unix timestamp in milliseconds for the myDateTime value.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.