- Home /
How can I get the time since the epoch date in Unity3D?
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.
No problem! Probably plenty of better ways to do it now. Ancient question at this point. :)
Answer by sonnyyap · Jan 14, 2015 at 07:26 AM
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)
If you are trying to match JavaScript new Date().getTime();
you will need to multiply cur_time
in this answer by 1000 to get milliseconds.
Answer by Astrydax · Sep 12, 2016 at 04:09 PM
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.
I see. A static class looks like a good idea. And yeah it is probably better to change the epoch date to a recent one. Thanks for pointing out!
To avoid the 1-19-2038 problem, just use a long
ins$$anonymous$$d of an int
Answer by codewing · Nov 23, 2021 at 01:41 PM
DateTimeOffset.Now.ToUnixTimeMilliseconds()
This is enought