How to convert a Unix timestamp to milliseconds in C#
By FoxLearn 1/3/2025 1:23:22 AM 225
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Motiv MUI React Admin Dashboard Template
11/19/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024