Compare Google sheet dates to Google Calendar Event date - javascript

Matching dates from Sheet and Google Calendar is always false, how can I format the two dates to compare?
I've attemped to format the dates even if they look exactly the same it comes back false.
var Sheet_StartDate = Spreadsheet.getActiveSheet().getRange(1,1).getValue();
var calendar = CalendarApp.getCalendarById('####');
var event = calendar.getEventById(eventId);
var calendar_StartTime;
try {
// Get all day event
calendar_StartTime = event.getAllDayStartDate();
}
catch (e) {
//Multi-day event
calendar_StartTime = event.getStartTime();
}
if (calendar_StartTime === Sheet_StartDate )
{
//This comes back false
}

Try this:
function compareDates() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var dt=new Date(sh.getRange(1,1).getValue());
var Sheet_StartDate_value=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//This removes the time portion
var calendar = CalendarApp.getCalendarById('####');
var event = calendar.getEventById(eventId);
dt=new Date(event.getAllDayStartDate());
var calendar_StartTime_value=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
if(calendar_StartTime_value == Sheet_StartDate_value ) {
//This will come back true if in fact they are the same date
}
}
You can also use Date().getTime()

Related

How do i set timestamp to specific cells everytime i open my google sheet?

How do I set a timestamp to multiple specific cells every time I open my document using script?
Lets say I want to set the current date and time on every cell from A2 to A25 how do I achieve this?
Thanks in advance.
Try this:
function initTimeStamps() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheets()[0];
var rg=sh.getRange(2,1,24,1);//This is the range that receives timestamps
var vA=rg.getValues();//This gives me access to the values
var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
for(var i=0;i<vA.length;i++) {
vA[i][0]=ts;
}
rg.setValues(vA);//This is where the values are written back into the spreadsheet
}
function setupOnOpenTrigger() {//Run this once to setup the trigger
var ss=SpreadsheetApp.getActive();
if(!isTrigger('initTimeStamps')) {
ScriptApp.newTrigger('initTimeStamps').forSpreadsheet(ss.getId()).onOpen().create();
}
}
function isTrigger(funcName){
var r=false;
if(funcName){
var allTriggers=ScriptApp.getProjectTriggers();
for(var i=0;i<allTriggers.length;i++){
if(funcName==allTriggers[i].getHandlerFunction()){
r=true;
break;
}
}
}
return r;
}
class Sheet Read this to learn how to setup ranges.
You can also setup triggers from the edit/current project triggers menu.

Fullcalendar - Need event to not be more than a day - using selectAllow but issue with allDay

I'm using Fullcalendar and need events to not be more than a day.
I've got it working for when you pick an hour range but it never works for allDay events, as the from and to dates are different. Here is my selectAllow function. I'm aware it's not elegant, my Javascript is limited!
function(selectInfo) {
var ambig = selectInfo.start._ambigTime;
var from_date = selectInfo.start._d;
from_date = String(from_date).substr(0, 10);
var to_date = selectInfo.end._d;
to_date = String(to_date).substr(0, 10);
if (from_date != to_date)
{
return false;
}
else
{
return true;
}
var duration = moment.duration(selectInfo.end.diff(selectInfo.start));
console.log(duration.asHours());
}
As you can see from the code, I've gone down the route of having different checks based on ambigTime (I assume this is whether it's allDay or not?) and using the duration but the duration doesn't work when it's all day.
Any help much appreciated.
Actually you can solve this much more neatly and simply by using selectConstraint. This limits the user's selection to a certain window of time. By specifying it as per the following example, it effectively limits an individual selection to the day where the selection began:
selectConstraint: {
start: '00:00',
end: '24:00',
},
Demo: http://jsfiddle.net/9qv5xz18/
Thanks to ADyson, I've fixed it. I think I can neaten up the code but the below now works.
function(selectInfo) {
console.log(selectInfo);
var ambig = selectInfo.start._ambigTime;
var from_date = selectInfo.start._d;
var from_dat = selectInfo.start;
var to_dat = selectInfo.end;
console.log(to_dat.diff(from_dat))
from_date = String(from_date).substr(0, 10);
var to_date = selectInfo.end._d;
to_date = String(to_date).substr(0, 10);
if (!ambig)
{
if (from_date != to_date) {
return false;
} else {
return true;
}
}
else
{
return to_dat.diff(from_dat) == 86400000;
}
var duration = moment.duration(selectInfo.end.diff(selectInfo.start));
console.log(duration.asHours());
}

Convert HH:MM:SS string to moment

I am using full calendar and I am trying to see if an event created is overlapping with the lunch breaks which I have defined as part of business hours. This is my code
function isCalendarEventOverlappingBusinessHour(event)
{
var evts = businessHoursArr;
for (i in evts)
{
var start_moment=moment(evts[i].start, 'MMM DD').format();
var end_moment=moment(evts[i].end);
if (event.start.isBefore(end_moment) && event.end.isAfter(start_moment))
{
return true;
}
}
return false;
}
I am not able to compare the event start and business hour start since in business hours, the time is defined in string format as 08:00:00. I want to convert it into a moment so that I can compare the times. Can anyone suggest a method?
My event is in the following format:
events.push({
id: guid(),
title: eventTitle,
start: moment(date),
end: moment(date).add(defaultTimedEventDuration,'hours'),
stick: true,
});
And my businesshoursarr looks like
{
dow:[1,2,3,4,5]
start:08:00:00
end:12:00:00
},
{
dow:[1,2,3,4,5]
start:13:00:00
end:17:00:00
}
I'd suggest moment(value, 'HH:mm:ss').valueOf() which will return an integer and you could just compare numbers at that point.
It'd also help if you provided an example of what businessHoursArr and event look like.
Update: Taking your code and making a few modifications, this should give you the general idea.
function isCalendarEventOverlappingBusinessHour(event) {
var evts = businessHoursArr;
var overlapping = false;
var dayFormat = 'YYYYMMDD';
var secFormat = dayFormat + 'HH:mm:ss';
var eventStartDate = event.start.format(dayFormat);
var eventEndDate = event.end.format(dayFormat);
for (i in evts) {
var start_moment = moment(eventStartDate + evts[i].start, secFormat);
var end_moment = moment(eventEndDate + evts[i].end, secFormat);
if (event.start.isBefore(end_moment) && event.end.isAfter(start_moment)) {
overlapping = true;
break;
}
}
return overlapping;
}

Get a combined Date from ui.bootstrap date and time pickers

I'm trying to combine the Datepicker and Timepicker directives to get the date from the first and the time from the second in a combined Date object. I came across some examples that are not using these directives like this one Combining Date and Time input strings as a Date object. However when I try to apply something similar to my case it's not working. Console returns "TypeError: $scope.dt.split is not a function". Above is the function I try to use which is called by $watch.
function tryCombineDateTime() {
if ($scope.dt && $scope.mytime) {
var dateParts = $scope.dt.split('-');
var timeParts = $scope.mytime.split(':');
if (dateParts && timeParts) {
dateParts[1] -= 1;
$scope.fullDate = new Date(Date.UTC.apply(undefined, dateParts.concat(timeParts))).toISOString();
}
}
}
Here is a plunker showing the problem. http://plnkr.co/edit/tnbE3LWQTTzLhLWXLCQB?p=preview
I would prefer a solution based on my Plunker as I don't want to install other components like DateTimePicker.
Date format has been changed, so exception is being thrown, Try this
function tryCombineDateTime() {
if ($scope.dt && $scope.mytime) {
var date = $scope.dt.toString();
var time = $scope.mytime.toString();
var dateParts = date.split(' ');
var timeParts = time.split(' ');
if (dateParts && timeParts) {
dateParts[4] = timeParts[4]
$scope.fullDate = new Date(dateParts.join(' ')).toISOString();
}
}
}
your tryCombineDateTime function sould be like this:
function tryCombineDateTime() {
if ($scope.dt && $scope.mytime) {
$scope.fullDate =new Date($scope.dt.getFullYear(), $scope.dt.getMonth(), $scope.dt.getDate(),$scope.mytime.getHours(),$scope.mytime.getMinutes()).toISOString();
}
}
this a working demo forked from your plunker

Preferred Method to (Accurately) Get Time From User Input (in UiApp - GAS)

UiApp has DateBox and DateTimeFormat
for that Class. However, there is no such thing as TimePicker or TimeBox, where a user could enter a time in a well-specified manner such as through using Google Forms:
Forms has different behavior for this Widget in Chrome vs Firefox (I much prefer the Chrome behavior). Anyway, currently I am using a TextBox to get time values, where someone would enter a time value in the following manner:
12:00 or 13:50, etc. These times would be in the 24-hour clock so that I could create new Date objects based on someDate + " " + startTime, which would act as the real start time for an event on the Calendar (this is the process I currently use in several of my applications at work). This is obviously unreliable for several reasons.
Ex: If the user entered anything except a valid 24-hour representation in HH:MM:SS, Date creation would fail.
I don't want to force my boss to be overly-precautious about how he inputs times into the UI, and I also want to avoid regexing "valid" formats and having the UI do a lot of back-end work (it would be 18 regex tests total, and if any failed I'd have to handle them individually).
So, the question: is there an efficient/preferred method of getting times in UiApp, either via TextBox or some other interface?
What about something like that ? Test app here (updated with new version, see edit)
code below :
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'15px'});
var handler = app.createServerHandler('setTime').addCallbackElement(frame);
var h = app.createListBox().setId('h').setName('h').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m').setName('m').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am').setName('am').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setName('date').addValueChangeHandler(handler);
var label = app.createHTML('<b>StartTime *</b><br>When your reservation starts').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'10px'});
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'5px'});
var result = app.createHTML().setId('date').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'color':'#AA6','padding-top':'20px'})
.setHTML(Utilities.formatDate(new Date(new Date().setHours(0,0,0,0)), Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
frame.add(date).add(label).add(subFrame).add(result);
subFrame.add(h).add(m).add(am);
return app.add(frame);
}
function setTime(e){
var app = UiApp.getActiveApplication();
var date = app.getElementById('date')
var date = new Date(e.parameter.date);
var am = e.parameter.am
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter.h)+am;
var m = Number(e.parameter.m);
date.setHours(h,m,0,0)
Logger.log(date);
app.getElementById('date').setHTML(Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
return app
}
EDIT : here is the wrapped version and a demo with a grid and 10 panels.
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var grid = app.createGrid(10,2)
var handler = app.createServerHandler('setTime').addCallbackElement(grid);
var varName = 'date';
var htmlString = '<b>StartTime *</b> When your reservation starts'
for(var idx=0 ; idx<10;idx++){
var frame = pickDate(idx,varName,htmlString,handler);
grid.setText(idx, 0, 'test widget '+idx+' in a grid').setWidget(idx,1,frame);
}
var result = app.createHTML('<h1>Click any widget</h1>').setId('result');
return app.add(grid).add(result);
}
/* wrapped version
** takes a var name + index + label string + handler
** as input parameter
** The same handler will be used for every occurrence , the source being identified in the handler function (see code example below)
** and returns a selfcontained widget that you can add to a panel or assign to a grid
** or a flex Table
*/
function pickDate(idx,varName,htmlString,handler){
var app = UiApp.getActiveApplication();
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'1px', 'border-radius':'5px'});
var h = app.createListBox().setId('h'+idx).setName('h'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m'+idx).setName('m'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am'+idx).setName('am'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setId(varName+idx).setName(varName+idx).addValueChangeHandler(handler);
var label = app.createHTML(htmlString).setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'3px'}).setId('html'+idx);
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFE','padding':'1px', 'border-radius':'4px'});
frame.add(label).add(date).add(subFrame);
subFrame.add(h).add(m).add(am);
return frame;
}
function setTime(e){
// Logger.log(JSON.stringify(e));
var app = UiApp.getActiveApplication();
var idx = Number(e.parameter.source.replace(/\D+/,''));
Logger.log('date'+idx+ ' > '+e.parameter['date'+idx]);
var date = new Date(e.parameter['date'+idx]);
var am = e.parameter['am'+idx];
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter['h'+idx])+am;
var m = Number(e.parameter['m'+idx]);
date.setHours(h,m,0,0)
app.getElementById('result').setHTML('<h1>Widget Nr '+idx+' has value '+Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm')+'</h1>');
return app
}

Categories