Time difference in javascript time1-time2 - javascript

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.

Related

Set Hours in Date() to 0 [duplicate]

i am trying to get current date to compare and setting hours to zero but still getting time.
var today = new Date(new Date().setHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);
my output like :
2018-03-20T18:30:00.000Z
I need to get date as it is but time 2018-03-20T00:00:00.000Z
When you create a new Date(), the time zone is that of the system. When you use toISOString(), the time is printed in UTC. This means that your code will print a different result when running on systems with different time zones (it prints 2018-03-20T23:00:00.000Z for me).
Instead of using setHours(), use setUTCHours().
var today = new Date(new Date().setUTCHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);

How do I get difference between two dates of unknown format in javascript?

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);

calculate minutes from starting and ending time

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/

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');

javascript unixtime one minute in front

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

Categories