Fixing script to input 2021-02-01 instead of 2021-02-32 - datetime

I'm trying to this code in the Script Editor of Google Sheets to insert today's date along with a consistent piece of text, and it was working fine up until Jan 31, 2021, when it started inserting 2021-02-32, 2021-02-33, etc. instead of 2021-02-01, 2021-02-02, etc. Here's the code I'm running:
function daily() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Social Tracker");
var date = Utilities.formatDate(new Date(), "GMT", "YYYY-MM-DD");
var aValues = sh.getRange("A1:A").getValues();
var aLast = aValues.filter(String).length;
// Assuming A and B have same last row, no need for B
// If different, need to calculate separately
var bValues = sh.getRange("B1:B").getValues();
var bLast = bValues.filter(String).length;
// If A and B are the same, use setValues
sh.getRange(aLast + 1, 1, 1, 2).setValues([[date,'handle']]);
var sheet = SpreadsheetApp.getActiveSheet();
var followers = sheet.getRange(2,5,sheet.getLastRow()).getValues();
var nextRowJ = getFirstEmptyRow('J');
var following = sheet.getRange(2,6,sheet.getLastRow()).getValues();
var nextRowK = getFirstEmptyRow('K');
var engagement = sheet.getRange(2,7,sheet.getLastRow()).getValues();
var nextRowL = getFirstEmptyRow('L');
var likes = sheet.getRange(2,8,sheet.getLastRow()).getValues();
var nextRowM = getFirstEmptyRow('M');
var comments = sheet.getRange(2,9,sheet.getLastRow()).getValues();
var nextRowN = getFirstEmptyRow('N');
var posts = sheet.getRange(2,4,sheet.getLastRow()).getValues();
var nextRowO = getFirstEmptyRow('O');
// Record current balance and timestamp at end of columns B & C
sheet.getRange(nextRowO, 15, 1, 1).setValues([[posts]]);
sheet.getRange(nextRowJ, 10, 1, 1).setValues([[followers]]);
sheet.getRange(nextRowK, 11, 1, 1).setValues([[following]]);
sheet.getRange(nextRowL, 12, 1, 1).setValues([[engagement]]);
sheet.getRange(nextRowM, 13, 1, 1).setValues([[likes]]);
sheet.getRange(nextRowN, 14, 1, 1).setValues([[comments]]);
}
// From https://stackoverflow.com/a/9102463/1677912
function getFirstEmptyRow(columnLetter) {
columnLetter = columnLetter || 'A';
var rangeA1 = columnLetter + ':' + columnLetter;
var spr = SpreadsheetApp.getActiveSpreadsheet();
var column = spr.getRange(rangeA1);
var values = column.getValues(); // get all data in one call
var ct = 0;
while ( values[ct][0] != "" ) {
ct++;
}
And here's an image of the cells that are being filled in by the script. I'm assuming my issue is with the line:
sh.getRange(aLast + 1, 1, 1, 2).setValues([[date,'consistent piece of text']]);
How can I adjust this to make sure it follows the next date in A1, ie. inserts 2021-02-01 instead of 2021-02-32?

Use:
var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
Reason:
Utilities.formatDate(date, timeZone, format) follows this format guidelines
When you use "DD", you specify the Day in a year. If you want to specify the Day of the month you need to use dd
In addition, when you use "YYYY" you are referring to a Week year. If you want to get the actual year use "yyyy" instead.

If you find using Java SE Simple Date Format counterintuitive and you are using Google Apps Script V8 runtime instead of using Utilities.formatdate() you might use to Date.prototype.toLocaleDateString
Instead of "YYYY-MM-DD" use "yyyy-MM-dd"
YYYY stands for 4 digit weak year (the first/last week of the year it might return a number different of what you are expecting.
yyyy stands for 4 digit year
DD stands for day year (32 is February 1st)
MM stands for 2 digit month (02 is February)
mm stats for 2 digit minutes

Related

I'm using moment.js diff to compare two times, but the result is incorrect

I'm using moment.js diff to compare two times,but the result is incorrect
var moment = require('moment.js')
console.show()
var mydate = new Date();
myhours = mydate.getHours()
myminutes = mydate.getMinutes()
var a = moment([2007, 0, 29]);
var b = moment([2007, parseInt(myhours), parseInt(myminutes)]);
log(b.diff(a,'minutes'))
I want the result to be correct
You are trying to use the hours and minutes of myDate like month and day in the array to pass at moment constructor.
You can change b with this code:
const b = moment([2007, 0, 29, parseInt(myhours), parseInt(myminutes)]);
or using the methods of moment:
const b = moment().year(2007).startOf('minute');
.year() set the year of date, and .startOf() rounds the time to start of minute.
This can be a solution, if I understood what do you want:
const moment = require('moment.js');
const a = moment([2007, 0, 29]); // 2007-01-29 00:00:00
const b = moment().year(2007).startOf('minute'); // 2007-01-12 14:34:00
console.log(b.diff(a, 'minutes')); // -23606 -> use Math.abs(b.diff(a, 'minutes')) for the absolute value, your choice.

Working with Date, Time in Google Apps Script

I need help with some quick coding with google apps script, linking to my googlesheets spreadsheet.
In the googlespreadsheets, I have a cell with the value “26-Jun-2020”. It is a date.
I want to use google apps script to calculate the number of days difference between that date (“26-Jun-2020”) and today’s day, but it won’t do the calculation for me somehow.
If I print only “expiry_date[i]” using Logger.log(expiry_date[i]), it will provide the output “Fri Dec 17 2021 01:00:00 GMT-0500 (Eastern Standard Time) “
function Put_Options_Expiry_Alert() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Long equity (sell puts)");
//var timeZone = AdsApp.currentAccount().getTimeZone(); //Get timezone of current spreadsheet
var status = sheet.getRange("F:F").getValues();
var expiry_date = sheet.getRange("M:M").getValues();
var potential_capitaloutlay_USD = sheet.getRange("Z:Z").getValues();
Logger.log("Length of status = " + status.length);
Logger.log("Length of expiry_date = " + expiry_date.length);
Logger.log("Length of potential_capitaloutlay_USD = " + potential_capitaloutlay_USD.length);
for (var i = 0; i < status.length; i++) {
if (status[i] == "Entered") { //Evaluate if this is a live Put position
//Calculate the time difference of two dates using date2. getTime() – date1. getTime();
//Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
Logger.log("expiry date is = "+expiry_date[i]);
Logger.log("today's date is = "+Date());
var days_to_expiry = dateDiffInDays(expiry_date[i],Date());
Logger.log(days_to_expiry);
}
}
}
// Function that returns the number of days difference between DateA and DateB
// DateA and DateB are javascript Date objects
function dateDiffInDays(DateA, DateB) {
var milliseconds_per_day = 1000 * 24 * 60; // number of milliseconds in a day
const utcA = Date.UTC(2021, DateA.getMonth(), DateA.getDate());
const utcB = Date.UTC(2020, DateB.getMonth(), DateB.getDate());
return Math.floor((utc2 - utc1) / milliseconds_per_day);
}
function timeDiffDays(Start, End) {
var day = 86400000;
var t1 = new Date(Start).valueOf();
var t2 = new Date(End).valueOf();
var d = t2 - t1;
return Math.floor(d / day);
}

How to find difference between two times in 24 hour format - Flutter?

I have to find the difference between two times in 24 hour format. I have the two time strings, Eg: 10:40 and 18:20. How can I find the difference between these two times in Flutter?
You can use intl package.
var format = DateFormat("HH:mm");
var one = format.parse("10:40");
var two = format.parse("18:20");
print("${two.difference(one)}"); // prints 7:40
A complete answer for perfect calculation is given bellow
String start_time = formateTime('12:00'); // or if '24:00'
String end_time = formateTime('24:00'); // or if '12:00
var format = DateFormat("HH:mm");
var start = format.parse(start_time);
var end = format.parse(end_time);
if (start.isAfter(end)) {
print('start is big');
print('difference = ${start.difference(end)}');
} else if(start.isBefore(end)){
print('end is big');
print('difference = ${end.difference(start)}');
}else{
print('difference = ${end.difference(start)}');
}

Javascript Moment.js add a day to a date in milliseconds

I am trying to add a day to a date in milliseconds.
The code I am using is bellow.
var x = 1450612800000;
var timeFrame = 'days'
x = moment(x).add(timeFrame, 1);
console.log(x['_i']) //returns 1450612800000
Here is the fix:
var x = 1450612800000;
var timeFrame = 'd'
var newDay = moment(x).add(tf, 1);
console.log('newDay');
//Get New Date in Milliseconds format
console.log(newDay.valueOf());
//Get New Date in Date Format
console.log(newDay.toDate());
Take a look at this StackOverflow answer: https://stackoverflow.com/a/28132227/3692354
_i isn't what you want to use here - that's the input that was used to create the moment object. I think what you want to use instead is moment's valueOf function: http://momentjs.com/docs/#/displaying/unix-offset/

How to refresh displayed date in CalendarExtender?

I've this code that changes the maximum date of a second Calendar Extender to 90 days after the date that has been defined in a first one and minimum to the same it has been selected on the first and it works right except for one thing.
var cal2 = $find("calendar2");
var fecha = cal._selectedDate;
var date = fecha.getDate() + 90;
var year = fecha.getFullYear();
var month = fecha.getMonth();
var todayDate = new Date(year, month, date);
cal2._startDate = cal._selectedDate;
cal2._selectedDate = fecha;
cal2._switchMonth(fecha);
cal2._endDate = todayDate;
Problem is that if I first seelct a date on cal, dates are properly shown in cal2, but I select one on cal again then cal2 doesn't display in the same month that cal, what's much worse it displays to select days that would be now impossible to select and in fact you can select them unless you go back first to month mode.
Any idea on how to "refresh" the behavior of the second CalendarExtender?
Thank you.
you can use this method.
Sys.Extended.UI.CalendarBehavior.prototype.refresh = function () {
this._isOpen = true;
this._ensureCalendar();
this.invalidate();
this._isOpen = false;
}
When you add the method only call:
cal2.refresh()

Resources