Epoch and Unix Timestamp Conversion in C# or C Sharp
Here we will explain C# Date/Time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.
C# or C Sharp is a simple, modern, general-purpose, object-oriented programming language. It is intended for use in developing software components suitable for deployment in distributed environments. It is more suitable for writing applications for both the hosted and embedded systems. The C# provided date time methods from DateTime
to handle epoch or Unix timestamp conversion into human readable dates or can convert human readable dates to Unix timestamp.
We will use the DateTimeOffset
instance method ToUnixTimeSeconds()
to get the current timestamp.
DateTimeOffset.Now.ToUnixTimeSeconds()
We can also get the current timestamp from a DateTime
:
DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
Convert epoch or Unix timestamp to date in C#
We will use the method FromUnixTimeSeconds()
to convert the epoch or timestamp to readable date format.
var dateTime = DateTimeOffset.FromUnixTimeSeconds(1745570598);
Convert date to epoch or unix timestamp in C#
We can convert human readable date to timestamp using ToUnixTimeMilliseconds()
method.
var dateTime = new DateTime(2025, 02, 21, 22, 0, 0, DateTimeKind.Utc);
var dateWithOffset = new DateTimeOffset(dateTime).ToUniversalTime();
long timestamp = dateWithOffset.ToUnixTimeMilliseconds();
Also, read:
- Epoch and Unix Timestamp Conversion in PHP
- Epoch and Unix Timestamp Conversion in Java
- Epoch and Unix Timestamp Conversion in JavaScript
- Epoch and Unix Timestamp Conversion in Perl
- Epoch and Unix Timestamp Conversion in Python
- Epoch and Unix Timestamp Conversion in TypeScript
- Epoch and Unix Timestamp Conversion in MySQL
- Epoch and Unix Timestamp Conversion SQL Server
- Epoch and Unix Timestamp Conversion in Kotlin
- Epoch and Unix Timestamp Conversion in Go
- Epoch and Unix Timestamp Conversion in Ruby
- Epoch and Unix Timestamp Conversion in VBA
- Epoch and Unix Timestamp Conversion in MATLAB
- Epoch and Unix Timestamp Conversion in Rust