How to convert timestamp to date in C#
By Tan Lee Published on Nov 16, 2024 692
A timestamp in C# represents time as the number of seconds (or milliseconds) since the Unix epoch (January 1, 1970). Converting a timestamp to a date is often required for proper representation, as it provides a human-readable format of the time.
This conversion is important for accurately displaying information about files, folders, or packages. It ensures that both date and time are available, helping to provide precise details and proper context for any time-based data.
How to Convert Timestamp to Date in C#?
If you have a Unix timestamp, you can convert it to a DateTime
as follows:
For example:
// convert timestamp to date c# // Example Unix timestamp (milliseconds since Unix epoch) long unixTimestamp = 1413761632; // Convert to DateTime var dateTime = new System.DateTime(1980, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(unixTimestamp); System.Console.WriteLine($"{dateTime.ToShortDateString()} {dateTime.ToShortTimeString()}");//10/18/2024 11:33 PM
This program demonstrates how to convert a Unix timestamp into a human-readable date format. Specifically, it shows how the Unix timestamp corresponds to the date and time of October 18, 2024, at 11:33 PM in the output.
If the timestamp is in milliseconds, you can use FromUnixTimeMilliseconds
method:
For example:
// Example Unix timestamp (milliseconds since Unix epoch) long unixTimestamp = 1617845980123; // Convert to DateTime DateTime dateTime = DateTimeOffset.FromUnixTimeMilliseconds(unixTimestamp).DateTime; //4/8/2021 1:39:40 AM Console.WriteLine(dateTime);
This program demonstrates the conversion of a Unix timestamp to a DateTime
object in C#. The output shows the accurate calculation of the converted DateTime
based on the given Unix timestamp.
C# Date to milliseconds converter
To convert a DateTime
to milliseconds in C#, you can use the DateTime
object and subtract it from the Unix epoch (1970-01-01) to get the number of milliseconds.
For example:
// Your DateTime object (example: current time) DateTime dateTime = DateTime.Now; // Unix epoch (1970-01-01 00:00:00) DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // Calculate the number of milliseconds long milliseconds = (long)(dateTime.ToUniversalTime() - epoch).TotalMilliseconds; // Output the result Console.WriteLine($"Milliseconds since Unix epoch: {milliseconds}");
In this example:
DateTime.Now
: Represents the current date and time.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
: Represents the Unix epoch in UTC.Subtracting the current time from the epoch gives you a
TimeSpan
, and.TotalMilliseconds
converts theTimeSpan
to milliseconds.
This will output the number of milliseconds since the Unix epoch (January 1, 1970).