Convert a string to date in google apps script
Asked Answered
Y

7

14

I am new to GAS (actually new to coding too) I got a date string in the format of yyyymmdd (eg. 20140807), how could I turn it to date so that Google apps script can recognize it and later I can do some calculation (mostly to compare with Today as in var today = new Date();)

Google apps script can't recognize the following correctly:

// string is in the format of yyyymmdd (eg. 20140807)
var pubdate = new Date(string)
Yellowtail answered 7/8, 2014 at 4:36 Comment(0)
D
22

The only way - parse the string by hand:

var dateStr = "20140807"

var year = +dateStr.substring(0, 4)
var month = +dateStr.substring(4, 6)
var day = +dateStr.substring(6, 8)

var pubdate = new Date(year, month - 1, day)

The reason for month - 1 is that the month numeration starts from 0.

And the + sign before function just converts string, which is returned by functions, to numbers so we can pass them right into new Date()

Donatist answered 7/8, 2014 at 6:11 Comment(4)
@Yellowtail then mark my answer as correct (by clicking the tick under the downvote button), so other users could see it was helpfulDonatist
@Yellowtail also read THIS to understand better how does StackOverflow work. BTW, welcome to SO!Donatist
Thank you. At first, I actually tried to upvote it but I was not allowed to because my account is new. I didn't realise there is a "tick" sign. SO is really an exciting place.Yellowtail
How do I convert a date string with minutes and hours to new Date?Frigging
L
9

You can use moment.js to parse a string of date in GAS.

First you need to add moment.js to your GAS. In script editor, go to "Resources" then "Libraries...", then put this project key MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48 and click "Add". Choose the version from the dropdown, then click "Save".

Parsing date with moment is as easy as this.

var momentDate = Moment.moment("20140807", "YYYY/MM/DD");

What's returned here is a moment object, which is a wrapper of JavaScript's native Date object and very handy for date manipulation .

But, if you still need to get JavaScript's Date object, you can get it like this;

var date = momentDate.toDate();

You can also create formatted date time string with moment.js. Here is the reference for the tokens to specify format.

Leeleeann answered 13/5, 2017 at 6:6 Comment(0)
P
7

On November 3, 2022, a new method has been added to Class Utilities. It's parseDate(date, timeZone, format). By this method, the date string can be parsed. When this method is used to the date string of 20140807, the sample script is as follows.

Sample script:

function myFunction() {
  const str = "20140807";
  const dateObject = Utilities.parseDate(str, Session.getScriptTimeZone(), "yyyyMMdd");
  console.log(dateObject);
}

Reference:

Programme answered 24/11, 2022 at 12:24 Comment(0)
B
3

Be careful to pick the right timezone! In my example its

  • "+01:00 " => GMT+1 = Berlin (without daylight saving).

Other possible options

  • ".000000000Z" = "+00:00" => UTC = GMT = Unix Time
  • "-05:00" => EST = New York/ America
let date = "2021-03-10"
let time = "10:03:00"
let offset_to_utc = "+01:00"
let new_date_object = new Date(date + "T" + time + offset_to_utc)
Brainpan answered 10/3, 2021 at 11:27 Comment(0)
B
0

Thnx to Vyacheslav Pukhanov, I could solve my problem and answer the question of Code Guy in the comments. Excuse me for the names of vars are in Dutch ;)

function DatumStringNaarDatumWaarde(datumString){   
/* @param datumString: can be passed in by another function in your code
   If not provided, this function uses an example as returned by a stockQuoting RESTserver:
*/
 if(!datumString) datumString = "2017-04-25T09:10:00.000000000Z";   
 //--- parsing the string; datevalues   
 var splits      = datumString.split("T")
 var datumSplits = splits[0].split("-")
 var dd   = Number(datumSplits[2]);
 var MM   = Number(datumSplits[1])-1;
 var yyyy = Number(datumSplits[0]);   
 //---parsing the string; time values
 var tijd      = splits[1].split(":00.000000000Z")
 var minuutUur = tijd[0].split(":")
 var uur    = Number(minuutUur[0]);
 var minuut = Number(minuutUur[1]);
 //--- constructing dateValue, with possibilty to be formatted by Utilties             
 var datumWaarde = new Date(yyyy,MM,dd,uur,minuut);
 var werkDatum = Utilities.formatDate(new Date(datumWaarde), "GMT+2", "dd-MM-yyyy HH:mm")
 return(datumWaarde)
 }
Bainbridge answered 25/4, 2017 at 10:17 Comment(0)
O
0

This worked for me.

function dateFromString(dateString){
    if(!dateString) 
        dateString = "2020-06-05T09:10:00.000000000Z";
    var dateValue = new Date(dateString);
    return dateValue;
}
Oilcloth answered 4/6, 2020 at 19:37 Comment(0)
V
0

Maybe this help... From a google form, a Date submitted in text, convert to a valid Date in script:

function ddmmyyy() {
   var date = new Date('6/15/1974');
   var dd = date.getDate();
   var mm = date.getMonth()+1;
   var yyyy = date.getFullYear();

}
Venter answered 26/12, 2021 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.