Moment time difference in hours is not correct - javascript

I am trying to find time difference in hours between two time but somehow its not correct. I might be doing something wrong but can't figure out where. The time difference I want is from a certain date with any time to some end date at 00:00:00
The following is how I find the difference:
async function getSubscriptionValidity(org_id) {
// Get expiry date of the organisation
let validity = await Customers.findOne({ orgId: org_id }, "expiresOn -_id");
let now = moment();
let expiryDate = moment(validity.expiresOn).startOf("day");
// Calculate time remaining to expiry in hours
let difference = expiryDate.diff(now, "hours");
console.log(now);
console.log(expiryDate);
console.log(difference);
}
Result
moment("2019-04-09T21:30:43.579") // Start Date and time
moment("2019-04-10T00:00:00.000") // End date and time
2 // Shouldn't this be 3 ?

By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument.
https://momentjs.com/docs/#/displaying/difference/

Related

Moment js not adding hours and minutes to a specific time

I have a start time to which i would like to add an end time to.
for example
startTime=19:09
endTime=00:51 // 0 hours and 51 minutes
i want to add the 51 minutes to the 19:09 to make it 20:00.
I have tried multiple different scenarios as showing bellow but nothing is giving me the correct time
i tried
let [hour, minute] = endTime.split(':').map(Number);
this.endTime = Moment(startTime)).add({ hour: 'hours', minute: 'minutes' }) // also tried .add(hour,'hours').add(minute,'minutes')
which still outputs 19:09. its just ignoring my end time
i tried
Moment(endTime, 'hh:mm').add(Moment.duration(startTime)).format("hh:mm");
which gives me an output of 08:00 when it should be 20:00
What am i doing wrong?
i want to add the end time to a start time.
Keep in mind that my endTime is always changing so sometimes it could be 13:05 etc cause its a user input
There are three major issues with your code:
Creating a moment with a timestamp alone (ie something like moment('19:09') without a date) like you do is deprecated and throws an error. You either have to pass in a fully specified timestamp in RFC2822 or ISO format or explicitely tell the library, what input format you are using.
The object you are passing to the add() function literally is
{
hour: "hours",
minute: "minutes"
}
ie, instead of passing the numerical values for hours and minutes to add to your
moment, you are passing the strings "hours" and "minutes", which obviously
momentsjs can't handle.
The format hh:mm only accepts hours from 0 to 12. If you want a 24-hour clock you have to use HH:mm
Taking these issues into account, the following snippet works as expected:
let start = '2021-01-07 19:09',
duration = '0:51',
starttime = '19:09';
let [hour, minute] = duration.split(":");
//shorthand initialization for the argument
let endtime1 = moment(start).add({hour, minute}).toString();
//explicit definition of property names
let endtime2 = moment(start).add({hours: hour, minutes: minute}).toString();
//add hours and minutes separately
let endtime3 = moment(start).add(hour, "hours").add(minute, "minutes").toString();
//provide a format for the timestamp. momentsjs will take the current date for the date value
let endtime4 = moment(starttime, "HH:mm").add(hour, "hours").add(minute, "minutes").toString();
console.log(endtime1);
console.log(endtime2);
console.log(endtime3);
console.log(endtime4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Also keep in mind, that for specifiying which part of the timestamp to manipulate, you can either use singular or plural wording. Ie
moment(...).add(4, "hour").add(17, "minute") and moment(...).add({hour: 4, minute: 17})
is equivalent to
moment(...).add(4, "hours").add(17, "minutes") and moment(...).add({hours: 4, minutes: 17})
respectively as can also be seen in the snippet with the creation of endtime1 and endtime2
You need to convert your duration into a single unit as minutes, seconds, days etc...
Then you can use the following snippet to add duration.
you can uses moment methods to convert your duration
const mins = moment.duration(10, "hour").asMinutes();
const someTime = moment('19:09',"HH:mm");
const data = someTime.add('51','minutes').format("HH:mm")
//More clever solution would be
const data2 = someTime.add(1, "hours").add(51, "minutes").format("HH:mm")
console.log(data)
console.log(data2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Calculating Time Difference in Javascript

I am trying to find time differences. Difference is NaN. What should I do?
currentTime.format() = 2016-12-07T11:43:19+03:00
pws.lastDataTime = 2016-12-07T08:35:14.4126931+00:00
var difference= currentTime.format() - pws.lastDataTime;
currentTime.format() = 2016-12-07T11:43:19+03:00
currentTime.format is a function. You can't assign it's return value to something.
currentTime.format() - pws.lastDataTime
I don't think the format function returns a number, but instead a string or an object. If you subtract anything from them, they return NaN (not a number). You need to either convert both to milliseconds and subtract one from the other, or calculate the year, month, day, hour, second and millisecond separately.
I don't know what denomination you want, so I'll just show you how to find it in milliseconds.
If already you have a date or two, you can use date.getTime().
var stackOverflowLaunchDate = new Date(2008, 8, 15);
var today = new Date();
var diff = today.getTime() - stackOverflowLaunchDate.getTime(); // milliseconds since Stack Overflow was launched
If you don't have (and don't need) a date object, use Date.now() to get millisecondds since epoch
var start = Date.now();
// ... Some time later
var diff = Date.now() - start; // milliseconds since start

Minutes since midnight in Momentjs

In pure JS, this would be how.
How can I find out the number of minutes since midnight for a given moment object (without extracting to Date)?
Must take into account DSTs
Minutes should be rounded
Must work with local time (not convert to UTC)
// Your moment
var mmt = moment();
// Your moment at midnight
var mmtMidnight = mmt.clone().startOf('day');
// Difference in minutes
var diffMinutes = mmt.diff(mmtMidnight, 'minutes');
By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.
Consider this pseudocode because I haven't test to see if the difference takes into account DST.
This is what I have at the moment:
if (!moment.isMoment(mmt)) {
return 0;
}
var hh = mmt.get('hour');
var mm = mmt.get('minute');
return hh*60 + mm;
I am not sure if it takes into account various edge cases; comment if this is the case, or provide an alternate answer.

How to read the correct time/duration values from Google Spreadsheet

I'm trying to get from a time formatted Cell (hh:mm:ss) the hour value, the values can be bigger 24:00:00 for example 20000:00:00 should give 20000:
Table:
if your read the Value of E1:
var total = sheet.getRange("E1").getValue();
Logger.log(total);
The result is:
Sat Apr 12 07:09:21 GMT+00:09 1902
Now I've tried to convert it to a Date object and get the Unix time stamp of it:
var date = new Date(total);
var milsec = date.getTime();
Logger.log(Utilities.formatString("%11.6f",milsec));
var hours = milsec / 1000 / 60 / 60;
Logger.log(hours)
1374127872020.000000
381702.1866722222
The question is how to get the correct value of 20000 ?
Expanding on what Serge did, I wrote some functions that should be a bit easier to read and take into account timezone differences between the spreadsheet and the script.
function getValueAsSeconds(range) {
var value = range.getValue();
// Get the date value in the spreadsheet's timezone.
var spreadsheetTimezone = range.getSheet().getParent().getSpreadsheetTimeZone();
var dateString = Utilities.formatDate(value, spreadsheetTimezone,
'EEE, d MMM yyyy HH:mm:ss');
var date = new Date(dateString);
// Initialize the date of the epoch.
var epoch = new Date('Dec 30, 1899 00:00:00');
// Calculate the number of milliseconds between the epoch and the value.
var diff = date.getTime() - epoch.getTime();
// Convert the milliseconds to seconds and return.
return Math.round(diff / 1000);
}
function getValueAsMinutes(range) {
return getValueAsSeconds(range) / 60;
}
function getValueAsHours(range) {
return getValueAsMinutes(range) / 60;
}
You can use these functions like so:
var range = SpreadsheetApp.getActiveSheet().getRange('A1');
Logger.log(getValueAsHours(range));
Needless to say, this is a lot of work to get the number of hours from a range. Please star Issue 402 which is a feature request to have the ability to get the literal string value from a cell.
There are two new functions getDisplayValue() and getDisplayValues() that returns the datetime or anything exactly the way it looks to you on a Spreadsheet. Check out the documentation here
The value you see (Sat Apr 12 07:09:21 GMT+00:09 1902) is the equivalent date in Javascript standard time that is 20000 hours later than ref date.
you should simply remove the spreadsheet reference value from your result to get what you want.
This code does the trick :
function getHours(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var cellValue = sh.getRange('E1').getValue();
var eqDate = new Date(cellValue);// this is the date object corresponding to your cell value in JS standard
Logger.log('Cell Date in JS format '+eqDate)
Logger.log('ref date in JS '+new Date(0,0,0,0,0,0));
var testOnZero = eqDate.getTime();Logger.log('Use this with a cell value = 0 to check the value to use in the next line of code '+testOnZero);
var hours = (eqDate.getTime()+ 2.2091616E12 )/3600000 ; // getTime retrieves the value in milliseconds, 2.2091616E12 is the difference between javascript ref and spreadsheet ref.
Logger.log('Value in hours with offset correction : '+hours); // show result in hours (obtained by dividing by 3600000)
}
note : this code gets only hours , if your going to have minutes and/or seconds then it should be developped to handle that too... let us know if you need it.
EDIT : a word of explanation...
Spreadsheets use a reference date of 12/30/1899 while Javascript is using 01/01/1970, that means there is a difference of 25568 days between both references. All this assuming we use the same time zone in both systems. When we convert a date value in a spreadsheet to a javascript date object the GAS engine automatically adds the difference to keep consistency between dates.
In this case we don't want to know the real date of something but rather an absolute hours value, ie a "duration", so we need to remove the 25568 day offset. This is done using the getTime() method that returns milliseconds counted from the JS reference date, the only thing we have to know is the value in milliseconds of the spreadsheet reference date and substract this value from the actual date object. Then a bit of maths to get hours instead of milliseconds and we're done.
I know this seems a bit complicated and I'm not sure my attempt to explain will really clarify the question but it's always worth trying isn't it ?
Anyway the result is what we needed as long as (as stated in the comments) one adjust the offset value according to the time zone settings of the spreadsheet. It would of course be possible to let the script handle that automatically but it would have make the script more complex, not sure it's really necessary.
For simple spreadsheets you may be able to change your spreadsheet timezone to GMT without daylight saving and use this short conversion function:
function durationToSeconds(value) {
var timezoneName = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (timezoneName != "Etc/GMT") {
throw new Error("Timezone must be GMT to handle time durations, found " + timezoneName);
}
return (Number(value) + 2209161600000) / 1000;
}
Eric Koleda's answer is in many ways more general. I wrote this while trying to understand how it handles the corner cases with the spreadsheet timezone, browser timezone and the timezone changes in 1900 in Alaska and Stockholm.
Make a cell somewhere with a duration value of "00:00:00". This cell will be used as a reference. Could be a hidden cell, or a cell in a different sheet with config values. E.g. as below:
then write a function with two parameters - 1) value you want to process, and 2) reference value of "00:00:00". E.g.:
function gethours(val, ref) {
let dv = new Date(val)
let dr = new Date(ref)
return (dv.getTime() - dr.getTime())/(1000*60*60)
}
Since whatever Sheets are doing with the Duration type is exactly the same for both, we can now convert them to Dates and subtract, which gives correct value. In the code example above I used .getTime() which gives number of milliseconds since Jan 1, 1970, ... .
If we tried to compute what is exactly happening to the value, and make corrections, code gets too complicated.
One caveat: if the number of hours is very large say 200,000:00:00 there is substantial fractional value showing up since days/years are not exactly 24hrs/365days (? speculating here). Specifically, 200000:00:00 gives 200,000.16 as a result.

Subtract two date variables and get in terms of days in javascript

Here is my code.
var today = new Date();
var reqDate = new Date(today.getFullYear(),today.getMonth()-3, today.getDate());
var day = today-reqDate;
I want the 'day' should be something around 90; but it gives as some long integer.
The long integer is the number of milliseconds since midnight Jan 1, 1970. So in order to get the number of days you need to divide it. Code below:
var days = day/(1000*60*60*24);
You have got value in day variable as milliseconds, so divide it by 1000*60*60*24 to get day count.
Another thing, it will be a decimal value.
So you have to discard fraction value using floor function.
var days = Math.floor(day/(1000*60*60*24));

Categories

Resources