LoginSignup
28
30

More than 3 years have passed since last update.

Google Apps Scriptの日付操作もろもろ

Last updated at Posted at 2019-01-23

ある案件で日付の取得、比較を行う必要があり、今まで自分が使用していた開発言語とは使い方が違っていたので苦労したことをまとめておこうと思う。

さっそくコーディング

// 現在日時を取得
var today = new Date();

// 翌日を取得
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

// 特定の時間をセット
var 6oclock = newDate();
6oclock.setHours(06);
6oclock.setMinutes(00);
6oclock.setSeconds(00);

// 日付の大小を比較(比較結果の差異を「時間」に換算)
var jadgeRange = (today.getTime() - tomorrow.getTime()) / (1000 * 60 * 60);
  • 日付形式の指定方法、とりあえずよくつかうものだけ
// 現在日時を24時間表記で取得 ※「M」は月、「m」は分
var today = new Date();
Logger.log(Utilities.formatDate(today, 'Asia/Tokyo', 'yyyy/MM/dd HH:mm:ss'));

日付や時間を直接比較するときは日付形式を指定してから判定をした方がよい。

var today = new Date();
if (Utilities.formatDate(today, 'Asia/Tokyo', 'HH') > 12) {
  Logger.log('午後です');
} else {
  Logger.log('午前です');
}

このあたりをおさえておいて、細かいところは必要に応じて調べていく感じです。参考になれば。

28
30
2

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
28
30