Untitled

mail@pastecode.io avatar
unknown
csharp
a year ago
1.4 kB
3
Indexable
Never
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public static class TimeApi
{
    public const string TIME_API_ENDPOINT = "http://worldtimeapi.org/api/ip";

    private class TimeData
    {
        public string datetime;
    }

    private static IEnumerator GetCurrentDateTime(Action<DateTime> currentDateTimeCallback)
    {
        // Set up the UWR so it can download the JSON response.
        using UnityWebRequest request = new UnityWebRequest(
            TIME_API_ENDPOINT,
            UnityWebRequest.kHttpVerbGET,
            new DownloadHandlerBuffer(),
            null);

        // Send the HTTP request.
        yield return request.SendWebRequest();

        // Check for errors.
        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(request.error);
            yield break;
        }

        // Deserialize the JSON into the data model.
        TimeData timeData = JsonUtility.FromJson<TimeData>(request.downloadHandler.text);

        // Try parsing a DateTime object from the string.
        if (!DateTime.TryParse(timeData.datetime, out DateTime currentDateTime))
        {
            Debug.LogError("Cannot parse DateTime from JSON.");
            yield break;
        }

        Debug.Log($"Current date & time: {currentDateTime}");
        currentDateTimeCallback?.Invoke(currentDateTime);
    }
}