Google Script EPOCH date creation - javascript

I have a Google Script that needs to get 2 specific dates.
1) The second day of the previous month at 8 am GMT
2) The first day of the current month at 8 am GMT
Both dates need to be converted to EPOCH times.
I built this on a JS Fiddle:
var a = new Date();
var year = a.getFullYear();
var month = a.getMonth();
if(month === 0){
var startDate = new Date((year-1)+'-12-02 08:00 GMT');
var endDate = new Date(year+'-'+(month+1)+'-01 08:00 GMT');
}else{
var startDate = new Date(year+'-'+month+'-02 08:00 GMT');
var endDate = new Date(year+'-'+(month+1)+'-01 08:00 GMT');
}
This works perfectly fine, however when I use that in Google Script, the new Date() fails and returns NaN. I've read that it has to do with the JS version that Google Script uses, but couldn't find anything on how to format that string above to go through cleanly.
What is the correct format?

1) Replace the - in your date string with /.
2) For epoc do Date.getTime() /1000

Related

How to get the date of last day of week with a specific timezone using js

I want to get date of the last day of week with a specific timezone.
I got this code that works good but it shows the computer timezone. i want to add a specific timezone like GMT-0500
{
var lastday = date.getDate() - (date.getDay() - 1) + 6;
return new Date(date.setDate(lastday));
}
dt = new Date();
dt.setHours(23,59,59,999);
document.getElementById("lastday").innerHTML = endOfWeek(dt).toString();
console.log(endOfWeek(dt).toString());
How can i change the timezone? please help.

JavaScript simple date validation

I try to validate a date entered by the user. It must be today or a later date. How I can do that?
Why the condition in the code below is false?
var today = new Date();
var idate = new Date('02/09/2014');
if(today > idate) {
alert('your date is big');
}
If I set today then it is today's date and also I pass in idate then it is also today's date then how can I compare dates?
Here is JSFiddle: http://jsfiddle.net/0osh0q8a/1/
A few things to consider.
When you're creating a new Date object from a string representation, do it in the format YYYY-MM-DD. This will avoid problems with locale.
When comparing two dates, if the time can be ignored, set both to the exactly same time. It looks to be the case here.
Finally, use Date.parse() to make sure your object is a valid date and make it possible to be compared.
var today = new Date();
var idate = new Date('2014-09-02');
// The date entered by the user will have the same
// time from today's date object.
idate.setHours(today.getHours());
idate.setMinutes(today.getMinutes());
idate.setSeconds(today.getSeconds());
idate.setMilliseconds(today.getMilliseconds());
// Parsing the date objects.
today = Date.parse(today);
idate = Date.parse(idate);
// Comparisons.
if (idate == today) {
alert('Date is today.');
}
else if (idate < today) {
alert('Date in the past.');
}
else if (idate > today) {
alert('Date in the future.');
}
Demo
As a side note, when you face hard-to-solve date/time calculations, manipulations, etc, you can use the Moment.js library. It's really useful: Moment.js
the default data parser is reading your idate as 9th febuary 2014, hence today is greater than idate
If you set idate to 09/04/2014 the code runs as expected
var today = new Date();
var idate = new Date('09/04/2014');
console.log(today);
>>>Tue Sep 02 2014 11:48:52 GMT+0100 (BST)
console.log(idate);
>>>Thu Sep 04 2014 00:00:00 GMT+0100 (BST)
You have 2 problems.
The date culture and the time part.
First off, new Date() picks-up the current date, with the current browser's culture plus the time part.
new Date('09/04/2014') does not add a time part, so it starts at 00:00:00 and the culture again depends on the browser. So it may mean 9th of March or 4th of Sept depending on culture.
Remember, that new Date() contains the time part.
If you don't care about the time, create the today date like this:
var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDay());
Another thing is that JS date formatting is 'mm/dd/yyyy'. So change your 'idate' like this:
var idate = new Date('09/02/2014');
You can use < and > to compare the dates. But == will always return false, to check if 2 dates are equal use: if(today.getTime() == idate.getTime())
See the updated fiddle: http://jsfiddle.net/0osh0q8a/3/

See if date selected is future from today - JavaScript

I have to compare the date that they want to put in and the current date today, and if they have put in a date that is in the future, then alert them to change the date, otherwise insert the data.
Basically I am having issues comparing the dates. here is my code:
var today = year + '-' + month + '-' + day + ' 00:00:00';
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
var d2 = new Date(today); // todays date
if(d1>d2){
alert('You cannot post in the future!');
}
But that doesnt seem to work. Where am I going wrong?
Convert the dates into a comparable number, like milliseconds.
if(d1.valueOf()>d2.valueOf()){
alert('You cannot post in the future!');
}
You don't need to create a new variable today.
If by today you are trying to get today's date, you can simply do
var today = new Date();
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
//----------
var d2 = new Date(year,month,day); // todays date
//----------
if(d1>d2){
alert('You cannot post in the future!');
}
Remember month is 0 based index. So, for december it would be 11.
Compare the dates with the same format, if today is 2014-01-24 00:00:00 then postdate also should be 2014-02-01 00:00:00
Then use + prefix to compare milliseconds:
if(+d1 > +d2){
alert('You cannot post in the future!');
}

How can I add a day to user's input? [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 9 years ago.
I have a textfield that inputs date in this format: yyyy-mm-dd, how can I add a day to that users input? I have the following code but it doesnt work...
users_date = document.getElementById('users_date').value;
var date = new Date(users_date);
var next_date = new Date();
next_date .setDate(date.getDate()+1);
document.getElementById('next_date').value = next_date;
The first problem is the format of the date in the second is like 'Mon Aug 05 2013 16:24:40 GMT-0500 (Hora est. Pacífico, Sudamérica)'
The second problem is that when the user input the fist day of the month like '2013-01-01' or '2013-08-01' it displays 'Sun Sep 01 2013 16:26:06 GMT-0500 (Hora est. Pacífico, Sudamérica)' ALWAYS
For example if user inputs 2013-01-01 I want another textfield to be 2013-01-02 or 2013-08-31 it displays 2013-09-01, how can I do that?
Thanks!!
ITS NOT DUPLICATE BECAUSE THE OTHER POST DOESN'T FORMAT THE DATE!!!!
Prior to ES5 there was no standard for parsing dates. Now there is a format that is a version of ISO8601, however it isn't supported by all browsers in use and is not typically used for user input.
Normally a format is requested or a "date picker" used that returns a specific format. From there, it's quite simple to parse the string to create a Date object:
// s is date string in d/m/y format
function stringToDate(s) {
var b = s.split(/\D/);
return new Date(b[2], --b[1], b[0]);
}
For ISO8601 format (y-m-d), just change the order of the parts:
// s is date string in y/m/d format
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
To add one day to a Date object, just add one day:
var now = new Date();
var tomorrow = now.setDate(now.getDate() + 1);
This should work:
var date = new Date(document.getElementById('users_date').value);
var next_date = new Date(date.getTime() + 24*60*60*1000); // adding a day
document.getElementById('next_date').value = next_date.getFullYear() + "-" +
(next_date.getMonth()++) + "-" + next_date.getDate();
Please, note that Date#getMonth() is zero-based. Hence, the increment.

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

Categories