Untitled

 avatar
unknown
csharp
2 years ago
1.4 kB
5
Indexable
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);
    }
}
Editor is loading...