How to convert a Unix timestamp to milliseconds in C#
By Tan Lee Published on Jan 03, 2025 444
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.
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Material Lite Admin Template
Nov 14, 2024
HTML Login Form
Nov 11, 2024
tsParticles Authentication Template
Nov 11, 2024