LoginSignup
11
12

More than 5 years have passed since last update.

日本標準時刻を取得する

Posted at

端末時刻じゃなくて現在時刻を取得したかったので書いてみました。
NICTの日本標準時プロジェクトが公開しているWebAPIを使用しました。
Newtonsoft.Jsonを使用しています。


    public class TimeService
    {
        /// <summary>
        //  現在時刻を取得します。
        /// </summary>
        /// <returns></returns>
        public async Task<DateTime> GetNow()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.Timeout = TimeSpan.FromSeconds(3);
                var result = await client.GetAsync("https://ntp-a1.nict.go.jp/cgi-bin/json");
                if (result.IsSuccessStatusCode)
                {
                    var time = JsonConvert.DeserializeObject<NitcTime>(await result.Content.ReadAsStringAsync());

                    var now =
                        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Convert.ToDouble(time.st))
                            .ToLocalTime();

                    return now;
                }
            }
            catch
            {                
            }
            return DateTime.Now;
        }

        public class NitcTime
        {
            public string id { get; set; }
            public decimal it { get; set; }
            public decimal st { get; set; }
            public int leap { get; set; }
            public decimal next { get; set; }
            public int step { get; set; }
        }
    }
11
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12