JavaScriptで日付を扱うスニペット

Pocket

JavaScriptで日付オブジェクトを扱ったり変換したりする場合に使うスニペットです。

dateobj = new Date();
console.log(dateobj);//Wed Mar 15 2017 17:37:35 GMT+0900 (東京 (標準時))

//日付を8桁で。
datestr = dateobj.getFullYear() * 10000 + (dateobj.getMonth() + 1) * 100 + dateobj.getDate();
console.log(datestr);//20170315

//日付を年月日で。
datestr = dateobj.getFullYear() + "年" + (dateobj.getMonth() + 1) + "月" + dateobj.getDate() + "日";
console.log(datestr);//2017年3月15日

//日付をハイフン区切りで。
datestr = dateobj.getFullYear() + "-" + (dateobj.getMonth() + 1) + "-" + dateobj.getDate();
console.log(datestr);//2017-3-15

//月を英語で。
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
datestr = months[dateobj.getMonth()];
console.log(datestr);//March

//曜日を英語で。
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
datestr = days[dateobj.getDay()];
console.log(datestr);//Wednesday

//曜日を日本語で。
days = ["日", "月", "火", "水", "木", "金", "土"];
datestr = days[dateobj.getDay()];
console.log(datestr);//水

//日付オブジェクトを年月日時分秒に分解。
nen = dateobj.getFullYear();
tsuki = dateobj.getMonth() + 1;
hi = dateobj.getDate();
ji = dateobj.getHours();
fun = dateobj.getMinutes();
byo = dateobj.getSeconds();
datestr = nen + " " + tsuki + " " + hi + " " + ji + " " + fun + " " + byo;
console.log(datestr);//2017 3 15 17 37 35

//日付文字列(8桁)を日付オブジェクトに。
datestr = dateobj.getFullYear() * 10000 + (dateobj.getMonth() + 1) * 100 + dateobj.getDate();
datestr = datestr.toString(10); //日付文字列(8桁)
m = datestr.match(/(\d{4})(\d{2})(\d{2})/);
dateobj = new Date(m[1], m[2] - 1, m[3]);
console.log(dateobj);//Wed Mar 15 2017 00:00:00 GMT+0900 (東京 (標準時))

//日付文字列(ハイフン区切りなど)を日付オブジェクトに。
datestr = dateobj.getFullYear() + "-" + (dateobj.getMonth() + 1) + "-" + dateobj.getDate();
m = datestr.match(/(\d+)\D+(\d+)\D+(\d+)/);
dateobj = new Date(m[1], m[2] - 1, m[3]);
console.log(dateobj);//Wed Mar 15 2017 00:00:00 GMT+0900 (東京 (標準時))

//経過日数
datefrom = new Date(2015, 1, 1);
dateto = new Date(2015, 1, 15);
daydiff = Math.floor((dateto - datefrom) / 24 / 60 / 60 / 1000);
console.log(daydiff + "日");//14日

//経過年数
datefrom = new Date(2010, 7, 1);
dateto = new Date(2015, 0, 15);
yeardiff = dateto.getFullYear() - datefrom.getFullYear();
monthdiff = dateto.getMonth() - datefrom.getMonth();
daydiff = dateto.getDate() - datefrom.getDate();
yeardiff -= (monthdiff < 0 || (monthdiff == 0 && daydiff < 0)) ? 1 : 0;
console.log(yeardiff + "年");//4年

//経過年数(別の方法)
yeardiff = Math.floor(
  (
    (dateto.getFullYear() - datefrom.getFullYear()) * 10000 + (dateto.getMonth() - datefrom.getMonth()) * 100 + dateto.getDate() - datefrom.getDate()) / 10000);
console.log(yeardiff + "年");//4年

[ 2017年3月15日 | カテゴリー: JavaScript | タグ: , ]

« | »

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

送信してください。


タグ

カテゴリー

最近の投稿

最近のコメント

固定ページ

アーカイブ

stabucky

写真

メタ情報