LoginSignup
47
41

More than 3 years have passed since last update.

JavaScriptでunixtimeから日時へ変換するやり方のメモ

Posted at

やりたいこと

「1567566215」みたいな感じのunixtime状態から、「2019/9/4」とか「9/4」(月日のみ抽出)みたいな日時の表記に変換すること。

やり方

test.js
// Dateがミリ秒なので1000倍が必要
let dateTime = new Date(unixtime * 1000);

// .toString()や.toLocaleDateString()、.toLocaleTimeStringでうまくいく
// 以下、unixtime = 1567566215 でのサンプル
console.log(dateTime.toString()); // => Wed Sep 04 2019 12:03:35 GMT+0900 (日本標準時)
console.log(dateTime.toLocaleDateString()); // => 2019/9/4
console.log(dateTime.toLocaleDateString('ja-JP').slice(5)); // => 9/4
console.log(dateTime.toLocaleTimeString()); // => 12:03:35
console.log(dateTime.toLocaleTimeString('ja-JP')); // => 12:03:35

年月日のうち月日のみを抽出するやり方を調べたけどいい感じのが見つからず、.slice()が簡単な気がきました。
getMonth()とかを使おうとすると複雑になるし、これのために何か読み込むとかも嫌だし。。

注意

(1) sliceのところでLocaleで'ja-JP'指定しているのは、sliceの位置を固定するためです。
(2) ただ、(1)のせいでLocal Timeを扱うのがちょっと不便。。

参考

Dateオブジェクト|JavaScript プログラミング解説
Date|MDN

47
41
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
47
41