How can I use moment.js to exclue Mondays? - momentjs

I have this code to show guests time based on their Timezone and it show also my time, the if time is between 11:00 and 17:00 so we are on line else we are not.
How can I exclude Monday , so when it's Monday it shows an offline message
function updateTime() {
var format = 'HH:mm:ssA'
var divGuest = $('#spt_local_time');
var divLocal = $('#spt_our_time');
var tmz =moment.tz("Africa/Casablanca");
//put UTC time into divUTC
divGuest.text(moment().format('HH:mm:ssA'));
//get text from divUTC and conver to local timezone
var time = moment.tz("Africa/Casablanca").format('HH:mm:ssA');
time = moment(time),format;
divLocal.text(moment.tz("Africa/Casablanca").format('HH:mm:ssA'));
shiftStart = moment.tz('11:00:00', format, "Africa/Casablanca");
shiftEnd = moment.tz('17:00:00', format, "Africa/Casablanca");
var a = moment().day('Monday');
const test = moment();
if (test.isBetween(shiftStart, shiftEnd)) {
$('.sj-support-time .spt-wrap').hasClass('spt-status-on')
$('.sj-support-time .spt-wrap').removeClass('spt-status-off').addClass('spt-status-on');
} else {
$('.sj-support-time .spt-wrap').hasClass('spt-status-off')
$('.sj-support-time .spt-wrap').removeClass('spt-status-on').addClass('spt-status-off');
}
}
setInterval(updateTime, 1000);
updateTime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.js"></script>
I hope this post will be accepted

You can use the methods .day() of moment for get the number of day of week from 0 to 6(Sunday-to-Saturday)
const MONDAY = 1;
if (moment().day() === MONDAY) {
alert('offline'); // Show offline message
} else {
// do something of different
}

moment().format('dddd');
use this to extract the Day and just wrap the whole code into an if condition.
if(moment().format('dddd')==="Monday")
{
// your code
} else{
// offline message
}

Related

How to fix Google Apps Script for local time and automatically clear a cell

I am creating a shared agenda that has to be filled by different people. Everytime they modify a certain cell, the date of change (day) is reported in another cell on the same row. The code below is currently working, but there are 3 minor problems:
The local time is not correct (I am living in italy)
I would like to see the time as well (hours:minutes)
If the modified cell is cleared (like if the text is deleted), also the date of change should disappear.
I find this type of code difficult to debug and would appreciate any help.
Thank you in advance,
function onEdit(event) {
var cell = event.source.getActiveCell();
var sheet = cell.getSheet();
var headers= sheet.getDataRange().getValues()[0];
var statusCol = headers.indexOf('Status') + 1 ;
var ss = event.source.getActiveSheet();
if (event.range.columnStart != 2) {
} else {
ss.getRange(event.range.rowStart, 5)
.setValue(getDate(new Date()));
}
var tt = event.source.getActiveSheet();
if (event.range.columnStart != 34) {
return;
} else {
tt.getRange(event.range.rowStart, 37)
.setValue(getDate(new Date()));
}
}
function getDate(d) {
if (d) {
return d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getYear();
}
}
Add TimeZone, Hours, Minutes and deletes Datetime if cell contents is deleted.
It adds hours and minutes in 24 hour format with a timezone correction and if e.value is null then it deletes the contents of the datetime cell.
function onEdit(e) {
var ss=e.source;
var rg=e.range;
var sh=rg.getSheet();
if(rg.columnStart!=2 && rg.columnStart!=34){return;}
if(rg.columnStart==2){
if(e.value) {
sh.getRange(rg.rowStart, 5).setValue(Utilities.formatDate(new Date(new Date().getFullYear(),new Date().getMonth()+1,new Date().getDate(),new Date().getHours(),new Date().getMinutes()),Session.getScriptTimeZone(),"d/MMM/yyyy HH:mm"));
}else{
sh.getRange(rg.rowStart, 5).setValue('');
}
}
if (rg.columnStart==34) {
if(e.value) {
sh.getRange(rg.rowStart, 37).setValue(Utilities.formatDate(new Date(new Date().getFullYear(),new Date().getMonth()+1,new Date().getDate(),new Date().getHours(),new Date().getMinutes()),Session.getScriptTimeZone(),"d/MMM/yyyy HH:mm"));
}else{
sh.getRange(rg.rowStart, 37).setValue('');
}
}
}
Spreadsheet Edit Event Object
Utilities.formatDate()

Cooking countdown timer with start button

I'm creating an app to help the user cook pasta. The user will select a variety of options and the final step will create a timer based on the options they select. (Example: selecting spaghetti noodles, al dente will result in a 10 minute timer) For the purpose of debugging the code, I have removed my code to calculate the cookTime variable and set it equal to 10 (minutes) to make thins a little easier. Here is my code:
<script>
var cookTime = 10;
$("#timerButton").on("click", function(event){
event.preventDefault();
document.getElementById('timer').innerHTML = Number(cookTime) + ":" + 00;
startTimer();
});
function startTimer() {
var presentTime = Number(cookTime) + ":" + 00;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s===59){
m=m-1;
} //if(m<0){alert('timer completed')}
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0){ // add zero in front of numbers < 10
sec = "0" + sec;
}
if (sec < 0){
sec = "59";
}
return sec;
}
</script>
p {
text-align: center;
font-size: 60px;
margin-top:50px;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="timer"></div>
Start Timer
</body>
</html>
You're setting your minute and second variables inside your function so they're getting the same values every time.
var cookTime = 1;
var presentTime = Number(cookTime) + ":00";
var timeArray = presentTime.split(/[:]+/);
// set your minute and second counters
var min = parseInt(timeArray[0]);
var sec = parseInt(timeArray[1]);
$("#timerButton").on("click", function(event){
event.preventDefault();
// show initial time (using jquery since you're already using it for your click function)
$('#timer').html(presentTime);
startTimer(min, sec);
});
function startTimer(m, s) {
s--;
if (s<0) {
s = 59;
m--;
}
if (m>=0) {
$('#timer').html(m+':'+pad2(s));
// pass the current values for m and s into startTimer
setTimeout(function(){
startTimer(m,s);
}, 1000);
}
else alert('time\'s up');
}
// shorter version of your checkSecond function
function pad2(number) {
return (number < 10 ? '0' : '') + number;
}
Check the fiddle: https://jsfiddle.net/j3txcjmz/

Error Code when script tries to import All Day Event to Calendar

I have been using the same script to import appointments to Calendar for 2 years with no issues. All of a sudden today, I am getting an error code that reads TypeError: Cannot find function createAllDayEvent in object Calendar. (line 35, file "Code")
Why is this happening?? We use this script to schedule company deliveries, so I really need it to work. Any help would be greatly appreciated!!
This is the script I have been using...
function importCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "CALENDAR ID HERE";
var cal = CalendarApp.getCalendarById(calId);
for (i=0; i<data.length; i++) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var startDate = row[3]; // Fourth column
var title = row[1]; // Second column
var location = row[2];
var description = row[4];
var id = row[6]; // Seventh column == eventId
var advancedArgs ={description: description, location: location};
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createAllDayEvent(title, new Date(startDate), advancedArgs).getId(); This is the row with the error.
row[6] = newEvent; // Update the data array with event ID
}
else {
Utilities.sleep(5000);
event.setTitle(title);
event.setDescription(description);
event.setLocation(location);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, new Date(startDate));
}
debugger;
}
// Record all event IDs to spreadsheet
range.setValues(data);
}
You may refer with this thread: Cannot find function createEvent (or createAllDayEvent) in object Calendar. (Google Spreadsheet App). Make sure that yout startDate variable has the right format.
if you are not sure about the 'date' variable being actually a date
you could use
cal.createAllDayEvent(title, new Date(date), {description:desc,location:loc});
that said, it is quite easy to check with the logger
Logger.log(date)
should return a date value in the form Tue Sep 18 03:00:00 PDT 2012
Additional reference: Google script google sheet to calendar TypeError: Cannot find function createEvent in object Calendar. (line 18, file "Code")

ServiceNow: Calling onSubmit in a callback function leads to infinite loop

Here I am comparing 2 variables for dates start_date and end_date and allowing to submit the form only in case end_date is bigger than start_date, else rejecting the form to be submitted, but while running this code, it goes into the infinite loop and if i make this asynchronous by using getXMLWait() instead of getXML(checkDateDiff) it's not supported with mobile api's.
Also there are lot of client script which help in comparing dates but none of them is supported with mobile apis.
Please have a look at the below code and help!!!!
function onSubmit() {
var requestType = g_form.getValue('request_type');
if (requestType == 'mifi') {
console.log("calling validateTravelEndDate()");
validateTravelEndDate();
return false;
} else
return true;
}
//Helper function which calls a AJAX script include called "ClientDateTimeUtils" which gives the response in a callback where i am deciding whether to submit the form or not based on the status of days result.
function validateTravelEndDate() {
var startDate = g_form.getValue('travel_start'); //First Date/Time field
var endDate = g_form.getValue('travel_end'); //Second Date/Time field
var dttype = 'day'; //this can be day, hour, minute, second. By default it will return seconds.
console.log("startDate :" + startDate + "endDate :" + endDate);
var ajax = new GlideAjax('ClientDateTimeUtils'); // This is the script include which can be used for date validation.
ajax.addParam('sysparm_name', 'getDateTimeDiff');
ajax.addParam('sysparm_fdt', startDate);
ajax.addParam('sysparm_sdt', endDate);
ajax.addParam('sysparm_difftype', dttype);
console.log("before " + g_form.getValue('travel_end'));
ajax.getXML(checkDateDiff);
}
// callback function where deciding to go ahead or not with form submission.
function checkDateDiff(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
console.log("difference in days:" + answer);
if (answer <= 0) {
alert("Travel End date must be after Travel Start date.");
g_form.setValue('travel_end', '');
g_form.showFieldMsg('travel_end', 'Please provide a future date', 'error');
return false;
} else {
console.log("%%%%%%%%%%%%%%% Calling g_form.submit()");
g_form.submit(); // This has some issue as it’s going in the infinite loop and if we just return true/false from here as it’s asynchronous call , it’s not handled by the onSubmit function
}
}
Your onSubmit() function always returns false for a mifi request. onSubmit() functions can execute a safer submit when they return a true. Also, g_form functions cannot be run in the callback function, since that is executed on the server.
Rather than have a g_form.submit() at the end of your checkDateDiff function, have onSubmit() function return true.
Something like this should work. I commented every line that I changed:
function onSubmit() {
var requestType = g_form.getValue('request_type');
if (requestType == 'mifi') {
console.log("calling validateTravelEndDate()");
// **CHANGED CODE: instead of g_form.submit(), this will return true
if(validateTravelEndDate()){
return true;
}
else{
return false;
}
} else
return true;
}
//Helper function which calls a AJAX script include called "ClientDateTimeUtils" which gives the response in a callback where i am deciding whether to submit the form or not based on the status of days result.
function validateTravelEndDate() {
var startDate = g_form.getValue('travel_start'); //First Date/Time field
var endDate = g_form.getValue('travel_end'); //Second Date/Time field
var dttype = 'day'; //this can be day, hour, minute, second. By default it will return seconds.
console.log("startDate :" + startDate + "endDate :" + endDate);
var ajax = new GlideAjax('ClientDateTimeUtils'); // This is the script include which can be used for date validation.
ajax.addParam('sysparm_name', 'getDateTimeDiff');
ajax.addParam('sysparm_fdt', startDate);
ajax.addParam('sysparm_sdt', endDate);
ajax.addParam('sysparm_difftype', dttype);
console.log("before " + g_form.getValue('travel_end'));
// **CHANGED CODE: validateTravelEndDate returns the callback value
return ajax.getXML(checkDateDiff);
}
// callback function where deciding to go ahead or not with form submission.
function checkDateDiff(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
console.log("difference in days:" + answer);
if (answer <= 0) {
alert("Travel End date must be after Travel Start date.");
g_form.setValue('travel_end', '');
g_form.showFieldMsg('travel_end', 'Please provide a future date', 'error');
return false;
}
else {
// **CHANGED CODE: checkDateDiff will return true
return true;
}
}

Is there a JQuery plugin to convert UTC datetimes to local user timezone?

If I have a tag:
<span class="utctime">2010-01-01 11:30 PM</span>
I would like a jquery script or plug in to convert every utctime class to the current user's browser local time. I would prefer to find this before writing one.
Ok, so I created one that does it:
/*
Note: this requires that the JQuery-DateFormat plugin (available here) be loaded first
http://plugins.jquery.com/project/jquery-dateFormat
*/
(function ($) {
$.fn.localTimeFromUTC = function (format) {
return this.each(function () {
// get time offset from browser
var currentDate = new Date();
var offset = -(currentDate.getTimezoneOffset() / 60);
// get provided date
var tagText = $(this).html();
var givenDate = new Date(tagText);
// apply offset
var hours = givenDate.getHours();
hours += offset;
givenDate.setHours(hours);
// format the date
var localDateString = $.format.date(givenDate, format);
$(this).html(localDateString);
});
};
})(jQuery);
Usage:
<span class="utcdate">2/5/2010 10:30 PM</span>
$('.utcdate').localTimeFromUTC('MM/dd/yyyy hh:mm a');
Use input date to find time zone offset. Important for DST changes.
(function ($) {
$.fn.localTimeFromUTC = function (format) {
return this.each(function () {
// get provided date
var tagText = $(this).html();
var givenDate = new Date(tagText);
if(givenDate == 'NaN') return;
// get time offset from browser
var offset = -(givenDate.getTimezoneOffset() / 60);
// apply offset
var hours = givenDate.getHours();
hours += offset;
givenDate.setHours(hours);
// format the date
var localDateString = $.format.date(givenDate, format);
$(this).html(localDateString);
});
};
})(jQuery);
Use it like....
function ConvertDatesToLocalTime() {
$('.ConvertUtcToLocal').localTimeFromUTC('MM/dd/yyyy hh:mm:ss a');
}
$(document).ready(function () {
ConvertDatesToLocalTime();
});
Assign 'ConvertUtcToLocal' class to all elements requiring conversion.
$(".localdatetime").each(function () {
var datestr = $(this).text();
//alert(datestr);
if (datestr.trim() != '') {
var dateOb = (new Date(Date.parse(datestr, 'MM-dd-yyyy HH:mm'))).setTimezone("GMT").toString('dd MMM yyyy hh:mm tt');
//alert(dateOb);
$(this).text(dateOb);
}
})
this can also be used along with Date.js library to display time in user timezone
CodeGrue thanks so much for sharing this with the community.
For those who are forced to work with other timezones than UTC .. you can alter the function by adding the time difference like this:
Original snippet:
var offset = -(currentDate.getTimezoneOffset() / 60);
Snippet altered to work with CEST timezone (Time zone offset: UTC + 2 hours):
var offset = -(currentDate.getTimezoneOffset() / 60 + 2);
and so on.
When I used this, I had to change the line
var hours = givenDate.getHours();
to
var hours = givenDate.getUTCHours();
When debugging through this, the line var givenDate = new Date(tagText) ends up creating a Date object that is in UTC (if you give it a date in RFC1123 format, e.g. ddd, dd MMM yyyy HH:mm:ss GMT), but when you call getHours on that you get the hours in the local time zone. So unless you call getUTCHours, it doesn't work.
So the full thing is
/*
Note: this requires that the JQuery-DateFormat plugin be loaded first
http://plugins.jquery.com/project/jquery-dateFormat
*/
(function ($) {
$.fn.localTimeFromUTC = function (format) {
return this.each(function () {
// get time offset from browser
var currentDate = new Date();
var offset = -(currentDate.getTimezoneOffset() / 60);
// get provided date
var tagText = $(this).html();
var givenDate = new Date(tagText);
// apply offset
var hours = givenDate.getUTCHours();
hours += offset;
givenDate.setHours(hours);
// format the date
var localDateString = $.format.date(givenDate, format);
$(this).html(localDateString);
});
};
})(jQuery);
See this other question for how I used it in combination with the timeago plugin.

Resources