LoginSignup
20
15

More than 3 years have passed since last update.

「javascript、サーバー時刻取得できるってよ」

Last updated at Posted at 2019-10-29

「ふえええ...、javascriptだと、サーバーの時間取れないよぉぉぉ〜〜〜〜〜」と
赤ちゃん返りしていたところに
参考になりそうな記事を発見したので
案件で利用しているaxiosに合わせて書き直してみた。

サーバーの時刻とクライアントの時刻の違い

02.png

忙しい人のためのソースコード

ajax通信するためにaxiosを利用

index.html
<html>
<body>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</body>
</html>
getSevertime.js
// フロント側の時間
let frontSideTime = new Date()
console.log(frontSideTime) // デバイスの時刻

// サーバー側の時間
axios.head(window.location.href).then(res => {
  console.log(new Date(res.headers.date)) // サーバー時刻
})

これで海外からのwebページのアクセスでも
サーバーの時間を基準にしているから問題なくデバイスに依存せずに表示することができるようになった

参考

JavaScriptだけでサーバー時間を取得したタイマー作成方法

20
15
0

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
20
15