Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting next day date for specific string format in Google Apps Script (JavaScript)

Good day everyone! Working on aprojectmI had to start working with Google Spereadsheet interface and faced a problem I cannot quickly overcome due to not working with JavaScripts ever before. I have a date in specific format as a string

var date = "2012-08-09";

What I need is to get the next day date as

date = "2012-08-10";

which should include changing not only the day, but month and year too, if necessary.

I've tried using date format

  var datum= new Date(date);
  datum.setDate(datum.getDate() + 1);
  date = datum.toString('yyyy-MM-dd');

but the code appears to fail at writing date to datum variable. What is the best and quickiest way tosolve this litle problem?

Thanks

like image 828
iVanguard Avatar asked Mar 17 '26 03:03

iVanguard


1 Answers

The problem when you tag a question 'Javascript' and when you are actually using Google Apps Script is that you get nice answers from people that do not know some special functions available in GAS.

GAS is based on Javascript but Javascript is not GAS... if you see what I mean ;-)

That said, there is actually a "special" function to format date string and I'll show it in the following code.

But there is also another point that could put you into trouble : if you don't mention hours in your date object there is a risk to shift one day if you live in a country that uses daylight savings. This issue has been discussed quite often on this forum and elsewhere so I won't give all the details but it's a good idea to take this into account when you play with date objects. In the code below I extract a tz (time zone) string from the date object we have just created to know if it's in summer or in winter time, then I use this tz string as a parameter in the Utilities.formatDate() method . This guarantees an exact result in every situations.

Here is (finally) the test code : (use the logger to see results. script editor>view>logs)

function test(){
  date = "2012-08-9";
  var parts = date.split('-')
  var datum = new Date(parts[0],parts[1]-1,parts[2],0,0,0,0);// set hours, min, sec & milliSec to 0
  var tz = new Date(datum).toString().substr(25,8);// get the tz string
  Logger.log(datum+'    in TimeZone '+tz)
  datum.setDate(datum.getDate() + 1);// add 1 day
  var dateString = Utilities.formatDate(datum,tz,'yyyy-MMM-dd');// show result like you want, see doc for details
  Logger.log(dateString);// the day after !
  }

Logger results :

Thu Aug 09 2012 00:00:00 GMT+0200 (CEST)  in TimeZone GMT+0200
2012-Aug-10
like image 140
Serge insas Avatar answered Mar 19 '26 00:03

Serge insas