javascript 現在日時から分単位で演算する

javascript 現在日時から分単位で演算する

javascriptで、現在日時から分単位で演算するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 105.0.5195.102

現在日時から分単位で演算

現在日時から分単位で演算するには、「getMinutes」で分単位で演算いして、「setMinutes」でその結果を戻してあげます。

const date = new Date();

console.log( '現在日時 : ' + date );

date.setMinutes( date.getMinutes() + 10 );

console.log( '10分前   : ' + date );

date.setMinutes( date.getMinutes() + 10 );

console.log( '10分後   : ' + date );

実行結果を見ると、演算されていることが確認できます。

秒単位

秒単位の場合は「getSeconds」と「setSeconds」を使用します。

const date = new Date();

console.log( '現在日時 : ' + date );

date.setSeconds( date.getSeconds() + 10 );

console.log( '10秒前   : ' + date );

date.setSeconds( date.getSeconds() + 10 );

console.log( '10秒後   : ' + date );

実行結果