Google apps script if statement goes wrong - javascript

So, I am currently trying to check if a date from my Google spreadsheet cell matches some date I got from a HTML document. Here is the function that I use:
for (var i=0; i < data.length; i++) {
var testDate = subDaysFromDate(data[i][0],1)
var DateToCheck = Utilities.formatDate(testDate, "GMT", "dd-MM-yyyy");
var DateToCheckBefore = DateToCheck.split("-");
var DateToCheckAfter = new Date(DateToCheckBefore[2], DateToCheckBefore[1]-1, DateToCheckBefore[0]); //dit is de datum van een row
var d1 = $d1.split("-");
var d2 = $d2.split("-");
var from = new Date(d1[0], d1[1]-1, d1[2]); // -1 because months are from 0 to 11
var to = new Date(d2[0], d2[1]-1, d2[2]);
if(DateToCheckAfter >= from && DateToCheckAfter <= to){
var dataCheck = sheet.getRange("T2").getValue();
if(DateToCheckAfter == dataCheck){
Browser.msgBox('9 march?!', Browser.Buttons.OK);
}
Logger.log(dataCheck);
Logger.log(DateToCheckAfter);
}
}
As you can see it is obviously not finished yet, my question is; why does the following if statement not work??
if(DateToCheckAfter == dataCheck)
{
Browser.msgBox('9 march?!', Browser.Buttons.OK);
}
When I log the variables, the logger says:
[15-03-18 14:06:33:227 CET] Mon Mar 09 00:00:00 GMT+01:00 2015
[15-03-18 14:06:33:228 CET] Mon Mar 09 00:00:00 GMT+01:00 2015
So why is my if statement not working?

Well the answer was pretty simple..
DateToCheckAfter was a Date object and dataCheck was a string
if(DateToCheckAfter.toString() == dataCheck)
{
Browser.msgBox('9 march?!', Browser.Buttons.OK);
}
Fixed it

Related

How to list all month between 2 dates with moment.js?

I've two dates
2015-3-30 2013-8-31
How can I make a month list like:
[ '2015-3', '2015-2', '2015-1', '2014-12', '2014-11', '2014-10', '2014-09', '2014-08', '2014-07', '2014-06', '2014-05'....., '2013-08' ]
Thanks.
This should do it:
var startDate = moment('2021-12-31');
var endDate = moment('2022-12-14');
var betweenMonths = [];
if (startDate < endDate){
var date = startDate.startOf('month');
while (date < endDate.endOf('month')) {
betweenMonths.push(date.format('YYYY-MM'));
date.add(1,'month');
}
}
I think the original answer isn't entirely correct, as you wouldn't get '2015-3' in your array. This is due to the fact your start date would eventually end up as '2015-3-31' and would fail the conditional in place. You could extend it like below.
UPDATE: I've now included cloning the dateStart variable so it isn't mutated at all.
var dateStart = moment('2013-8-31');
var dateEnd = moment('2015-3-30');
var interim = dateStart.clone();
var timeValues = [];
while (dateEnd > interim || interim.format('M') === dateEnd.format('M')) {
timeValues.push(interim.format('YYYY-MM'));
interim.add(1,'month');
}
You could try with this example
var one = moment("2015-3-30");
var two = moment("2014-8-31");
var dateDiffs = [];
var count = Math.round(moment.duration(one.diff(two)).asMonths());
month = two.month() + 1;
year = two.year();
for (var i=1; i<=count; i++) {
if (month > 12) {
month = 1;
year++;
}
dateDiffs.push(year+"-"+month);
console.log(month);
month++;
}
console.log(dateDiffs);
You are using multiple formats in the output: YYYY-MM and YYYY-M, so I picked the first. You can edit as you see fit.
var startDateString = "2012-5-30";
var endDateString = "2015-8-31";
var startDate = moment(startDateString, "YYYY-M-DD");
var endDate = moment(endDateString, "YYYY-M-DD").endOf("month");
var allMonthsInPeriod = [];
while (startDate.isBefore(endDate)) {
allMonthsInPeriod.push(startDate.format("YYYY-MM"));
startDate = startDate.add(1, "month");
};
console.log(allMonthsInPeriod);
document.getElementById("result").innerHTML = allMonthsInPeriod.join("<br />");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
<div id="result"></div>
const getMonths = (start, end) =>
Array.from({ length: end.diff(start, 'month') + 1 }).map((_, index) =>
moment(start).add(index, 'month').format('MM.YYYY'),
);
const months = getMonths(moment('01.2019','MM.YYYY'),moment('01.2020','MM.YYYY'))
console.log(months)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
This is the best way in my opinion.
const startDate = moment('2013-8-31', 'YYYY-M-DD');
const endDate = moment('2015-3-30', 'YYYY-M-DD');
const months = [];
const flag = startDate;
while (flag.diff(endDate) <= 0) {
months.push(flag.format('YYYY-M'));
flag.add(1, 'M');
}
Why don't you just https://date-fns.org/v2.13.0/docs/eachMonthOfInterval ??
// Each month between 6 February 2014 and 10 August 2014:
var result = eachMonthOfInterval({
start: new Date(2014, 1, 6),
end: new Date(2014, 7, 10)
})
//=> [
// Sat Feb 01 2014 00:00:00,
// Sat Mar 01 2014 00:00:00,
// Tue Apr 01 2014 00:00:00,
// Thu May 01 2014 00:00:00,
// Sun Jun 01 2014 00:00:00,
// Tue Jul 01 2014 00:00:00,
// Fri Aug 01 2014 00:00:00
// ]

for in loop not working as expected javascript

I have an object, Object { 2014-01-30=[1], 2014-02-01=[1]}
and an array called fechasPeriodo,
so why is the following code:
fechasPeriodo = [];
for(var property in SelectedDates) {
fechasPeriodo.push(new Date(property));
}
producing this result [Date {Wed Jan 29 2014 18:00:00 GMT-0600}, Date {Fri Jan 31 2014 18:00:00 GMT-0600}]
Edit: I'd expect the result to be Thu Jan 30 2014 etc. , Sun 02 Feb 2014.
Actually it's a problem only because I'm trying to define a range of dates in datepicker using a Google Calendar feed. So the following code:
if(fechasPeriodo.length > 1) {
r[1] = fechasPeriodo[0] <= date && date <= fechasPeriodo[1] ?"Highlighted"+SelectedDates[key][0].replace(/\s/g, "_"):"Highlighted-unknown";
}
I'd expect to highlight a range from the 30th Jan to the 02nd of February. But if you can guide me as to why it isn't working, I'd be very grateful, I'm following this fiddle:
http://jsfiddle.net/qaEuj/
At the risk of being downvoted again I have to say that I still don't understand why my last bit of code above isn't working like the fiddle I mention, so here's my complete code:
$(document).ready(function() {
var fechaDefecto = new Date('2014/01/01');
var fechaFin = new Date('2014/08/31');
SelectedDates = null;
/*SelectedDates[new Date('12/25/2014')] = new Date('12/25/2014');
SelectedDates[new Date('12/12/2014')] = new Date('12/12/2014');
SelectedDates[new Date('06/06/2014')] = new Date('06/06/2014');*/
$('#tiposFechas').change(function() {
$.getJSON("https://www.google.com/calendar/feeds/cide.edu_sm151i2pdhu2371vq8hamcver4#group.calendar.google.com/public/full?q="+encodeURI($(this).val()), {"alt" : "json"}, function(data) {
SelectedDates = {};
$.each(data.feed.entry, function(i, entry) {
var key = entry.gd$when[0].startTime.substr(0, 10)
var clave = entry.gd$when[0].endTime.substr(0, 10);
if(key in SelectedDates === false || clave in SelectedDates === false) {
SelectedDates[key] = [];
SelectedDates[clave] = [];
}
SelectedDates[key].push(entry.title.$t);
SelectedDates[clave].push(entry.title.$t);
});
$('#cal').datepicker("refresh");
});
});
$('#cal').datepicker(
{
beforeShowDay: function (date) {
var r = [true, ""];
if (SelectedDates === null) {
r[1] = "Highlighted-unknown";
}
else {
fechasPeriodo = [];
for(var property in SelectedDates) {
fechasPeriodo.push(new Date(property));
//alert(property);
}
var key = $.datepicker.formatDate("yy-mm-dd", date);
if(key in SelectedDates) {
if(fechasPeriodo.length > 1) {
r[1] = fechasPeriodo[0] <= date && date <= fechasPeriodo[1] ?"Highlighted"+SelectedDates[key][0].replace(/\s/g, "_"):"Highlighted-unknown";
}
else {
r[1] = "Highlighted"+SelectedDates[key][0].replace(/\s/g, "_");
}
r[2] = SelectedDates[key].join(", ");
}
}
return r;
},
minDate : fechaDefecto,
maxDate : fechaFin,
numberOfMonths: [3,3]
});
});
I'm hoping someone points out a cause, even if it's a criticism, because it's getting late.
I must say I tried this:
r[1] = new Date(fechasPeriodo[0].getYear(), fechasPeriodo[0].getMonth(), fechasPeriodo[0].getDate()) <= date && date <= new Date(fechasPeriodo[1].getYear(),fechasPeriodo[1].getMonth(),fechasPeriodo[1].getDate()) ?"Highlighted"+SelectedDates[key][0].replace(/\s/g, "_"):"Highlighted-unknown";
But didn't work either. May there be a problem in the way I'm representing the dates when I call new Date in the line fechasPeriodo.push(new Date(property)); and the way I'm comparing them?
It's just the difference between the UTC and non-UTC representation.
new Date('2014-01-30').toString(); //Wed Jan 29 2014 19:00:00
new Date('2014-01-30').toUTCString(); //Thu, 30 Jan 2014 00:00:00
Try fechasPeriodo[0].toUTCString(); and I'm pretty sure it will return what you expect.

Working with Javascript dates, getting 0 or above 31

I am using this code to generate 5 dates for my 'calendar' from the current week:
var days = new Array(4);
GetDaysOfWeek(new Date());
function GetDaysOfWeek(date)
{
for (var i = 0; i < 5; i++)
{
var $dd = (date.getDate() - date.getDay() + 1 + i);
var $mm = date.getMonth()+1;
var $yyyy = date.getFullYear();
if($dd<10){$dd='0'+$dd}if($mm<10){$mm='0'+$mm}
days[i] = $dd+'/'+$mm+'/'+$yyyy;
}
}
However depending what date it is it can return 00/10/2013 or 32/10/2013 on some of my boxes. It seems the only one updating correct is the actual date I am on.
How would I update those 5 dates so I would get the correct dates instead of non exist dates.
Thanks in advance.
currentTimestamp = new Date().getTime()
currentDay = currentTimestamp-currentTimestamp%(24*60*60*1000)
for (var i = 1; i< 6; i++){
nextDay = new Date(currentDay + i*24*60*60*1000)
days[i] = nextDay.toString(); //specify the format yourself
}
Here's a somewhat shorter way of creating an array of the dates of 5 weekdays from a given date;
function weekdays(d){
// set date [d] (or today) to the sunday before
var d = (function(){
this.setDate(this.getDate()-(this.getDay()));
return this;
}).apply(d || new Date);
// create an Array with length 5 and map 5 dates starting
// from date [d] into it
return String(Array(5)).split(',')
.map(function(){
return new Date(this.setDate(this.getDate()+1));
}, d);
}
It returns the weekdays from the first monday before the date, or, if the given date is a sunday, the dates of the weekdays from the next week.
weekdays();
//=> [Mon Oct 21 2013 17:14:23 GMT+0200, ... ,Fri Oct 25 2013 17:14:23 GMT+0200]
weekdays(new Date('2013/10/06'));
//=> [Mon Oct 07 2013 00:00:00 GMT+0200, ..., Fri Oct 11 2013 00:00:00 GMT+0200]
See also: Mozilla DN on map
Maybe this jsfiddle is of use to you?

Check if dates match in javascript

I'm creating a custom ASP.Net validator that checks if the data entered is a non working day.
The definition of "non working day" is:
The date is either a Saturday or Sunday
The date is a national holiday
I've coded the c# stuff and have created expando attributes for the error message and a string of holiday dates. Having done that, I've created a javascript function that contains this code to check for none working days. I've removed other code for brevity.
if (sender.NonWorkingDayErrorMessage && sender.Holidays) {
// Is weekend
if (date.getDay() == 6 || date.getDay() == 0) {
sender.innerHTML = sender.NonWorkingDayErrorMessage;
return;
}
// Is holiday
var holidays = sender.Holidays.split(";");
for (var i = 0; i < holidays.length; i++) {
var h = new Date(Date.parse(holidays[i]));
if (h === date) {
sender.innerHTML = sender.NonWorkingDayErrorMessage;
return;
}
}
}
The issue I have is that the code h === date is always false - here's the output I get when I add an alert and type in 26/8/2013.
Mon Aug 26 2013 00:00:00 GMT+0100 (GMT Standard Time) => Mon Aug 26 2013 00:00:00 GMT+0100 (GMT Standard Time) => false
As you can see I parse the holidays but I also test the input 'date' like this further up the function like this:
// Deconstruct string and reconstruct
// as date.
var parts = args.Value.split("/");
var day = parseInt(parts[0],10);
var month = parseInt(parts[1],10) -1;
var year = parseInt(parts[2],10);
var date = new Date(year, month, day);
// Valid date format but not a valid date
if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
sender.innerHTML = sender.InvalidErrorMessage;
return;
}
Anyone got ideas as to why these two dates aren't seen as matches?
Try like this
var a = new Date(2013,12,1);
var b = new Date(2013,12,1);
a.getTime() === b.getTime()

Writing a complicated if statement in js

I have a list of years with id, from date and to date as follows:
id from_date to_date
1 2013-02-12 2013-02-22
2 2013-03-01 2013-03-28
3 2013-03-29 2013-04-15
and so on
I am having problems with overlapping dates if condition. I want to edit from_date of id 2 to a date in between 2013-02-22 and 2013-03-01 or to_date of period 1 to a date in between 2013-02-22 and 2013-03-01, but it only allows 1 as per my code below.
Here is a snippet of my code:
function validate(id){
//id is passed as a parameter to the function
from_date = document.getElementById('from_date_' + id);
to_date= document.getElementById('to_date_' + id);
var from = new Date();
var to = new Date();
// I am able to split the string, .split("-") and convert it in date format
previous_to_date = document.getElementById("to_" + id);//id is one less
next_from_date = document.getElementById("from_date_" + id);//id is one more
current_from_date //I store it before editing the from date
current_to_date //Similarly for current from date
//from_date and to_date are the edited dates by the user
if (from_date > to_date){ alert("This date is invalid"); return false; }
//now to check for overlapping dates
**//This is the condition I am having problems with**
if ((from_date < current_from_date && from_date < previous_to_date) || (to_date > current_to_date && to_date > next_from_date) && from_date > current_to_date){
alert("These dates overlap,Please select another date");
return false;
}
//successful so now we submit the form...
}
In simpler terms if there is a gap between the from date on current
period and the to date of the previous period, i should be able to
edit the change to minimize the gap to at most 1.
var to_previous = "2013-02-22"
var from = "2013-03-01"
var to_previous_millis = Date.parse(to_previous);
var from_millis = Date.parse(from);
one_day = 1000*60*60*24;
while( (from_millis - to_previous_millis) >= one_day) {
current = new Date(from_millis);
console.log(current.toUTCString());
from_millis -= one_day
}
--output:--
Fri, 01 Mar 2013 00:00:00 GMT
Thu, 28 Feb 2013 00:00:00 GMT
Wed, 27 Feb 2013 00:00:00 GMT
Tue, 26 Feb 2013 00:00:00 GMT
Mon, 25 Feb 2013 00:00:00 GMT
Sun, 24 Feb 2013 00:00:00 GMT
Sat, 23 Feb 2013 00:00:00 GMT
var attempts = [
"2013-2-28",
"2013-2-23",
"2013-2-22"
];
var len = attempts.length;
for (var i=0; i < len; ++i) {
var attempt = attempts[i];
attempt_millis = Date.parse(attempt);
if (attempt_millis >= (to_previous_millis + one_day) ) {
console.log(attempt + " : valid change");
}
else {
console.log(attempt + " : invalid change");
}
}
--output:--
2013-2-28 : valid change
2013-2-23 : valid change
2013-2-22 : invalid change

Categories