These are my time formats;
const startTime = "20:00";
const endTime = "05:00";
const startDate = "2021-01-20T00:00:00+05:30"
const days = "1"; // it can be 0 also
Now, I need to find the difference between startTime and endTime using moment, and as the "days = 1", it means the endTime ends on the next day:
So the expected output would be,
9hrs 0mints on 2021-01-21
( As the days says 1, we need to count one day and show the endDate and if days=0 means same date as start date )
How to perform this using moment?
As tried I,
var dif = moment.duration(endTime.diff(startTime))
But it gives the error "endTime.diff is not a function". Please help.
You can use this way when the time duration of more than 24 hours.
var startTime = moment("20:23", "HH:mm");
var endTime = moment("05:10", "HH:mm");
var days ="1";
// calculate the days in milliseconds
var duration = moment.duration(parseInt(days), 'days');
var day = duration.asMilliseconds();
//calculate the total milliseconds
var ms = day + moment(endTime,"HH:mm").diff(moment(startTime,"HH:mm"));
var d = moment.duration(ms);
//get the total duration
var s = Math.floor(d.asHours())+" hrs " + moment.utc(ms).format("mm") + " mins";
console.log(s);
Related
I'm passing a string representing a 24 hour datetime like HH:mm, I'm trying to format it in order to compare and get remaining time between two datetimes, however I'm getting a very weird output and my function is returning NaN when outputting time difference..
const remainingHourAndMinute = (endDate) => {
var now = moment().format('HH:mm');
console.log('now', now);
var end = moment(endDate, 'HH:mm'); //Here I format the string to a moment object
console.log('end', end);
var duration = moment.duration(end.diff(now));
//Get Days and subtract from duration
var days = duration.asDays();
duration.subtract(moment.duration(days, 'days'));
//Get hours and subtract from duration
var hours = duration.hours();
duration.subtract(moment.duration(hours, 'hours'));
//Get Minutes and subtract from duration
var minutes = duration.minutes();
duration.subtract(moment.duration(minutes, 'minutes'));
//Get seconds
var seconds = duration.seconds();
return hours > 0 ? hours + ' horas y ' + minutes + ' minutos' : minutes + ' minutos';
};
let closingTime = '21:00';
let remaining = remainingHourAndMinute(closingTime);
console.log(remaining);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
This is what the console logs.
now 18:56
end "2020-12-09T20:00:00.000Z"
diff NaN minutes
Notice how the now time is a normal 24h datetime but end is such a weird parsed format, that's why I think my function is giving me NaN, because I'm comparing dattimes in different formats...
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);
I have two times (basically start time and end time). Also, I have the number of questions played by the user. I wanna know the average time user spent for each question.
//startGameTime: 2019-07-27T07:58:42.000Z
//endGameTime: 2019-07-27T07:59:57.000Z
function averageQuestionTime(startGameTime, endGameTime, totalNumberOfQuestions) {
var d1 = new Date(startGameTime);
var d2 = new Date(endGameTime);
var d1msecs = new Date(d1).getTime(); // get milliseconds
var d2msecs = new Date(d2).getTime(); // get milliseconds
var avgTime = (d1msecs + d2msecs) / totalNumberOfQuestions;
var date = new Date(avgTime);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
return (day + ":" + hour + ":" + min + ":" + sec)
}
I understand my logic is completely flawed as the units for date and time and nos of questions are different. What is the best way to achieve the result ?
There are good libraries which prevent the users from having to reinvent the wheel every time they want to manipulate date/time in Node.
Obtaining time difference is pretty simple (I can see you are doing it correctly to obtain the difference in milliseconds) and libraries make them even simpler.
See how simple it is using momentJS
var moment = require('moment');
var startDate = moment('2019-7-24 00:00:00', 'YYYY-M-DD HH:mm:ss');
var endDate = moment('2019-7-24 05:27:31', 'YYYY-M-DD HH:mm:ss');
var diffSeconds = endDate.diff(startDate, 'seconds');
var diffHours endDate.diff(startDate, 'seconds');
console.log(`Avg in secs: ${diffSeconds / totalNumberOfQuestions}`);
console.log(`Avg in secs: ${diffHours/ totalNumberOfQuestions}`);
I have two times which are in 12 hours format. Example 10:00 am and 3:30 pm. I want to show 330 minutes between them. I have tried many ways but couldn't get accurate result.
my script:
time1= 'yy/mm/dd 10:00 am';
time2='yy/mm/dd 3:30 pm';
from1 = new Date(time1);
to1 = new Date(time2);
console.log(from1-to1);
I don't usually like writing code for people, but I'm feeling nice today.
function parse12hToMin(timeStr){ //returns the minutes as an offset from 12:00 AM
let match12h = new RegExp(
"^" + // start of string
"(1[0-2]|[1-9])" + // hour
":" + // separator
"([0-5][0-9])" + // minutes
" " + // separator
"(am|pm)" // AM or PM
, 'i'); // case insensitive
let matched = timeStr.match(match12h);
let min = parseInt(matched[1]) * 60 // hours
+ parseInt(matched[2]) // minutes
+ (matched[3].toLowerCase() === "pm" ? 720 : 0); // 720 min PM offset
return min;
}
function minutesDiff12h(start, end){
return parse12hToMin(end) - parse12hToMin(start);
}
console.assert(minutesDiff12h("10:00 am","3:30 pm") === 330);
Please always try to list what you tried, and show us the code snippets that aren't working.
I would isolate the hours part of your time and use 24hr time to make things easier.
var start_time ="1000";
var end_time ="1530";
var start_hour = start_time.slice(0, -2);
var start_minutes = start_time.slice(-2);
var end_hour = end_time.slice(0, -2);
var end_minutes = end_time.slice(-2);
var startDate = new Date(0,0,0, start_hour, start_minutes);
var endDate = new Date(0,0,0, end_hour, end_minutes);
var millis = endDate - startDate;
var minutes = millis/1000/60;
console.log(minutes);
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