URLをコピーしました!
スキルアップを始める!

GAS(Google Apps Script)で日付を取得する方法|new Date()

GAS(GoogleAppsScript)
\ワードプレスのスキルアップはこちら!/ WordPress入門読本

GAS(Google Apps Script)で日付を取得する

GAS(Google Apps Script)で日付を取得するには、new Date()コンストラクタを使用するか、Utilities.formatDate()メソッドを使用することができます。

以下にそれぞれの方法の例を示します。

new Date()コンストラクタを使用する例

const currentDate = new Date();

これにより、現在の日時が含まれるDateオブジェクトが取得されます。このオブジェクトから必要な情報を取り出すことができます。

const currentDate = new Date();
Logger.log(currentDate);

情報	Wed Feb 22 01:21:44 GMT+09:00 2023

たとえば、年、月、日を取得するには、以下のようにします。

const year = currentDate.getFullYear();  // 現在の年を取得
const month = currentDate.getMonth() + 1;  // 現在の月を取得(0から始まるため、1を足す)
const day = currentDate.getDate();  // 現在の日を取得

それぞれの値が取得できます。

  const year = currentDate.getFullYear();  // 現在の年を取得
  const month = currentDate.getMonth() + 1;  // 現在の月を取得(0から始まるため、1を足す)
  const day = currentDate.getDate();  // 現在の日を取得
  Logger.log(year);
  Logger.log(month);
  Logger.log(day);

情報	2023.0
情報	2.0
情報	22.0

Utilities.formatDate()メソッドを使用する例

const currentDate = new Date();
const formattedDate = Utilities.formatDate(currentDate, "JST", "yyyy/MM/dd");

これにより、現在の日時が指定されたフォーマットで文字列として取得されます。

[rml_read_more]

上記の例では、”yyyy/MM/dd”というフォーマットを指定しているため、年月日の形式で文字列が取得されます。必要に応じて、フォーマットを変更することができます。

  const currentDate = new Date();
  const formattedDate = Utilities.formatDate(currentDate, "JST", "yyyy/MM/dd");
  Logger.log(formattedDate);

情報	2023/02/22

また、第2引数のタイムゾーンには、適切なタイムゾーンを指定する必要があります。上記の例では、”JST”という日本のタイムゾーンを指定しています。

まとめ

以上、現在日時を取得する基本的な方法です。例えば、スプレッドシートのセルや、Googleドライブに新規作成や複製したファイル名に日付を設定したい場合などに役立ちます。

ご参考ください。

Kindle Unlimited 会員は無料で購読できます
購読はこちら
Kindle Unlimited 会員は無料で購読できます
購読はこちら