EN
C# / .NET - string date time to epoch timestamp in seconds
0 points
In this article, we would like to show you how to string date time to epoch timestamp in seconds in C#.
Quick solution:
xxxxxxxxxx
1
string dateString = "2021-05-13 11:59:00.000";
2
3
DateTime epochTime = DateTime.Parse("1970-01-01");
4
DateTime date = DateTime.Parse(dateString);
5
6
var milliseconds = date.Subtract(epochTime).TotalSeconds;
7
8
Console.WriteLine(milliseconds); // 1620907140
In this example, we convert dateString
to date
using Parse()
method, then we use Subtract()
method with TotalSeconds
property to get number of seconds that passed since the Epoch to specified date.
xxxxxxxxxx
1
using System;
2
3
public static class Program
4
{
5
public static void Main(string[] args)
6
{
7
string dateString = "2021-05-13 11:59:00.000";
8
9
DateTime epochTime = DateTime.Parse("1970-01-01");
10
DateTime date = DateTime.Parse(dateString);
11
12
var milliseconds = date.Subtract(epochTime).TotalSeconds;
13
14
Console.WriteLine(milliseconds); // 1620907140
15
}
16
}
Output:
xxxxxxxxxx
1
1620907140