Time flies in Windows 10 IoT Core. How to get hold on it

Yes, time actually flies in a Raspberry Pi. It appears that it can not remember the current time when it is powered off in Windows 10 IoT Core.

One solution is to make use of a ‘sensor’ which tells the time.

Another solution is to ask ‘the internet’ for the current time. I use this service although there will be more, I can imagine 🙂

using System;
using System.Globalization;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Web.Http;
using Windows.Web.Http.Headers;

...
using (var client = new HttpClient())
{
  client.DefaultRequestHeaders.UserAgent.Add(
    new HttpProductInfoHeaderValue(
          "Mozilla / 5.0(Windows NT 10.0; Win64; x64)"));
  var response = await client.SendRequestAsync(
              new HttpRequestMessage(
              HttpMethod.Get,
              new Uri("http://www.timeapi.org/utc/now.json")));
  if (response.StatusCode == HttpStatusCode.Ok)
  {
     // {{"dateString": "2015-09-21T21:46:34+02:00"}}
    dynamic json = JsonConvert.DeserializeObject(
                                  response.Content.ToString());
    DateTime dateTime =
          DateTime.Parse(json.dateString.ToString(),
          CultureInfo.InvariantCulture);
    tbTest.Text = "Universal time: " 
                         + dateTime.ToUniversalTime();
  }
  else
  {
    tbTest.Text = response.StatusCode.ToString();
  }
}

This service can return a date time in several ways, but I prefer the UTC. So when received, the datetime json message is transformed into a datetime which will give me the UTC.

Advertenties