I write some code for getting current date and compare it with a future date for application limitation. I don't know why this function doesn't work.
getYYMMDD();
function getYYMMDD(): String {
var dateObj: Date = new Date();
var year: String = String(dateObj.getFullYear());
var month: String = String(dateObj.getMonth() + 1);
if (month.length == 1) {
month = "0" + month;
}
var date: String = String(dateObj.getDate());
if (date.length == 1) {
date = "0" + date;
}
return year.substring(0, 4) + month + date;
trace(year + ":" + month + ":" + date);
if (int(year) > 2017 && int(month) > 5 && int(date) > 31) {
trace("SYSTEM TIME IS OFF.");
} else {
trace("SYSTEM TIME IS ON.");
}
}
(1) Since your function returns data of String type...
function getYYMMDD(): String
Make sure that returned data is also being received by a String... ie: someString = getYYMMDD(); means someString now has returned value from function.
(2) You return (exit the function) too soon...
Put return as last command to allow all other code inside your function to run.
(3) You should consider returning a Boolean type (true/false)...
var can_Start : Boolean = false; //# assume false before checking
can_Start = getYYMMDD(); //# use function to update status to true/false
if (can_Start == true) { run_Program(); }
else { trace("Sorry time has expired"); }
function getYYMMDD(): Boolean
{
var dateObj: Date = new Date();
var year: String = String(dateObj.getFullYear());
var month: String = String(dateObj.getMonth() + 1);
if (month.length == 1) { month = "0" + month; }
var date: String = String(dateObj.getDate());
if (date.length == 1) { date = "0" + date; }
trace(year + ":" + month + ":" + date);
if(int(year) == 2017)
{
if(int(month) >= 05 && int(date) > 31)
{ trace("SYSTEM TIME IS OFF."); can_Start = false; } //# can_Start == false;
else { trace("SYSTEM TIME IS ON."); can_Start = true; } //# can_Start == true;
}
return can_Start;
}
Related
I'm trying to write a google script that will updates the sensor data google sheet.This part is ok.
And I try to add a function clearRange(), when the data updated to 100 rows and delete the first 100 rows and reupdate the data. Is there something that I'm missing here?
function doGet(e) {
Logger.log( JSON.stringify(e) );
var sheet_id = 'XXXXXXXXXXXXXXXXXXXXX'; // Spreadsheet ID
var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else if(e.parameter != 'undefined'){
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "GMT+8", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
break;
case 'humidity':
rowData[3] = value; // Humidity in column D
result += ' ,Humidity Written on column D';
break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
else if (newRow==100)
{
clearRange();
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
function clearRange() {
sheet.deleteRows(1,100);
}
Try this:
function doGet(e) {
var sheet_id = 'XXXXXXXXXXXXXXXXXXXXX'; // Spreadsheet ID
var sh = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sh.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else if (e.parameter != 'undefined') {
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "GMT+8", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
var value = e.parameter[param].replace(/['"]+/g, '');
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
break;
case 'humidity':
rowData[3] = value; // Humidity in column D
result += ' ,Humidity Written on column D';
break;
default:
result = "unsupported parameter";
}
}
var newRange = sh.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
else if (newRow == 100) {
sh.deleteRows(1, 100);
}
return ContentService.createTextOutput(result);
}
I'm building a webapp in which are inputboxes with a date. How can I bind the data to my background code?
I tried just doing it directly but i guess an inputbox can only handle strings so a made a convert to string method and so on.
<div>
<label>start date: </label>
<input [(ngModel)]="item.stringStartDate" placeholder="start date" type="date">
</div>
void set startDate(DateTime startDate)
{
_startDate = startDate;
}
void set stringStartDate(String startDate)
{
this.startDate = parseDate(startDate);
}
static DateTime parseDate(String formattedString)
{
final RegExp r = new RegExp(
r'^(\d\d)-?(\d\d)-?([+-]?\d{4,6})');
Match match = r.firstMatch(formattedString);
if (match != null)
{
int years = int.parse(match[3]);
int month = int.parse(match[2]);
int day = int.parse(match[1]);
return new DateTime(years, month, day);
}
else
{
throw new FormatException("Invalid date format", formattedString);
}
}
static String dateToString(DateTime date){
if (date == null)
return null;
String ret = "${date.year}/";
if (date.month < 10)
ret+="0";
ret+="${date.month}/";
if (date.day < 10)
ret += "0";
ret+="${date.day}";
return ret;
}
it should be separated by - instead of /
you can use toIso8601String and substring
DateTime _date = new DateTime.now();
String get date => _date.toIso8601String().substring(0, 10);
void set date(value) {
if (value is DateTime) {
_date = value;
} else if (value is String) {
_date = DateTime.parse(value);
}
}
I have successfully accessed a Google calendar event and can change the color, but I'm stuck when it comes to removing the hangouts link.
I'm attempting to use code to automatically remove the hangouts links when I am the meeting originator and have not changed the hangout name, but I'm not having any success in actually changing the link.
Any help greatly appreciated.
function removehangout() {
var calendarId = 'primary';
//var calendars = CalendarApp.getOwnedCalendarsByName('Mirage ELDRIDGE');
var now = new Date();
// Determines how many events are happening in the next 24 hours x 1 days.
var now = new Date();
var endr = new Date(now.getTime() + (1 * 24 * 60 * 60 * 1000));
var events2 = CalendarApp.getDefaultCalendar().getEvents(now, endr);
Logger.log('Number of events: ' + events2.length);
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 5
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event1 = events.items[i];
var d = event1.description;
var ttitle = event1.summary;
var whoby = event1.creator.email;
Logger.log(ttitle + ' by: ' + whoby);
if(whoby.indexOf('mirage.eldridge') != -1){
Logger.log(ttitle + '--> was by mirage');
var hangoutname = event1.hangoutLink;
Logger.log(ttitle + '--> hangout link name --> ' + hangoutname);
if (hangoutname != null) {
if (hangoutname.indexOf('mirage-eldridge') != -1){
//delete this link here
Logger.log(ttitle + '--> remove hangout');
//event.setHangoutLink(null);
//var idno = event.iCalUID
//CalendarApp.getEventSeriesById(idno)
event1.HangoutLink = null;
Logger.log(ttitle + '... ' + event1.hangoutLink);
Logger.log(event1.iCalUID);
//event.setcolorId('11');
var event2 = Calendar.Events.get(calendarId, event1.id)
event2.colorId = 9;
event2.hangoutLink = 'fred';
//Calendar.Events.patch(event2,calendarId,event1.id);
Calendar.Events.update(event2,calendarId,event1.id);
}
} else {
Logger.log(ttitle + ' -- do not remove ' + hangoutname);
}
}
if (!d)
d = '';
//var foundlinkyes = d.indexOf('HangoutLink');
//var actuallink = event.hangoutLink;
//var hasrlink = 'True';
//if (!actuallink) {
//Logger.log(ttitle + ' no link found');
//hasrlink = "False";
//}
//Logger.log('desc: ' + ttitle + '-- foundyes: ' + foundlinkyes);
//if (foundlinkyes == -1 && hasrlink == 'True'){
//if (event.hangoutLink && (d.indexOf('Hangout: ')== -1)){
//Logger.log (event.summary + ' - ' + event.hangoutLink + ' - ' + event.description);
//Logger.log(ttitle + ' added this ' + event.hangoutLink);
//event.description = 'HangoutLink: ' + event.hangoutLink + '\n\n' + d;
//Calendar.Events.update(event, calendarId, event.id);
//foundlinkyes = 0;
//hasrlink = 'True';
//}
//}
}
} else {
Logger.log('No events found.');
}
}
Could anyone please help with generating number of working days between two dates in Google Apps Script.
Thank you.
Based on the answer given here: How do I calculate number of given weekday between range using Moment JS?
It works similar in AppsScript
function workdays_between(start_date_string, end_date_string) {
var startDate = new Date(start_date_string)
var endDate = new Date(end_date_string)
// Validate input
if (endDate <= startDate) { return 0; }
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) { days -= 2; }
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) { days--; }
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) { days--; }
return days
}
function test_it() {
let start_date_string = "March 12, 2021"
let end_date_string = "October 15, 2021"
console.log(workdays_between(start_date_string, end_date_string) + " workdays between " + start_date_string + " and " + end_date_string)
}
From user KBA (https://stackoverflow.com/users/453331/kba) from response How do I calculate number of given weekday between range using Moment JS?:
var firstDate = new Date("March 1, 2015");
var secondDate = new Date("March 25, 2015");
function getWeekdaysBetweenDates(firstDate, secondDate, dayOfWeek) {
var MILISECONDS_IN_DAY = 86400000;
function getNextDayOfWeek(date, dayOfWeek) {
date.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
return date;
}
firstDate = getNextDayOfWeek(firstDate, dayOfWeek);
if (firstDate > secondDate) {
return 0;
}
return 1 + Math.floor(((secondDate - firstDate) / MILISECONDS_IN_DAY) / 7);
}
Is there anyway that I can make a default value of HTML5 input type='datetime-local' to today's date and this current time.
Thanks before
You can make it shorter:
<input type="datetime-local" id="cal">
window.addEventListener('load', () => {
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
/* remove second/millisecond if needed - credit ref. https://stackoverflow.com/questions/24468518/html5-input-datetime-local-default-value-of-today-and-current-time#comment112871765_60884408 */
now.setMilliseconds(null)
now.setSeconds(null)
document.getElementById('cal').value = now.toISOString().slice(0, -1);
});
It's possible. By using a JQuery function, you can have a really complete solution.
Here is an example.
JSFiddle http://jsfiddle.net/v8MNx/1/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Date:</label>
<input type="datetime" name="anniversaire" id="anniversaire"/>
</p>
<input type="submit" value="Submit"/>
</form>
JQuery:
//Function found here: https://gist.github.com/ryanburnette/8803238
$.fn.setNow = function (onlyBlank) {
var now = new Date($.now())
, year
, month
, date
, hours
, minutes
, seconds
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
if ( onlyBlank === true && $(this).val() ) {
return this;
}
$(this).val(formattedDateTime);
return this;
}
$(function () {
// Handler for .ready() called.
$('input[type="datetime"]').setNow();
});
The accepted answer seems pretty complicated to me... here a shorter solution that doesn't need jQuery
JSFiddle: https://jsfiddle.net/rzaceg8v/
window.addEventListener("load", function() {
var now = new Date();
var utcString = now.toISOString().substring(0,19);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var localDatetime = year + "-" +
(month < 10 ? "0" + month.toString() : month) + "-" +
(day < 10 ? "0" + day.toString() : day) + "T" +
(hour < 10 ? "0" + hour.toString() : hour) + ":" +
(minute < 10 ? "0" + minute.toString() : minute) +
utcString.substring(16,19);
var datetimeField = document.getElementById("myDatetimeField");
datetimeField.value = localDatetime;
});
<input type="datetime-local" id="myDatetimeField"/>
The methods above worked but were too verbose for me.
Here's my version:
window.addEventListener("load", function() {
var now = new Date();
var offset = now.getTimezoneOffset() * 60000;
var adjustedDate = new Date(now.getTime() - offset);
var formattedDate = adjustedDate.toISOString().substring(0,16); // For minute precision
var datetimeField = document.getElementById("myDatetimeField");
datetimeField.value = formattedDate;
});
This worked perfectly!
One note, I tried this the only month it would break, October. It would give me a '010', instead of 10.
month = (now.getMonth() +1 ).toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
Big line works for me, if it doesn't for you you can introduce whitespaces and line breaks in the expressions.
function setDatetimeInput(element, t = new Date()){
function p(number){return number.toString().padStart(2, '0');}//number to 2 digit, 0 padded string
element.value = `${t.getFullYear()}-${p(t.getMonth()+1)}-${p(t.getDate())}T${p(t.getHours())}:${p(t.getMinutes())}`;
}
here's a simple way:
<input type="datetime-local" id="cal">
const currentDateTime = () => {
var tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
var localISOString = new Date(Date.now() - tzoffset)
.toISOString()
.slice(0, -1);
// convert to YYYY-MM-DDTHH:MM
const datetimeInputString = localISOString.substring(
0,
((localISOString.indexOf("T") | 0) + 6) | 0
);
console.log(datetimeInputString);
return datetimeInputString;
};
document.getElementById('cal').value = currentDateTime();