getting time difference between a date and current date using moment - javascript

Hi I am trying to get the time difference between two dates. I have written a function which does this but when I convert the passed in date from shared preferences to moment date it gives me single digit number.
Using this in my react native project
I tried the same with manual input dates as string and it works fine.
what am I doing wrong here?
//This function does not work as expected (I want this function to return the time difference)
export const getTimeDiffWithCurrentTime = (lastLoggedInDateTime) => {
var moment = require('moment');
//***PROBLEM IS HERE IN THE BELLOW LINE WHERE THE OUTPUT IS 1547571895000***
var momentLastLoggedInDateTime = moment(lastLoggedInDateTime, "DD-MM-YYYY HH:mm:ss");
var currentDateTime = moment().format("DD-MM-YYYY HH:mm:ss");
consoleLog(' lastLoggedInDateTime - ' + lastLoggedInDateTime + 'momentLastLoggedInDateTime - ' + momentLastLoggedInDateTime
+ ' currentDateTime - ' + currentDateTime);
var timeDifference = currentDateTime.diff(momentLastLoggedInDateTime);
consoleLog("Time difference - " + timeDifference);
return timeDifference;
}
output :
lastLoggedInDateTime - 15-01-2019 17:04:55momentLastLoggedInDateTime - 1547571895000 currentDateTime - 15-01-2019 17:04:57
error -TypeError: currentDateTime.diff is not a function
Test Function that works
export const getTimeDiff = () => {
var moment = require('moment');
var now = moment("04-09-2013 15:00:00", "DD-MM-YYYY HH:mm:ss");
var then = moment("04-09-2013 14:59:40", "DD-MM-YYYY HH:mm:ss");
var timeDifference = now.diff(then);
consoleLog("Time difference - " + timeDifference);
}
output :
Time difference - 20000
I want to get the function getTimeDiffWithCurrentTime to work by passing a date and get the difference.
your help is much appreciated
R
UPDATE
Got it working. Few things to note.
Some have suggested to just use var momentLastLoggedInDateTime = moment(lastLoggedInDateTime);
but that gave me a warning similar to
Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info. Arguments: [0] _isAMomentObject: true, _isUTC: true, _useUTC: true, _l: undefined, _i: 2016-9-26 19:30, _f: undefined, _strict: undefined, _locale: [object Object]
So I had to use var momentLastLoggedInDateTime = moment(lastLoggedInDateTime, "DD-MM-YYYY HH:mm:ss");
which gave me a value 1547571895000
Only change I had to make to the function 'getTimeDiffWithCurrentTime' was to change var currentDateTime = moment().format("DD-MM-YYYY HH:mm:ss"); to var currentDateTime = moment();
so the working function is
export const getTimeDiffWithCurrentTime = (lastLoggedInDateTime) => {
var moment = require('moment');
var momentLastLoggedInDateTime = moment(lastLoggedInDateTime, "DD-MM-YYYY HH:mm:ss");
var currentDateTime = moment(); //This was the change required
consoleLog(' lastLoggedInDateTime - ' + lastLoggedInDateTime + 'momentLastLoggedInDateTime - ' + momentLastLoggedInDateTime
+ ' currentDateTime - ' + currentDateTime);
var timeDifference = currentDateTime.diff(momentLastLoggedInDateTime);
consoleLog("Time difference - " + timeDifference);
return timeDifference;
}
Output
lastLoggedInDateTime - 15-01-2019 18:12:26momentLastLoggedInDateTime - 1547575946000 currentDateTime - 1547575952574
Time difference - 6574
Thank you

according to the documentation of moment, basically with no parameters, the diff function returns a number in milliseconds, you can use years, months, weeks, days, hours, minutes, and seconds if you want to use a different time unit.
take into account:
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.
check a working piece of code which shows other types of units.
const getTimeDiff = (differenceIn = 'milliseconds', floating= false) => {
var now = moment("04-09-2013 15:00:00", "DD-MM-YYYY HH:mm:ss");
var then = moment("04-09-2013 14:59:40", "DD-MM-YYYY HH:mm:ss");
//this return the difference between now and then in milliseconds as default
var timeDifference = now.diff(then, differenceIn, floating);
console.log("Time difference - " + timeDifference + ' ' + differenceIn);
}
getTimeDiff();
getTimeDiff('seconds');
getTimeDiff('seconds', true);
getTimeDiff('minutes');
getTimeDiff('minutes', true);
getTimeDiff('hours');
getTimeDiff('hours', true);
getTimeDiff('days');
getTimeDiff('days', true);
getTimeDiff('weeks');
getTimeDiff('weeks', true);
getTimeDiff('months');
getTimeDiff('months', true);
getTimeDiff('years');
getTimeDiff('years', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.js"></script>
On your code, check that you are trying to do a diff of a String.
Basically you are doing a format before applying the diff.
const getTimeDiffWithCurrentTime = (lastLoggedInDateTime) => {
//***PROBLEM IS HERE IN THE BELLOW LINE WHERE THE OUTPUT IS 1547571895000***
var momentLastLoggedInDateTime = moment(lastLoggedInDateTime, "DD-MM-YYYY HH:mm:ss");
//var currentDateTime = moment().format("DD-MM-YYYY HH:mm:ss"); IF YOU DO THIS, you get a STRING
var currentDateTime = moment()
console.log(' lastLoggedInDateTime - ' + lastLoggedInDateTime + 'momentLastLoggedInDateTime - ' + momentLastLoggedInDateTime +
' currentDateTime - ' + currentDateTime);
var timeDifference = currentDateTime.diff(momentLastLoggedInDateTime);
console.log("Time difference - " + timeDifference);
return timeDifference;
}
const newDate = new Date(new Date() - 10000); //minus 10 seconds
getTimeDiffWithCurrentTime(newDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.js"></script>

var now = moment(new Date());
var then = moment("04-09-2013 14:59:40", "DD-MM-YYYY HH:mm:ss");
var timeDifferenceInSeconds = now.diff(then, 'seconds');
var timeDifferenceInHours = now.diff(then, 'hours');
var timeDifferenceInDay = now.diff(then, 'days');
console.log(timeDifferenceInHours, timeDifferenceInSeconds, timeDifferenceInDay);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

Related

do some math actions with strings in Javascript

I have two-hour data they are as strings let first = "09:15" let second = "10:15" how can I do some math actions with these strings? for example I want to do console.log(first - second)
Convert them from String to Date using Date.parseExact() from date.js library
var dateString = "10:12";
var date = new Date.parseExact(dateString, "HH:mm");
and then you can use : second.diff(first)
var dateString = "10:12";
var dateString2 = "10:20";
var startTime=moment(dateString, "HH:mm:ss a");
var endTime=moment(dateString2, "HH:mm:ss a");
var duration = moment.duration(endTime.diff(startTime));
var hours = parseInt(duration.asHours());
var minutes = parseInt(duration.asMinutes())-hours*60;
alert (hours + ' hour and '+ minutes+' minutes.')
var result = endTime.diff(startTime, 'hours') + " Hrs and " +
endTime.diff(startTime, 'minutes') + " Mns";
alert(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Also you can use MomentJS JavaScript library .

Javascript moment subtract lunchtime from workhours

I want to subtract lunch hours from datetime differece
How it can be achieved?
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 08:00:00.0
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 18:00:00.0
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss"); //00:30:00
var lunchTimeMs= moment(Lunch,"HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
ms = moment().subtract(lunchTimeMs); //This gives wrong result
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Total time " + i + " row" + s);
He is using Moment JS.
As far as I understood, the problem is that he has only date with time to manipulate in format similar to: dd.mm.YYYY HH:ii:ss.
My recommendation was to transfer server response datetime to timestamp using JS. It's much easier to manipulate date and time differences if you are using a timestamp.
UPDATE
Adding here my "vision" of JS date management (my fiddle). Feel free to improve it!
const date2timestamp= function(str){
_tmp = str.split(" ");
if(_tmp){
date_arr = ( _tmp[1] ? _tmp[0].split("-") : null );
time_arr = ( _tmp[1] ? _tmp[1].split(":") : _tmp[0].split(":") );
if(!date_arr) {
const today = new Date();
_date = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), time_arr[0], time_arr[1], time_arr[2]);
}
else {
_date = Date.UTC(date_arr[0], date_arr[1]-1, date_arr[2], time_arr[0], time_arr[1], time_arr[2]);
}
date_obj = new Date(_date);
return date_obj.getTime()/1000;
}
return false;
}
document.write(
date2timestamp("2020-04-20 08:00:00")+"<br/>",
date2timestamp("2020-04-20 17:00:00")+"<br/>",
date2timestamp("00:03:00")
);
And now you have timestamps. When you subtract, you know, that the 1min = 60sec, so the result is ((7*60)+30)*60 = date2timestamp("2020-04-20 17:00:00")-date2timestamp("2020-04-20 17:00:00")-(30*60)
MORE UPDATES
But, reading about the moment.js a bit, there is even easier way. Manual for subtract says:
moment().subtract(1, 'seconds');
that means, you have to actually transfer your Launch period into seconds and then add put it into the subtract: moment().subtract((30*60), 'seconds') or just add (for test) 'millisecond' as second part of subtract:
...
ms = moment().subtract(lunchTimeMs, 'milliseconds');
// or use that
ms = moment().subtract(lunchTimeMs/1000, 'seconds);
...
Try this:
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss");
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss");
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
moment(ms).subtract(Lunch);

round up hour difference in time to 2 decimal places with javascript

i'm trying to calculate the hours difference between to times using javascript. But i keep get the results NaN in the console. I get the current time using javascript and the late time from the localstorage
var log_time = localStorage.getItem('login_time')
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
console.log(log_time);
var today = day + "/" + month + "/" + year
var time = hour + ":" + minute + ":" + second
console.log(today+' '+time);
var date1 = (log_time);
var date2 = (today+' '+time);
var hours = Math.abs(date2 - date1) / 36e5;
console.log(hours.toFixed(2))
the time from the localstorage reads 15/7/2017 9:30:46
You need to change your date format little bit This may Help you and also parse those dates because those are stirng formate.
Working Fiddle
var log_time1 = '2017-07-15 09:30:46';//Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var log_time = new Date(log_time1)//string parsing date
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
var today = year + "-" + month + "-" + day
var time = hour + ":" + minute + ":" + second
var date1 = (log_time);
var test_date2 = (today+' '+time);
var date2= new Date(test_date2);//string parsing date
var hours = Math.abs(date2 - date1) / 36e5;
alert(hours.toFixed(2))
localStorage will store stringified version of any object, you need to parse it. If you converted it to milliseconds then also you need to parse it to number, it can save only string
var earlierDate = new Date( localStorage.getItem('login_time'))
// or var earlierDate = parseInt(localStorage.getItem('login_time'))
var currentDate = new Date()
var diff = currentDate - earlierDate;
Then convert diff to hour/minutes/seconds with your logic
Im not shure what youre trying to do here:
date2 - date1
These are booth strings, you cannot substract them. However you might convert them to milliseconds since 1970 which you could then do Math on:
var log_time = localStorage.getItem('login_time').split(" ");
log_time[0]=log_time[0].split("/").reverse().map((el,i)=>i?("0"+el).slice(-2):el).join("-");//5/4/2017 => 2017-04-05
log_time[1]=("0"+log_time[1]).slice(-8);// 9:30:10 => 09:30:10
var difference= new Date() - new Date(log_time.join("T"));
var hours=Math.floor(difference/(1000*60*60 /* one hour in ms */));
You may overthink the stored format. Its quite complicated to parse it properly.
http://jsbin.com/fofowayata/edit?console

How to loop between dates that are in dmy format

Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.

The day of the month does not show up properly in javascript (html)

This is my javascript code:
function borrowbook ()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var input_day = document.getElementById("textbox").value;
var newday = today.setDate(day + input_day);
var fulltime1 = newday + "-" + month + "-" + year;
alert ("Return Date is: " + fulltime1);
}
And the result was not my expected result:
Actually what I want to do is if a user enters a value in 'Days allowed',I want to display the book return date.But I do not know why does the day of the month cannot show up properly.Any suggestion to solve this problem?
When you do:
var newday = today.setDate(day + input_day);
you are setting the value of newday to the return value of today.setDate(...), which is a time clip.
Since *input_day* is the value of a form control, and such values are always strings, the + operator will concatenate the values, not add them.
What you probably want is the date, so:
today.setDate(day + +input_day); // set the new date, converting input_date to Number
var newday = today.getDate(); // get the new date
Also, you should get the month and year after adding the day as it may change their values:
31 May + 1 day -> 1 June
There are three things you need to change.
Here is a working jsfiddle.
http://jsfiddle.net/bbankes/VMn3x/
First, the month and the year may also be incorrect. If today were 31-Dec 2014, your code would not show 10-Jan 2014, but instead 10-Dec 2013. You can rectify this by getting the day month and the year from the renew date instead of today's date.
Second, input_day is a string, so you need to parse it as an integer using the built-in javascript function parseInt();
Third, the setDate() method on a Date object does not return the new date. This is the problem that RobG shows.
The new function is as follows:
function borrowbook() {
var today = new Date();
var day = today.getDate();
var input_day = document.getElementById("textbox").value;
var returnDate = new Date();
returnDate.setDate(day + parseInt(input_day));
var returnDay = returnDate.getDate();
var returnMonth = returnDate.getMonth() + 1;
var returnYear = returnDate.getFullYear();
var fulltime1 = returnDay + "-" + returnMonth + "-" + returnYear;
alert ("Return Date is: " + fulltime1);
}

Categories