EgonMilanVotrubec

WorldClock.cs

Jan 31st, 2019
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using System;
  2. using System.Net.Http;
  3. using UnityEngine;
  4.  
  5. /// Go to https://github.com/JamesNK/Newtonsoft.Json/releases and add the
  6. /// appropriate Newtonsoft.Json.dll to your Assets/Plugins folder.
  7. using Newtonsoft.Json;
  8.  
  9.  
  10. public class WorldClockTime
  11. {
  12.     [JsonProperty ( "currentDateTime" )]
  13.     public DateTime CurrentDateTime { get; set; }
  14.  
  15.     [JsonProperty ( "currentFileTime" )]
  16.     public long CurrentFileTime { get; set; }
  17. }
  18.  
  19.  
  20. public class WorldTime : MonoBehaviour
  21. {
  22.     static HttpClient client = new HttpClient ( );
  23.  
  24.     // Start is called before the first frame update
  25.     void Start()
  26.     {
  27.         GetTime ( );
  28.     }
  29.    
  30.  
  31.     private async void GetTime()
  32.     {
  33.         try
  34.         {
  35.             var response = client.GetAsync ( "http://worldclockapi.com/api/json/utc/now" );
  36.             var result = await response;
  37.             var responseString = await result.Content.ReadAsStringAsync ( );
  38.  
  39.             //Log ( $"PostAsync<T> result.StatusCode : {result.StatusCode} {responseBody}" );
  40.             if ( !string.IsNullOrEmpty ( responseString ) )
  41.             {
  42.                 var currentTime = JsonConvert.DeserializeObject<WorldClockTime> ( responseString );
  43.                
  44.                 var date = new DateTime ( currentTime.CurrentFileTime );
  45.  
  46.                 Debug.Log ( $"Current UTC time is {currentTime.CurrentDateTime}.\n" +
  47.                     $"Current Local Time is {currentTime.CurrentDateTime.ToLocalTime ( )}\n" +
  48.                     $"Current UTC CurrentFileTime is {date}.\n" +
  49.                     $"Current Local CurrentFileTime is {date.ToLocalTime ( )}" );
  50.             }
  51.         }
  52.         catch ( Exception e )
  53.         {
  54.             Debug.LogWarning ( $"Exception! {e.Message}" );
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment