Changing Pentaho date values to first and last day of the week in Javascript Modified Value - pentaho-spoon

I am trying to set two variables to the first and last day of the week for a given date, but the .setDate() method does not seem to be changing the date and 'lastday' and 'firstday' variables return an Invalid Date (1970)
DateNew is from my input step which is defined as dd/MM/yyyy format
var curr = DateNew;
var first = getDayNumber(curr,"d") - getDayNumber(curr,"wm")
var last = first + 7;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

Declaring the input variable as a date seemed to resolve the issue as there was no javascript type associated with it.
var curr = new Date(DateNew);
var first = getDayNumber(curr,"d") - getDayNumber(curr,"wm")
var last = first + 7;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

Related

Comparing dates in google app script one comparison works and one doesn't

I am trying to loop through some dates in a spreadsheet and come up with a date range earliest and last dates. Currently my variable lastdate works well. I can't figure out why firstdate isn't working as all that is done is I reversed the comparator (> to <) and changed variable names. The date1 variable is a date in the past month.
I have also tried this with if (date1.getTime() < firstDate.getTime()) firstDate = date1; and if (date1.toString() < firstDate.toString()) firstDate = date1;as suggested in other threads to no avail.
IAny help would be greatly appreciated! Thanks in advance!
--dwb
'''
var firstDate = new Date(2075,01,01);
firstDate = Utilities.formatDate(firstDate, "GMT-5", 'MM/dd/YYYY');
var lastDate = new Date(2000,01,01);
lastDate = Utilities.formatDate(lastDate, "GMT-5", 'MM/dd/YYYY');
tables.forEach(table => { // Selecting correct table based on cell (0,0) = "Date"
if(table.getCell(0,0).getText() == "Date"){
rows.forEach(function(row,index){
var date1 = Utilities.formatDate(row[0], "GMT-5", "MM/dd/yyyy");
// Calculating First and Last Date
if (date1.valueOf() < firstDate.valueOf()) firstDate = date1;
if (date1.valueOf() > lastDate.valueOf()) lastDate = date1;
'''
I got it working. Code is below. Note that to make it readable in the end you have to print out the date using Utilies.formatDate().
Bonus points if someone can tell me why the lastDate from the original problem worked and the firstDate did not.
Cheers,
--dwb
var date1 = new Date(row[0]).setHours(0,0,0,0);
var firstDate= new Date("01/01/2075").setHours(0,0,0,0);
var lastDate= new Date("01/01/2000").setHours(0,0,0,0);
// Calculating First and Last Date
if (date1.valueOf() < firstDate.valueOf()) firstDate = date1;
if (date1.valueOf() > lastDate.valueOf()) lastDate = date1;
//Format Date into readable format
body.replaceText('{{Last Date}}', Utilities.formatDate(new Date(lastDate),'GMT-5','MM-dd-yyyy'));
The valueOf() a string is different than the valueOf() a Date() object
Utilities.formatDate() returns a string not a Date() object
Try rewritting the section this way:
var firstDate = new Date(2075,01,01);
var lastDate = new Date(2000,01,01);
tables.forEach(table => {
if(table.getCell(0,0).getText() == "Date"){
rows.forEach(function(row,index){
var dt = new Date(row[0]);
var date1 = new Date(dt.getFullYear(),dt.getMonth(), dt.getDate());
if (date1.valueOf() < firstDate.valueOf()) firstDate = date1;
if (date1.valueOf() > lastDate.valueOf()) lastDate = date1;
You have to be careful with valueOf() because a lot of functions have a valueOf() function but they are different for different types of objects

Compare data with present date google script

Hi i want to compare column with date (i.e "Referral Date" column)
with present day , here is what i have
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
for (i=0;i<range.getLastRow();i++){
var dates = searchRange.getValues();
if (today.valueOf()>dates.valueOf()){
updatelFilter()
} else{
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
The problem i have is, it throws alert Future Date Error irrespective of date in column (Referral Date). Let me know if additional information is required.
My goal:
1)if date column (Referral Date) is greater than present date : Throw alert error & should not run updateFilter
2)if (Referral Date) is lesser than present date: Run updateFilter function
Issues
searchRange.getValues() yields a two dimensional array. So dates[0][0] points to a date, while dates[0] points to an array.
var dates = searchRange.getValues(); is being called inside the loop repeatedly, when it should ideally be called outside once since the value will not change; calling it inside the loop is costly and redundant
for (i=0;i<range.getLastRow();i++){ the condition can be replaced with i<dates.length if point 2 is followed
if (today.valueOf()>dates.valueOf()){ I believe is supposed to have dates[0] instead
Modified Code
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
var dates = searchRange.getValues().map(d=>d[0]);
for (i=0;i<dates.length;i++) {
if (today.valueOf()>dates[i].valueOf()){
updateFilter()
} else {
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
To run updateFilter only if no future dates
Replace the loop with the following -
if(dates.some(d => today.valueOf() < d.valueOf())) {
SpreadsheetApp.getUi().alert('Future Date Error');
} else {
for (let i=0; i<dates.length; i++) {
updateFilter();
}
}

How to pull date from cell and compare it to today's date

I am using a spreadsheet to manage certification expiration dates. I want to send an email to an employee when their certification is expiring within 90 days. I only want to send one email. I am struggling getting the date from the cell and comparing it to today's date.
I want to send an email if Todays Date + 90 days in MS is > certification expiration date in MS.
I started using a template to prevent sending duplicate emails. I got it working with if && with words in two cells. I am struggling getting the dates to work. I have tried using getTime() to get the dates in MS but getValues().getTime returns an error.
var EMAIL_SENT = 'EMAIL_SENT';
var NintyDayInMs = 90*24*60*60*100;
var Today = new Date().getTime();
var expired = Today+NintyDayInMs;
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 4);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var emailSent = row[2]; // Third column
var exp = row[3]; // Fourth column
var expDate = exp.getTime();
if (emailSent != EMAIL_SENT && expDate < expired) { // Prevents
sending duplicates
var subject = 'Sending emails from a Spreadsheet';
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is
interrupted
SpreadsheetApp.flush();
}
}
}
My current code results in
TypeError: Cannot find function getTime in object (Date in cell).
(line 26, file "Code")
Read Adding Days to a Date - Google Script for a better understanding of date arithmetic in scripts.
The flaw is in trying to chain the expiry date. Instead of:
var exp = row[3]; // Fourth column
var expDate = exp.getTime();
use just:
var expDate = new Date(row[3]); // make the sheet value a date object
Then the rest goes naturally...
var expDate = new Date(row[3]); // make the sheet value a date object
Logger.log("expiry = "+expDate);
var today = new Date();
Logger.log("today = "+today);
var today90 = new Date(today.getTime()+90*3600000*24);// 90 days from today
Logger.log("today90 = "+today90);
if ((today90 > expDate) && (emailSent!=EMAIL_SENT)){
Logger.log("send the email");
}
else
{
Logger.log("don't send the email");
}

From Google Forms to Google Calendar - Date and TIme issues

I am trying to modify a script I found online that seems to make the event an all day event, which I don't want, I want it to be just the time specified in the form/spreadsheet.
The spreadsheet is located here - https://docs.google.com/spreadsheet/ccc?key=0ApxazoOhNSK-dGFvZVhVOTQ1X3F3aWh4QTh3Wm9sbFE#gid=0
Here is the script I am using, but its not adding...
//this is the ID of the calendar to add the event to, this is found on the calendar settings page of the calendar in question
var calendarId = "<removed for privacy>";
//below are the column ids of that represents the values used in the spreadsheet (these are non zero indexed)
var startDtId = 4;
var endDtId = 4;
var titleId = 2;
var titleId2 = 3;
var descId = 7;
var tstart = 4;
var tstop = 5;
var formTimeStampId = 1;
function getLatestAndSubmitToCalendar() {
var start = new Date(sheet.getRange(lr,tstart,1,1).getValue());
var end = new Date(sheet.getRange(lr,tstop,1,1).getValue());
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var subOn = "Submitted on :"+sheet.getRange(lr,formTimeStampId,1,1).getValue()+" by "+sheet.getRange(lr,titleId,1,1).getValue();
var desc = "Comments: "+sheet.getRange(lr,descId,1,1).getValue()+"\n"+subOn;
var title = sheet.getRange(lr,titleId,1,1).getValue()+" "+sheet.getRange(lr,titleId2,1,1).getValue();
createEvent(calendarId,title,start,end,desc);
}
function createEvent(calendarId,title,start,end,desc) {
var cal = CalendarApp.getCalendarById(calendarId);
var start = new Date(sheet.getRange(lr,tstart,1,1).getValue());
var end = new Date(sheet.getRange(lr,tstop,1,1).getValue());
var loc = 'Computer Center';
var event = cal.createEvent(title, start, end, {
description : desc,
location : loc
});
};
The original article is located here: http://bruceburge.com/2012/09/05/automatically-adding-events-to-a-google-calendar-from-a-google-form-submission/
I just can't seem to get the dates to work at all... If I use the original code it works fine, but the time is the full day, not the specified time... I seem to have broken it in an attempt to make it work... Any help would be appreciated...
It was a lot simpler than I though... I just removed some of his lines (the ones that set the hour and minutes to 0. Once I removed that and changed a few things, I get the following which works just great:
//this is the ID of the calendar to add the event to, this is found on the calendar settings page of the calendar in question
var calendarId = "alcc.ccenter#gmail.com";
//below are the column ids of that represents the values used in the spreadsheet (these are non zero indexed)
var startDtId = 4;
var endDtId = 5;
var titleId = 2;
var titleId2 = 3;
var descId = 7;
var formTimeStampId = 1;
function getLatestAndSubmitToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var startDt = sheet.getRange(lr,startDtId,1,1).getValue();
//set to first hour and minute of the day.
var endDt = sheet.getRange(lr,endDtId,1,1).getValue();
//set endDt to last hour and minute of the day
var subOn = "Added :"+sheet.getRange(lr,formTimeStampId,1,1).getValue()+" by: "+sheet.getRange(lr,titleId,1,1).getValue();
var desc = "Comments :"+sheet.getRange(lr,descId,1,1).getValue()+"\n"+subOn;
var title = sheet.getRange(lr,titleId,1,1).getValue()+" - "+sheet.getRange(lr,titleId2,1,1).getValue();
createEvent(calendarId,title,startDt,endDt,desc);
}​
function createEvent(calendarId,title,startDt,endDt,desc) {
var cal = CalendarApp.getCalendarById(calendarId);
var start = new Date(startDt);
var end = new Date(endDt);
var loc = 'Computer Centre';
var event = cal.createEvent(title, start, end, {
description : desc,
location : loc
});
};
My form has the following Columns - Timestamp, Name, Absence, Start, End, Reason, Comments. They didn't need to be ne word but I changed them to one word headings because of the video example I was trying to follow... But the above code works miracles.
I had to modify the way Forms handles dates to accommodate Calendar
function createEvent() {
var form = FormApp.getActiveForm();
var cal = CalendarApp.getDefaultCalendar();
var responses = form.getResponses();
var len = responses.length;
var last = len – 1;
var items = responses[last].getItemResponses();
var email = responses[last].getRespondentEmail();
var name = items[0].getResponse();
var bring = items[1].getResponse();
var date = items[2].getResponse();
Logger.log(date);
var replace = date.replace(/-/g,”/”);
Logger.log(replace);
var start = new Date(replace);
Logger.log(‘start ‘+start);
//Logger.log(newStart.getHours());
var endHours = 2+0+start.getHours();
//Logger.log(start.getDay());
var day = start.getDate();
var minutes = start.getMinutes();
var year = start.getFullYear();
var month = start.getMonth();
var hours = start.getHours();
var d = new Date(year, month, day, endHours, minutes);
Logger.log(d);
var event = cal.createEvent(‘Class Party ‘+name+’ brings ‘+bring, start, d)
.addGuest(email)
.setDescription(name+’ you will be bringing ‘+bring+’ to the party.’);
GmailApp.sendEmail(email, name + ’ a Google Calendar invite has been created for you’, name + ’ You filled out the Google Form for the date of ‘ + start + ’. Check your Google Calendar to confirm that you received the invite.\n’);
}

Difference of two locale date in jquery

I am getting the date from CJuidatepicker with language such de,en,nl.
Now i need to find the difference between two dates in jquery accordnig to the language selected.
My Code is
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate()-1;
var output = d.getFullYear() + '-' +
((''+month).length<2 ? '0' : '') + month + '-' +
((''+day).length<2 ? '0' : '') + day;
var dateString1 = $('#Jobs_valid_date').val();
var dateString2= output;
var dateDiff = function ( dateString2, dateString1 ) {
var diff = Math.abs(dateString2 - dateString1);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000);
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000);
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000);
} else {
return "< 1 minute";
}
};
var new_date = dateDiff(new Date(dateString2), new Date(dateString1));
var sum = (parseInt(new_date * feature) + parseInt(fixed))
It retuns NAN.. Please help me to solve this
Doing it from scratch is not recommended for several reasons. If using a library is not a constraint, use moment.js. It has methods to calculate date differences. It has internationalization support too. In case your locale is not supported you can add it yourself. If you add a new locale, you are welcome to contribute it to the moment.js community.
Try this out, this worked for me. I wanted to calculate difference between the 2 dates which the client inputs.
function calculate(start_date,end_date)
{
var t1= start_date ;
var t2= end_date;
// The number of milliseconds in one day
var one_day=1000*60*60*24;
//Here we need to split the inputed dates to convert them into standard format
var x=t1.split(“/”);
var y=t2.split(“/”);
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0]);
//Calculate difference between the two dates, and convert to days
numberofDays=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
// numberofDays gives the diffrence between the two dates.
$(‘#Input_type_text).val(numberofDays);
}