How to convert a Unix timestamp to milliseconds in C#
By FoxLearn 1/3/2025 1:23:22 AM 92
In C#, to get the current Unix timestamp in milliseconds, you can use the following code:
How to get Unix time in milliseconds in C#?
The FromUnixTimeMilliseconds()
method in C# converts a Unix timestamp, expressed in milliseconds since January 1, 1970, to a DateTimeOffset
value.
// c# unix timestamp milliseconds DateTimeOffset value = DateTimeOffset.FromUnixTimeMilliseconds(100000); // Display the time Console.WriteLine("DateTimeOffset is {0}", value); // DateTimeOffset is 01/01/1970 00:01:40 +00:00
You can also convert the Unix timestamp to milliseconds in C# as shown below.
using System; class Program { static void Main() { // Get the current UTC time DateTime currentUtcTime = DateTime.UtcNow; // Unix epoch start time (1970-01-01) DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // Calculate the Unix timestamp in milliseconds long unixTimestampMilliseconds = (long)(currentUtcTime - unixEpoch).TotalMilliseconds; // Print the Unix timestamp in milliseconds Console.WriteLine(unixTimestampMilliseconds); } }
In this example:
DateTime.UtcNow
gives the current UTC time.- A
DateTime
representing the Unix epoch (1970-01-01 00:00:00 UTC
) is created. - The difference between the current time (
DateTime.UtcNow
) and the Unix epoch is calculated usingTimeSpan
. - The
TotalMilliseconds
property of theTimeSpan
gives the total milliseconds. - This value is cast to
long
to represent the Unix timestamp in milliseconds.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Material Lite Admin Template
11/14/2024
Focus Admin Dashboard Template
11/18/2024
Stisla Admin Dashboard Template
11/18/2024