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

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.

Related

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);
}

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

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

How to get max date from any date field in moment js

How to extract max date from date field by using any function in moment js?
I guess this can help
var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');
moment.min(a, b); // where a, b are moment objects
output: a
moment.max(a, b);
output: b

Moment.js show diff between 2 dates

I use moment(d, "YYYYMMDD").fromNow(); to get diff between date now and some date, but I would like to get without string "a few days ago".
Instead, I would like to get "7d" (7m, 1s, etc).
How can I do this?
If you want just to get the difference between two dates instead of a relative string just use the diff function.
var date = moment("20170101", "YYYYMMDD");
var date7 = moment("20170108", "YYYYMMDD");
var mins7 = moment("20170101 00:07", "YYYYMMDD HH:mm");
var secs1 = moment("20170101 00:00:01", "YYYYMMDD HH:mm:ss");
console.log(date7.diff(date, "days") + "d"); // "7d"
console.log(mins7.diff(date, "minutes") + "m"); // "7m"
console.log(secs1.diff(date, "seconds") + "s"); // "1s"
Moment.diff does exactly that.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
You can specify a unit:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
var before = moment('2017.02.12 09:00','YYYY.MM.DD HH:mm');
var now = moment();
console.log(
moment(now - before)
.format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

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/

Resources