Epoch Converter and Date/Time in C#
Quick Navigation
DateTime
The DateTime class represents an instant in time, typically expressed as a date and time of day.
using System;
class MainClass {
public static void Main (string[] args) {
DateTime date1 = DateTime.Now;
Console.WriteLine(date1);
DateTime date2 = DateTime.Today;
Console.WriteLine(date2);
//new DateTime(year, month, day, hour, min, seconds)
DateTime date3 = new DateTime(2008, 5, 1, 8, 30, 52);
Console.WriteLine(date3);
Console.WriteLine(date3.ToString("F")); //string format
}
}
Output:
02/16/2019 04:12:50
02/16/2019 00:00:00
05/01/2008 08:30:52
Thursday, 01 May 2008 08:30:52
Click here for more string formats.
Convert from Epoch to Human Readable Date
using System;
class MainClass {
public static void Main (string[] args) {
double timestamp = 1550545864;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, 0); //from start epoch time
start = start.AddSeconds(timestamp); //add the seconds to the start DateTime
Console.WriteLine (start);
}
}
Output:
2/19/2019 3:11:04 AM
Convert from Human Readable Date to Epoch
using System;
class MainClass {
public static void Main (string[] args) {
//subtract the epoch start time from current time
TimeSpan t = DateTime.Now - new DateTime(1970, 1, 1);
int secondsSinceEpoch = (int)t.TotalSeconds;
Console.WriteLine(secondsSinceEpoch);
}
}
Output:
1550290604