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);
Related
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);
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}`);
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>
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I want to the current date/time formatted in this format:
year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Currently I'm doing it as such. Is there a more elegant approach without the use of external libraries like moment.js?
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var milli = now.getMilliseconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
if(milli.toString().length == 1) {
var milli = '0'+milli;
}
var m_session_startTime = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Leverage template literals instead of concatenation and padStart() to fill leading zeros.
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
const milli = String(now.getMilliseconds()).padStart(4, "0");
const m_session_startTime = `${year}-${month}-${day} ${hour}:${minute}:${second}:${milli}`;
console.log(m_session_startTime);
You could use moment.js, it really helps you with formatting dates.
console.log(moment().format('YYYY-MMMM-DD h:mm:ss:SSS'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
This command does the job pretty well. moment() is a date object, when there are no arguments given like in this example it takes the current time but you can also use moment("2018-12-4") for specific dates.
You can then format the date according to your need,
YYYY is the full year (2018)
MMMM is the full month name (July)
(you can also use MMM for the short version of the month name)
DD is the day as a number (24)
(you can also use dddd for the full name of the day or ddd for the short name)
h is the hour as number (22)
mm is the minute as a number (23)
ss is the second as a number (as an example 22)
SSS is the millisecond as a number (example 245)
Try this?
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
console.log(jsonDate);
> 2018-07-24 20:32:06:435
Alternatively, if you want to split the entire thing into substrings:
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
let dateTime = jsonDate.split(" ");
let dt = dateTime[0].split("-");
let tt = dateTime[1].split(":");
let year = dt[0];
let month = dt[1];
let day = dt[2];
let hour = tt[0];
let minute = tt[1];
let second = tt[2];
let mili = tt[3];
console.log(jsonDate);
console.log(dateTime[0]);
console.log(dateTime[1]);
console.log([year, month, day, hour, minute, second, mili].join("~"));
console.log("Date: " + [year, month, day].join("-") + " Time: " + [hour, minute, second, mili].join(":"));
> 2018-07-24 21:03:05:706
> 2018-07-24
> 21:03:05:706
> 2018~07~24~21~03~05~706
> Date: 2018-07-24 Time: 21:03:05:706
As you might have noticed from this response, I work with databases. I have heavy bash, javascript, php, sql, golang background.
Use a moment.js. Great library that is designed to exactly what you would like. You can use the .format option.
var now = moment().format('YYYY-MM-DD HH:mm:ss.SSS');
$('#timeval').text(now);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current Time: <br>
<a id="timeval"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
https://momentjs.com/
Is it possible to do the below c# logic in javascript or jquery, The code converts duration between two dates int hours,minutes and seconds.the duration 20/01/2017 00:00:00 to 20/01/2017 02:20:30 will be 26:20:30
This about converting to hh:mm:ss format hours can go beyond 24, if minutes are more than 59 it should add to hours and seconds more than 59 should add to hours.
public static string ToTimeFormat(bool includeSeconds = false)
{
var startDate = DateTime.parse("20/01/2017 00:00:00";
var endDate = DateTime.parse("20/01/2017 02:20:30");
var ts = endDate - startDate;
var totalDaysToHours = ts.Days * 24;
return string.Format("{0}:{1}", (ts.Hours + totalDaysToHours).ToString("0"),
ts.Minutes.ToString("D2"))
+ (includeSeconds ? ":" + ts.Seconds.ToString("D2") : string.Empty);
}
You can use moment.js from here moment.min.js and below is the code
var startDate = "01/02/2016 00:00:00"; //MM/DD/YYYY HH:MM:SS format
var endDate = "01/03/2016 01:30:30"; //MM/DD/YYYY HH:MM:SS format
var diff = moment.duration(moment(endDate).diff(moment(startDate)));
var formatedData=[diff.asHours().toFixed(0), diff.minutes(), diff.seconds()].join(':');
so your output will be like
26:30:30
UPDATE
var startDate = "01/02/2016 00:00:00".split(/\//);
startDate= [ startDate[1], startDate[0], startDate[2] ].join('/'); // DD/MM/YYYY to MM/DD/YYYY
var endDate = "01/03/2016 01:30:30".split(/\//);
endDate = [ endDate[1], endDate[0], endDate[2] ].join('/'); // DD/MM/YYYY to MM/DD/YYYY
var diff = moment.duration(moment(endDate).diff(moment(startDate)));
var formatedData=[diff.asHours().toFixed(0), diff.minutes(),diff.seconds()].join(':');