In normal C#, I can usually use a function like this:
private double getTime() {
double dateReturn =
Math.Round((DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds);
// note that (..date..).TotalMilliseconds returns a number such as
// 1606465207140.45 where
// 1606465207140 is ms and the ".45" is a fraction of a ms
return dateReturn;
}
However, most of Unity’s C# uses either int or floats. This returns a double, which I am unsure how to use in Mathf functions like Mathf.min/max, which call for ints.
System.DateTime epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
int cur_time = (int)(System.DateTime.UtcNow - epochStart).TotalSeconds;
This will give you the current time (the number of seconds that have passed since 1970/1/1)
For me, I achieve this with a static class.
using UnityEngine;
using System.Collections;
using System;
public static class Epoch {
public static int Current()
{
DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
int currentEpochTime = (int)(DateTime.UtcNow - epochStart).TotalSeconds;
return currentEpochTime;
}
public static int SecondsElapsed(int t1)
{
int difference = Current() - t1;
return Mathf.Abs(difference);
}
public static int SecondsElapsed(int t1, int t2)
{
int difference = t1 - t2;
return Mathf.Abs(difference);
}
}
It is worth noting that if you use 1-1-1970 as your epoch, your code will break on 1-19-2038. This is because the date 1-19-2038 is 2147483647 seconds after 1-1-1970. The number 2147483647 is the largest number a 32-bit signed Int can hold. To avoid this, you can change the line
DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
to a more recent date in the past. An Int epoch spans 136 years.
DateTimeOffset.Now.ToUnixTimeMilliseconds()
This is enought