0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dateオブジェクトで時間部分を削除する方法(GAS)

Last updated at Posted at 2025-01-04

Dateオブジェクトを生成すると時刻まで設定されますが日付比較ができないなど時間部分を削除したいことがあると思います。

getメソッド

date1.gas
function dateTest1() {
  var today = new Date();
  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());

  console.log(today);
}
console
11:47:20 AM	Notice	Execution started
11:47:20 AM	Info	Sat Jan 04 2025 00:00:00 GMT+0900 (Japan Standard Time)
11:47:21 AM	Notice	Execution completed

setメソッド

date2.gas
function dateTest2() {
  var today = new Date();  
  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);

  console.log(today);
}
console
11:50:02 AM	Notice	Execution started
11:50:02 AM	Info	Sat Jan 04 2025 00:00:00 GMT+0900 (Japan Standard Time)
11:50:03 AM	Notice	Execution completed

toDateStringメソッド

toDateStringメソッドで日付文字列を取得して時間情報を付加する

date3.gas
function dateTest3() {
  var today = new Date();
  console.log(today.toDateString());
  today = new Date(today.toDateString() + " 00:00:00 GMT+0900 (Japan Standard Time)");
}
console
12:06:27 PM	Notice	Execution started
12:06:27 PM	Info	Sat Jan 04 2025
12:06:27 PM	Info	Sat Jan 04 2025 00:00:00 GMT+0900 (Japan Standard Time)
12:06:29 PM	Notice	Execution completed

getTimeメソッド

getTimeメソッドで1970年1月1日からの経過ミリ秒を取得して
86400000ミリ秒(1日)で剰余算して時間に当たるミリ秒を引き
32400000ミリ秒(9時間)で日本時間(UTC+9)を引く

date4.gas
function dateTest4(){
  var today = new Date();
  // 現在日時-時分秒-9時間(日本はUTC+9)
  today = new Date(today.getTime()-(today.getTime()%86400000)-32400000);

  console.log(today);
}
console
11:52:10 AM	Notice	Execution started
11:52:11 AM	Info	Sat Jan 04 2025 00:00:00 GMT+0900 (Japan Standard Time)
11:52:11 AM	Notice	Execution completed
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?