Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to date in google apps script

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)
like image 780
user3595556 Avatar asked Aug 07 '14 04:08

user3595556


People also ask

How do I convert a string to a date in Google script?

Enter =DATEVALUE( Click the cell that contains the text-formatted date that you want to convert. Enter ) Press ENTER, and the DATEVALUE function returns the serial number of the date that is represented by the text date.

How do you convert a string to a date in JavaScript?

You can Convert the date value from String to Date in JavaScript using the `Date()`` class. You can also use parse, which is a static method of the Date class. You can also split the given string date into three parts representing the date, month, and year and then convert it to Date format.

How do you format a date in Google App script?

You can create a date object by passing a formatted date string to the date constructor. For example: const date = new Date('February 17, 2021 13:00:00 -0500');


2 Answers

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()

like image 98
Vyacheslav Pukhanov Avatar answered Oct 19 '22 20:10

Vyacheslav Pukhanov


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.

like image 21
kanji Avatar answered Oct 19 '22 19:10

kanji