Retrieve Date and Time from the Internet

As a way to prevent cheating, I wanted to pull the current Date and Time from the net. So I tried this, and it works just fine in editor. However, when I deploy to WebGL, it gets nothing back in response. The code executes, but returns netTime as a null string. Again, in editor, it works exactly as intended and returns the date/time as a string. WebGL fails. Any ideas why? My understanding is that UnityWebRequest should be working with WebGL per the documentation (I’m using 5.5, it says implemented by 5.3)?

public IEnumerator GetInternetTime()
{
    UnityWebRequest myHttpWebRequest = UnityWebRequest.Get("http://www.microsoft.com");
    yield return myHttpWebRequest.Send();

    string netTime = myHttpWebRequest.GetResponseHeader("date");
    Debug.Log(netTime + " was response");
}

netTime returns a nice long string with the date/time in editor, returns nothing though when deployed to WebGL? Am I missing something?

1 Like

Maybe microsoft’s server doesn’t like the webplayer’s user-agent string? Or are there other restrictions on what a webplayer can do?

Tried multiple sites (besides MS), they all work locally, none work in WebGL. My guess atm is it works locally b/c there is no cross-domain issue (CORS), but once in browser, it’s hitting a CORS issue. I’m trying a CORS proxy to see if that fixes it.

Nope, even when I use a CORS proxy, it gets rid of the error returned, but I’m still getting absolutely nothing back. Sigh. Any ideas network knowledgeable folks? I’m amenable to alternate solutions if there’s a slicker way to get date/time from the net?

If it’s a cross domain issue, does the hosting site a cross domain policy xml file? http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html
I’ve had to use these in the past to solve such errors

Yah it’s not CORS, I used https://crossorigin.me to see if that was the problem. It doesn’t solve it, I’m getting absolutely nothing back in WebGL, although it seems to work in editor and PC platform…

I double checked I’m not getting any error with myHttpWebRequest.error is .isError. No error, just null coming back on WebGL. :frowning:

I even tried using the legacy WWW, and the exact same result. Null.

WWW www = new WWW("http://www.whattimeisit.com/");
yield return www;
www.text

www.text works fine in editor, properly grabs websites text, but in WebGL, nothing but null. True for WWW, true for UnityWebRequest. I’m out of ideas :frowning:

There’s an NTP script on this forum thread System.DateTime.now and how to avoid time cheats - Unity Engine - Unity Discussions This might be a better way to get time?

I actually couldn’t get his NTP script to work at all. Even then, the issue isn’t that above method doesn’t work, it does! It just doesn’t work on WebGL!

That said, I finally got it to return me SOME text using WWW, so I’ll just go down that road and see if I can find a website without ridiculous text for me to parse :slight_smile: Really should work with UnityWebRequest though…

Oh thank god someone made a reasonable website: http://www.timeapi.org/utc/now

That’s a string I can work with!

I had a similar issue and I figured it out then wrote a small guide http://leatonm.net/unity3d-internet-time-and-date-guide-stop-time-cheat/

public static DateTime GetNetTime()
{
    var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
    var response = myHttpWebRequest.GetResponse();
    string todaysDates = response.Headers["date"];
    return DateTime.ParseExact(todaysDates,
                               "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                               CultureInfo.InvariantCulture.DateTimeFormat,
                               DateTimeStyles.AssumeUniversal);
}
5 Likes

This occur issues on android build. works perfectly on editor. any ideas?

1 Like

You helped me so much. To anyone who comes along, this helped a lot, and it might help you to.

I had to add some using tags though, namely:
using System;
using System.Globalization;
using System.Net;

3 Likes

This works for me :slight_smile: and just add some try catch and everything is done… thanks :slight_smile:

does not works on webgl sadly

i have same problem when using it on android. The scene is stuck, but no error log appear. Does anyone know the reason?

Same problem here, when i try to get the date my scene freeze some sec (something like 40sec). I put a try / catch and it always goes in catch (i have internet)

Based on the information gathered here and there I wrote this static class that retrieves the internet time asynchronously (no scene freeze).

Call TimeManager.InitializeTime() at the start of your game and handle errors as you want. Then use TimeManager.UtcNow to get the current UTC time. If you want the local time add DateTimeStyles.AssumeUniversal as the last argument of DateTime.ParseExact (and modify the _utcStartTime name and initial value).

Note that this is not a great solution if you need the time for the internet very early in your code because we don’t know when the async method will finish. You could add some bool flag to know if the time was retrieved or not (or if something went wrong) to get around this issue though.

using System;
using System.Globalization;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
using UnityEngine;

public static class TimeManager
{
    private static DateTime _utcStartTime = DateTime.UtcNow;
    public static DateTime UtcNow => _utcStartTime.AddSeconds(Time.realtimeSinceStartup);
 
    public static void InitializeTime()
    {
        GetUtcTimeAsync().WrapErrors();
    }

    private static async Task GetUtcTimeAsync()
    {
        try
        {
            var client = new TcpClient();
            await client.ConnectAsync("time.nist.gov", 13);
            using var streamReader = new StreamReader(client.GetStream());
            var response = await streamReader.ReadToEndAsync();
            var utcDateTimeString = response.Substring(7, 17);
            _utcStartTime = DateTime.ParseExact(utcDateTimeString, "yy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        }
        catch
        {
            // Handle errors here
        }
    }

    private static async void WrapErrors(this Task task)
    {
        await task;
    }
}
2 Likes