How to convert a Unix timestamp to milliseconds in C#
By FoxLearn 1/3/2025 1:23:22 AM 323
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
RuangAdmin Template
11/17/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
Horizon MUI Admin Dashboard Template
11/18/2024