Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active August 25, 2022 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yano3nora/34651b536066f877ae8aecaca948aece to your computer and use it in GitHub Desktop.
Save yano3nora/34651b536066f877ae8aecaca948aece to your computer and use it in GitHub Desktop.
[js: Date] Date Object on JavaScript. #js

Overview

Date - developer.mozilla.org

JS の Date オブジェクト死ぬほど使いづらいので、luxon など原則ライブラリで触ったほうがいい。どうしてもライブラリ使えないケースでは注意して取り扱いたい。

toISOString 形式で timezone 考慮したい

new Date(
  new Date().getTime() -
  new Date().getTimezoneOffset() * (60 * 1000) // 分で UTC との offset を取れる
).toISOString().slice(0, -1) // 2022-05-29T19:22:33.164

Date を vanilla でなんとか format したい

標準機能でDateをformatする色々(toLocaleString/Intl.DateTimeFormat/etc)

減算、加算するときは UNIX タイムスタンプ使うとよさそう

How to add 30 minutes to a JavaScript Date object?

  • Date.prototype.getTime()
    • UNIX 元期からの経過ミリ秒数を返す
  • Date.prototype.setTime()
    • UNIX 元期からの経過ミリ秒数をセット
    • 通常 UNIX タイムスタンプは秒単位なので * 1000 してセットするとよさそう
/**
 * 例えば現在時刻から「ちょうど 24h 後」の Date を作る例
 */
const secOfADay = 86400;
const today     = new Date();

console.log(today);     // 2021-03-09T02:21:21.970Z

const tomorrow  = new Date();
tomorrow.setTime(today.getTime() + secOfADay * 1000);  // ミリ秒考慮

console.log(tomorrow);  // 2021-03-10T02:21:21.970Z
/**
 * addMinutesNowDate - 現在 date へ minutes を足した新規 date を返却
 *
 * @param  min {number}
 * @return {Date}
 */
function addMinutesNowDate(min) {
  const fetureDate = new Date();
  fetureDate.setTime(new Date().getTime() + min * 60 * 1000);

  return fetureDate;
}

比較も getTime() のが安全ぽい

const now = new Date();
const due = new Date(Date.parse('2019/03/18 21:00:00'));

if (due.getTime() < now.getTime()) {
  console.log('まだあわわわわわわわわわわわ');
} else {
  console.log('まだ慌てるような時間じゃない');
}

ミリセカンドを分、秒へ変換

/**
 * @example millisToMinutesAndSeconds(298999); // '4:59'
 */
export const millisToMinutesAndSeconds = (millis: number, hour = false) => {
  const second = Math.ceil(millis / 1000)
  const hours = Math.floor(second / 3600)
  const minutes = Math.floor(second / 60)
  const seconds = second - (minutes * 60)

  const formatted = {
    hours: hours.toString().padStart(2, '0'),
    minutes: minutes.toString().padStart(2, '0'),
    seconds: seconds.toString().padStart(2, '0'),
  }

  if (hour) {
    return `${formatted.hours}:${formatted.minutes}:${formatted.seconds}`
  }

  return `${formatted.minutes}:${formatted.seconds}`
}

Date オブジェクトを整形する例

JavaScriptでgetMonthやgetDayを使わずに日付を表示する方法

new Date().toLocaleDateString('ja-JP')
// '2021/11/30' になる、node だと 2021-11-30 だった

// 指定できるっぽい
new Date().toLocaleDateString('ja-JP', {
  year: 'numeric',
  month: 'short',
  day: 'numeric',
  weekday: 'short',  
})
// '2021年1月4日(月)' になる、node だと 2021 M11 30, Tue だった

// ゼロパディング
new Date(Date.parse('2021/01/08 00:00:00'))
  .toLocaleDateString('ja-JP', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })

// '2021/01/08'

以下は愚直な古いコード。

function getFormattedDateString(date) {
  var dateStr = '';
  if(var date == null) {
  	var now = new Date();
  } else {
  	var now = date;
  }
  if (date instanceof Date && !isNaN(date.valueOf())) {
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var d = now.getDate();
    var w = now.getDay();
    var h = now.getHours();
    var min = now.getMinutes();
    var s = now.getSeconds();
    var wNames = ['日', '月', '火', '水', '木', '金', '土'];
    m = ('0' + m).slice(-2);
    d = ('0' + d).slice(-2);
    h = ('0' + h).slice(-2);
    min = ('0' + min).slice(-2);
    s = ('0' + s).slice(-2);
    dateStr = (y + '/' + m + '/' + d + ' ' + h + ':' + min + ':' + s);        
    return dateStr;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment