Reputation: 342
Is there a time checker that can be implemented in unity? For example I want to check todays date and time, could I call something from google or another source to check time that way I don't check user device time which they could change. Any links or info would be useful.
Upvotes: 0
Views: 1572
Reputation: 36
This is the code I used. It uses UnityWebRequest (It requires Unity 5.2.0 or higher) for https and https://nist.time.gov/actualtime.cgi for the time, Uses coroutine to wait for the response
nist.time.gov/actualtime.cgi response :
// time * 10 == ticks
<timestamp time="1538381371720144" delay="0"/>
code :
public DateTime LastSyncedLocalTime
{
get;
private set;
}
public DateTime LastSyncedServerTime
{
get;
private set;
}
public DateTime InterpolatedUtcNow
{
get
{
return DateTime.UtcNow + (LastSyncedServerTime - LastSyncedLocalTime);
}
}
public IEnumerator Sync()
{
using (var www = UnityWebRequest.Get("https://nist.time.gov/actualtime.cgi"))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
yield break;
}
var timestamp = XElement.Parse(www.downloadHandler.text);
var ticks = long.Parse(timestamp.Attribute(XName.Get("time")).Value) * 10;
LastSyncedLocalTime = DateTime.UtcNow;
LastSyncedServerTime = new DateTime(1970, 1, 1).AddTicks(ticks);
}
}
Upvotes: 1
Reputation: 5163
As far as i know Unity does not support any way of getting the time that cannot be changed on the local device. I think your best solution to get around this would be to run a small php script to get the time using the date() format.
<?php echo "Today is " . date("Y/m/d");>
which will return the local time
You can then retrieve this data using the WWW class
public static IEnumerator GetTimeStamp(string url, RequestCompletedCallback callback)
{
UnityWebRequest www = UnityWebRequest.Get(url);//url would be where the php script is hosted
www.SendWebRequest();
while (!www.isDone)
{
if (www.isNetworkError || www.isHttpError)
{
throw new System.ArgumentException("Web request failed: ", www.error);
}
yield return null;
}
// Store results in a string
if (callback != null)
{
string result = www.downloadHandler.text;
}
www.Dispose();
}
Another solution would be using an API that returns dates like timezonedb or timeanddate
Upvotes: 0