Run JQuery Function on Page Load and Store the Result - function

I've got a script that hides most of the page when you first load the webpage.
When it does this, I want it to run a function which gets the current date, then saves it.
I've having trouble getting to do this for a few reasons.
Here is the page load code, where it hides the page if it's not been setup:
$(document).ready(
function() {
if (setup=="true") {
$("#show-page").show();
loadSetup();
} else {
$("#page-nav").hide();
}
});
Here is the date function:
function getStartDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getYear();
var startDate = dd + (mm * 30) + (yyyy * 360)
//edit
// return startDate
$("#start-date").val(startDate);
localStorage.startDate = $("#start-date").val();
}
I then want an if function in the first part of the loading page which says if the stored start date + 30 is less than the current date, show a message that gives them an updated url (isNewUrlNeeded()).
This was my attempt:
$(document).ready(
function() {
if (setup=="true") {
$("#show-page").show();
loadSetup();
isNewUrlNeeded();
} else {
$("#page-nav").hide();
getStartDate();
}
});
The problem here is that the getStartDate value isn't stored and I'm not sure how to store it. The reason it needs to be stored is so I can call on it later in the function isNewUrlNeeded.
Any help would be greatly appreciated.
Thank you!
Kind Regards,
Gary

You can try this :
function getStartDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getYear();
var startDate = dd + (mm * 30) + (yyyy * 360)
$("#show-page").data("start-date", startDate);
}
To retrieve this date you could do the follow :
var startDate = $("#show-page").data("start-date");

Related

two different hours subtraction Angular 6

I am trying to do how to subtract two different hours that is captured:
Here is TS code
clockingIn() {
var dt = new Date()
this.clockedIn= new Date().getHours()+':'+ new Date().getMinutes()+':'+ new Date().getSeconds();
console.log('clockin', this.clockedIn);
this.disableClockIn = true;
this.disableClockOut = false;
}
clockingOut() {
var dt2 = new Date();
this.clockedOut= new Date().getHours()+':'+ new Date().getMinutes()+':'+ new Date().getSeconds();
console.log('clockout', this.clockedOut);
this.disableClockIn = false;
this.disableClockOut = true;
}
subtraction() {
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
}
//table
test() {
const data = {
dateClock: this.dateobj(),
Job: this.selectedJob,
clockI: this.clockedIn,
clockO: this.clockedOut,
Hoursworked: this.subtraction()
};
this.dataSource.data.push(data);
this.refresh();
console.log(this.dataSource);
}
So this is a clock in and Clock out.
I want these two can calculate (Clock Out - Clock In) to see the difference of two hours in the table that I made. So this way, I can see the diff time between Clock Out and Clock In.
I am assuming your duration will be calculated in subtraction function.
Below changes will get the result :
subtraction() {
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
// I have set to minutes. Change unit as per your requirement by
// referring doc given as reference
var unit = 'm';
return moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"), unit);
}
Moment.js duration

Google Script for Gmail not consistent

I have a filter that adds the "unprocessed" label on all incoming emails.
Then a Google Script searches every minute for any email threads that have the "unprocessed" label, processes the messages, and conditionally apply a label to the corresponding thread.
I don't know what I have done wrong, but only SOME of the processed threads get the label. And it works randomly... For example only 3 out of 6 threads got the label, or 1 out of 3.
I have to re-apply the "unprocessed" label, and just run the script again to fix them.
function processGmail() {
var startTime = new Date().getTime();
var mailerRegex = /X-Mailer:(.*)/g;
var scannerLabel = GmailApp.getUserLabelByName("Scanner");
var unprocessedLabel = GmailApp.getUserLabelByName("unprocessed");
var countMessages = 0;
GmailApp.search("label:unprocessed").forEach(
function(emailThread) {
emailThread.getMessages().forEach(
function(message) {
var raw = message.getRawContent();
var result;
var doReturn = false;
while((matches = mailerRegex.exec(raw)) !== null) {
if (matches.some(function(match){return match.indexOf('Canon MFP') >= 0;})) {
emailThread.addLabel(scannerLabel);
emailThread.moveToArchive();
doReturn = true;
break;
}
}
emailThread.removeLabel(unprocessedLabel);
++countMessages;
if (doReturn) {
return;
}
}
);
}
);
var endTime = new Date().getTime();
Logger.log("Processed " + countMessages + " in " + (endTime-startTime) + "ms.");
}
Turns out the bug was Javascript related.
I had forgotten that the regex.exec needs to be looped until a null is returned, only then it will start a-new for a new input.
The fix was removing break :)

Funky IE JSON conversions

When running our AngularJS app in IE11 everything looks great in the debugger, but when our app encodes the data as JSON to save to our database, we get bad results.
Our app obtains a record from our database, then some manipulation is done and then the data is saved back to the server from another model.
Here is the data I got back from the server in the setAttendanceGetSInfo() function below:
{"data":{"Start":"2014-10-16T19:36:00Z","End":"2014-10-16T19:37:00Z"},
This is the code used to "convert the data" to 3 properties in our model:
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: new Date(e).toLocaleDateString(),
examStartTime: (new Date(e)).toLocaleTimeString(),
examEndTime: (new Date(f)).toLocaleTimeString()
});
return result.sInfo;
});
};
fromISO is defined as:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Take a look at the screenshot of the event model data:
But, if I eval the event model using JSON.stringify(model.event), I get this:
{\"examDate\":\"?10?/?16?/?2014\",\"examStartTime\":\"?2?:?44?:?00? ?PM\",\"examEndTime\":\"?2?:?44?:?00? ?PM\"}
And this is the JSON encoded data that actually got stored on the DB:
"examDate":"¿10¿/¿16¿/¿2014","examStartTime":"¿2¿:¿36¿:¿00¿ ¿PM","examEndTime":"¿2¿:¿37¿:¿00¿ ¿PM"
What is wrong here and how can I fix this? It works exactly as designed in Chrome and Firefox. I have not yet tested on Safari or earlier versions of IE.
The toJSON for the date class isn't defined perfectly the same for all browsers.
(You can see a related question here: Discrepancy in JSON.stringify of date values in different browsers
I would suspect that you have a custom toJSON added to the Date prototype since your date string doesn't match the standard and that is likely where your issue is. Alternatively, you can use the Date toJSON recommended in the above post to solve your issues.
First, I modified the fromISO prototype to this:
(function () {
var D = new Date('2011-06-02T09:34:29+02:00');
if (!D || +D !== 1307000069000) {
Date.fromISO = function (s) {
var D, M = [], hm, min = 0, d2,
Rx = /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D = s.substring(0, 10).split('-');
if (s.length > 11) {
M = s.substring(11).match(Rx) || [];
if (M[1]) D = D.concat(M[1].split(':'));
if (M[2]) D.push(Math.round(M[2] * 1000));// msec
}
for (var i = 0, L = D.length; i < L; i++) {
D[i] = parseInt(D[i], 10);
}
D[1] -= 1;
while (D.length < 6) D.push(0);
if (M[4]) {
min = parseInt(M[6]) * 60 + parseInt(M[7], 10);// timezone not UTC
if (M[5] == '+') min *= -1;
}
try {
d2 = Date.fromUTCArray(D);
if (min) d2.setUTCMinutes(d2.getUTCMinutes() + min);
}
catch (er) {
// bad input
}
return d2;
}
}
else {
Date.fromISO = function (s) {
return new Date(s);
}
}
Date.fromUTCArray = function (A) {
var D = new Date;
while (A.length < 7) A.push(0);
var T = A.splice(3, A.length);
D.setUTCFullYear.apply(D, A);
D.setUTCHours.apply(D, T);
return D;
}
Date.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
})()
Then I added moment.js and formatted the dates when they get stored:
var SaveAffRow = function () {
// make sure dates on coursedate and event are correct.
var cd = model.a.courseDate;
var ed = model.event.examDate;
var est = model.event.examStartTime;
var eet = model.event.examEndTime;
model.a.courseDate = moment(cd).format("MM/DD/YYYY");
model.event.examDate = moment(ed).format("MM/DD/YYYY");
model.event.examStartTime = moment(est).format("MM/DD/YYYY hh:mm A");
model.event.examEndTime = moment(eet).format("MM/DD/YYYY hh:mm A");
affRow.DocumentsJson = angular.toJson({a: model.a, event: model.event});
var aff = {};
if (affRow.Id != 0)
aff = affRow.$update({ Id: affRow.Id });
else
aff = affRow.$save({ Id: affRow.Id });
return aff;
};
and when they get read (just in case they are messed up already):
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: moment(e).format("MM/DD/YYYY"),
examStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
examEndTime: moment(f).format("MM/DD/YYYY hh:mm A")
});
return result.sInfo;
});
};

dojox.calendar and JsonRest - how to update?

I'm very new to dojo, so please bear with me. I'm currently working on creating a dojo calendar, with events sourced from a database. The calendar defaults to the grid (monthly) view, and on load, makes an initial call to get the first set of events. The default view makes a call to get the current months events +/- one week. I'm using a JsonRest object in an Observable to accomplish this.
This is currently working without issue. Where I'm having an issue is pulling / updating data for other months. The desired effect is to have the user click the forward or back button to move to the next or previous month. When this occurs, I would like to query the database for the new events to display. I'm able to return the new data and log it to the console, but I cannot get it to display on the calendar. I'm sure I'm missing something (hopefully) simple, but I cant figure it out, or find any good documentation. Here's what I have:
require(['dojo/parser',
'dojo/ready',
'dojox/calendar/Calendar',
'dojo/store/Observable',
'dojo/store/JsonRest',
'dijit/registry'],
function(parser, ready, Calendar, Observable, JsonRest, registry) {
ready(function(){
var MM = new Date().getMonth() + 1;
if (MM < 10)
{ MM = '0' + MM};
var YYYY = new Date().getFullYear();
var monthStore = new Observable(JsonRest({target: '/levelx/teamSchedule/getMonthInfo/'}));
calendar = new Calendar({
store: monthStore,
dateInterval: 'month',
style: styleText,
editable: false,
cssClassFunc: function(e){
return e.calendar;
},
query: '?q=' + YYYY + '-' + MM
}, 'calendar');
calendar.on("timeIntervalChange",function(e){
var YYYY = e.startTime.getFullYear();
var MM = e.startTime.getMonth() + 1;
if (MM < 10)
{ MM = '0' + MM};
monthStore.query('?q=' + YYYY + '-' + MM).then(function(results){
console.log(results);
});
});
I feel like I'm so close. Like I said, I have the correct data being returned to the console (console.log(results)), but no clue how to get it to show in the actual calendar.
I was able to accomplish what I needed with the following modifications. Whenever the user changes the displayed date range, it will automatically run a query to gather and display the proper events.
require(['dojo/parser',
'dojo/ready',
'dojox/calendar/Calendar',
'dojo/store/JsonRest',
'dijit/registry',
'dojo/dom',
'dojo/html'],
function(parser, ready, Calendar, JsonRest, registry, dom, html) {
ready(function(){
var MM = new Date().getMonth() + 1;
if (MM < 10)
{ MM = '0' + MM};
var YYYY = new Date().getFullYear();
var detailStore = JsonRest({target: '/levelx/teamSchedule/getDayInfo/'});
var monthStore = JsonRest({target: '/levelx/teamSchedule/getMonthInfo/'});
calendar = new Calendar({
dateInterval: 'month',
style: styleText,
editable: false,
cssClassFunc: function(e){
return e.calendar;
}
}, 'calendar');
calendar.on("timeIntervalChange",function(e){
var YYYY = e.startTime.getFullYear();
var MM = e.startTime.getMonth() + 1;
if (MM < 10)
{ MM = '0' + MM};
calendar.set('query','?q=' + YYYY + '-' + MM);
calendar.set('store', monthStore);
});
});
});
Try changing the interval-change function so that query is set via Calendar object and not directly onto the store.
calendar.on("timeIntervalChange",function(e){
var YYYY = e.startTime.getFullYear();
var MM = e.startTime.getMonth() + 1;
if (MM < 10)
{ MM = '0' + MM};
// this
this.query('?q=' + YYYY + '-' + MM).then(function(results){
console.log(results);
});
});
Have never used the calendar just yet, so its a guess tbh.. But it looks like there's an initial query to be set in the calendar properties, and that this should reflect in the dojo.store.api. The calendar itself most likely does not observe correctly and then in turn does not render when new data arrives.

How do I format this date string so that google scripts recognizes it?

I'm getting a json feed with a date string formatted like the following:
//2012-08-03T23:00:26-05:00
I had thought I could just pass this into a new Date as such
var dt = new Date("2012-08-03T23:00:26-05:00");
This works on jsfiddle but not in google scripts. It's returning an invalid date. After reading this post I recognize it may be how GAS interprets the date string so now I'm not sure how to reformat the date to make it work.
Is there a best way to reformat that date string so GAS can recognize it as a date?
Google Apps Script uses a particular version of JavaScript (ECMA-262 3rd Edition) and as you have discovered can't parse date/times in ISO 8601 format. Below is a modified function I use in a number of my Apps Scripts
var dt = new Date(getDateFromIso("2012-08-03T23:00:26-05:00"));
// http://delete.me.uk/2005/03/iso8601.html
function getDateFromIso(string) {
try{
var aDate = new Date();
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
return aDate.setTime(Number(time));
} catch(e){
return;
}
}
Found this other possible and very simple code that seems to also do the job :
function test(){
Logger.log(isoToDate("2013-06-15T14:25:58Z"));
Logger.log(isoToDate("2012-08-03T23:00:26-05:00"));
Logger.log(isoToDate("2012-08-03T23:00:26+05:00"));
}
function isoToDate(dateStr){// argument = date string iso format
var str = dateStr.replace(/-/,'/').replace(/-/,'/').replace(/T/,' ').replace(/\+/,' \+').replace(/Z/,' +00');
return new Date(str);
}
The hard and sure shot way to make it work if the format is known beforehand is to parse it.
var dtString = "2012-08-03T23:00:26-05:00";
var date = dtString.split('T')[0];
var time = dtString.split('T')[1].split('-')[0];
var tz = dtString.split('T')[1].split('-')[1];
var dt = new Date(date.split('-')[0] , date.split('-')[1] - 1, // month is special
date.split('-')[2], time.split(':')[0],
time.split(':')[1], time.split(':')[2] , 0);
I haven't tested this exact piece of code, but have used similar code. So, this gives you a fair idea of how to proceed.
This worked for me, when converting date-string to date-object in Google Script.
The date-string was taken from the Google Sheet cell by getValues() method.
From: 01.01.2017 22:43:34 to: 2017/01/01 22:43:34 did the job. And then the new Date().
var dateTimeObj = new Date(stringDate.replace(/^(\d{1,2})[-.](\d{1,2})[-.](\d{4})/g,"$3/$2/$1"));
As of now new Date() seems to work:
var dT = new Date("2012-08-03T23:00:26-05:00");
console.info("dT: %s or %d", dT, dT.getTime());
returns dT: Sat Aug 04 06:00:26 GMT+02:00 2012 or 1.344052826E12 in Google Apps Script