I am trying to calculate how many minutes a worker works from the input starting and ending time(e.g. 10:30 am to 3:30pm). Could u guys help how to calculate them? Could u check my code and correct them? I am very new in Javascript.
function myFunction(){
var sTime=document.getElementById("startTime").value;
var eTime=document.getElementById("endTime").value;
var diff = sTime-eTime;
var result= diff.getMinutes();
document.getElementById("demo").innerHTML=result`;
https://jsbin.com/bolapox/edit?html,output
You will need to turn the users input into a usable format with Date().parse(input). This returns the number of milliseconds since 1 January, 1970, 00:00:00, local time.
You can then take the difference in milliseconds and convert them into minutes.
var sTime=Date().parse(document.getElementById("startTime").value);
var eTime=Date().parse(document.getElementById("endTime").value);
var diff = eTime - sTime;
var result = diff / 60000;
You should consider Moment.js, here yiou can find some examples:
http://momentjs.com/docs/#/durations/
Related
let oneDay = 24*60*60*1000;
let firstDate = new Date();
let secondDate = this.props.eventData.date
let finalSecDate = new Date(secondDate)
var timeDiff = Math.abs(firstDate.getTime() - finalSecDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
I am trying to calculate the number of days between two dates using javascript in a redux project. (My second date variable above is based on the date that a user enters and then I am changing it into a new Date format.) The above code works but when the event has passed the the number of days until the event is still coming up as positive number of days. Can someone please help me distinguish whether or not the date has passed so I can get the negative number of days.
I appreciate any help you can give, thank you !
I would recommend using Moment.js, since they have a number of date functions that will become useful as you play around with dates more.
Here's what it would look like if you wanted to find the difference between two dates:
var present = moment();
var end = this.props.eventData.date;
present.diff(end, 'days') // 5
The diff function finds the difference between the two dates. It also solves your problem of returning a negative value if the date already passed.
var present = moment();
var past = moment('2014-02-03 12:53:12');
past.diff(present, 'days') // -1379
I've been working on calculating the total hours, minutes and seconds between two times using the moment.js library. The problem I have is that the calculations don't recognise that it's a day and return more hours than what is there. I'll give you an example:
I want to know how many hours are between 21:00 and 06:00, the answer is 9, however, the calculation brings back -15, this is also technically correct. I need to tell moment that it should use a day to calculate this value. I can get it to work if I use a DateTime picker but I don't want to use that as the user is only required to provide a time.
My application uses KendoUI for MVC and moment.js, moment.duration.format.js and moment.range.js
Here is my code which will return -15
#(Html.Kendo().TimePicker().Name("start").Value("21:00"))
#(Html.Kendo().TimePicker().Name("end").Value("06:00"))
<button class="btn btn-default btn-success" onclick="calc()">Plot</button>
Here is the javascript that works with this.
function calc() {
window['moment-range'].extendMoment(moment);
console.clear();
var dformat = "HH:mm:ss";
var start = $("#start").data("kendoTimePicker").value();
var end = $("#end").data("kendoTimePicker").value();
var startTime = moment(kendo.toString(start));
var endTime = moment(kendo.toString(end));
var duration = moment.duration(endTime.diff(startTime));
var hours = parseInt(duration.asHours());
console.log(hours);
}
If we change this to use DateTimePicker instead, it understands there is a day and calculates 9 hours. So how do I get around this? How can I achive this without using a datetime picker? Can I leaverage moment.js startof day or something?
Thanks to #VincenzoC I have managed to fix this problem. Here is the code which checks if the end time is before the start time and if it is, add a single day. This means the resulting time is accurate.
var startTime = moment(start);
var endTime = moment(end);
if (endTime.isBefore(startTime))
{
endTime.add(1, 'd');
}
//
//After the above condition has been passed, calculate the difference
var duration = moment.duration(endTime.diff(startTime));
//
//Any format you want
console.log(duration.format("HH"))
I get a date as String from server like this: 2017-01-23T16:08:45.742Z. I want to find the difference in days, between this and the current date (or precisely, current time). I could just extract date alone (without time) and check, but I'd need a precise answer based on provided time & current time.
How do I achieve this?
Should be easy....
var dateFromServer = '2017-01-23T16:08:45.742Z'
var msInDay = 1000 * 60 * 60 * 24
var difference = (new Date(dateFromServer) - Date.now()) / msInDay
document.write('difference = ' + difference + ' days')
That date format looks like ISO_8061. https://en.wikipedia.org/wiki/ISO_8601
Use the Date object to get the difference between today and the other date in milliseconds, then divide by the number of milliseconds in a day.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
The code below can be condensed into a single line but I wanted to be explicit.
let date = "2017-01-23T16:08:45.742Z";
let d1 = new Date(date); // given date
let today = new Date(); // today's date
let diff = (d1 - today); // difference in milliseconds
let days = diff / 8.64e+7; // divide difference by 1 day in milliseconds
console.log(days)
Point of clarification: if I understand you correctly, you're actually trying to get the difference between two dates of different formats, not two dates of unknown formats. That's way easier.
Further, it looks like your server string is already stored in ISO format, which again makes this way easier.
I'd recommend looking at the JavaScript Date object. I believe in this case your best bet would be something like this:
// Your string from the server
var data_from_server = '2017-01-23T16:08:45.742Z';
// Create a new Date() object using the ISO string provided by your server
var olddate = new Date(data_from_server);
// Create a new empty Date() object, which should default to the current time
var currentdate = new Date();
// Subtract the two
var dif = currentdate.getTime() - olddate.getTime();
// Alert the result
alert(dif);
I have 2 variables in javascript where 2 times has been stored for a reason.
say for ex:
var currentdate = new Date();
var time1 = "24:00:00"; // everytime this will be 24
var time2 = var time2 = currentdate.getHours() +":"+ currentdate.getMinutes() ; // this is the system time
need difference between the 2 times.
If have tried with time1-time2 but it is not working.
I want to make if difference between the 2 times is x, then perform some task. I need the difference thats it.
Something like this should work if your times are in the standard format that counts the date/time as the number of milliseconds from Jan 1, 1970. See here for details.
difference = parseInt(time2) - parseInt(time1)
Lastly, you can set a date to tonight's midnight (the one that has already passed) like this:
var midnight = new Date();
midnight.setHours(0,0,0,0);
Then, use it to subtract your time of interest using the method above where both variables have Date type.
Hi I'm passing a unixtimestamp to a javascript IF statement, can anyone tell me how to generate a unixtimestamp one minute in the future with javascript.
Anyhelp would be helpful.
Thanks
The JavaScript Date object has a getTime() method that returns milliseconds since 1970. To make this look like a UNIX timestamp, you need to divide by 1000 and round (with Math.floor()). Adding 60 get's your one minute ahead.
var d = new Date();
var unixtimeAdd60 = Math.floor(d.getTime()/1000)+60;
UNIX time is just the number of seconds since 1970-01-01Z. So just add 60 you'll get a timestamp one minute later.
JavaScript Date object's getTime returns the number of milliseconds since midnight Jan 1, 1970.
Try this.
var oneMinLater = new Date().getTime() + 60 * 1000;
var d = new Date();
d.setTime(oneMinLater);
Another way to get the unix timestamp (this is time in seconds from 1/1/1970) in a simple way its:
var myDate = new Date();
console.log(+myDate + 60); // you just sum the seconds that you want
// +myDateObject give you the unix from that date