Javascript : How to calculate the difference between two dates? [duplicate] - javascript

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
How to calculate the difference between two dates say date 1 is 28-04-2014 and date 2 is 30-04-2014 how to find the difference using javascript .

If you are using the datepicker from jQuery UI (or probably any other datepicker tool out there), you can chose what date format you want to recieve. In jQuery UI, use $( "#datepicker" ).datepicker( "option", "dateFormat", "yy-mm-dd" ); to get ISO 8601 dates, and then just compare them like this:
if ( dateOne < dateTwo ) ...
By using a standardized date format, you also know for sure that you will always be able to painlessly convert it to what ever format you want to display it in later.

Vishwas' answer was actually pretty close, even though it's getting downvoted. You need to pass in a valid date format into the new Date() constructor.
var date1 = new Date("28-04-2014".split("-").reverse());
var date2 = new Date("30-04-2014".split("-").reverse());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays, "number of days difference");
console.log(timeDiff, "in milliseconds");
The Date constructor needs dates in the form new Date(year, month, day, hour, minute etc etc..) and takes arrays too.
Since your date format is in the form day-month-year we take your string and split it (by -) and reverse it to get [year, month, day]
Full Date Object Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Related

Want to get difference between two dates in js? [duplicate]

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 4 years ago.
I tried so many solution on stack overflow itself, but not get the difference in js.
I was using
var days = ('13-10-2018'- '13-09-2018') / (1000 * 60 * 60 * 24)]
Well, there are 2 issues here.
First, you need to use your date strings to construct a proper JavaScript Date object, which only supports IETF-compliant RFC 2822 timestamps and also a version of ISO8601, as you can see in MDN. Therefore, you can't use DD-MM-YYYY, but you could use MM-DD-YYYY
Another way to construct a Date object is to use this syntax:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
So, to calculate the difference between 2 dates in the format DD-MM-YYYY, you first need to parse that and create two Date objects. Then, you call Date.prototype.getTime() in both of them and calculate the absolute difference in milliseconds. Lastly, you convert that to days dividing by 3600000 * 24 and rounding (if you don't want decimal days):
function getDateFromDDMMYYYY(dateString) {
const [day, month, year] = dateString.split('/');
return new Date(
parseInt(year),
parseInt(month) - 1,
parseInt(day)
);
}
const diff = Math.abs(getDateFromDDMMYYYY('13/10/2018').getTime() - getDateFromDDMMYYYY('13/09/2018').getTime());
const days = Math.round(diff / (3600000 * 24));
console.log(`${ days } ${ days === 1 ? 'day' : 'days' }`);
The way you are trying to subtract dates ('13-10-2018'- '13-09-2018') is wrong. This will give an error NaN (Not a number) because '13-10-2018' for instance is a string and can't be automatically converted to a Date object. if you ask '100' - '20' this will give you 80 as javascript automatically parses a string that can be converted to integers or floats when arithmetic operators are applied but in your case, it's '13-10-2018' that can't be parsed either as an integer or float because parsing it won't give any number.
If the date is in string format then you can parse it in following way and then perform some operation, Since your date is in DD-MM-YYYY I suggest you change it either in MM-DD-YYYY or in YYYY-MM-DD, for more info about Date you can look up to the this link.
let timeDifference = Math.abs(new Date('10-13-2018') - new Date('09-13-2018'));
console.log(Math.ceil( timeDifference / (1000 * 60 * 60 * 24)));
new Date('10-13-2018') - new Date('09-13-2018') will give you 2592000000 milliseconds, since time is represented as Unix time. you can check unix time of any date by doing following.
console.log(new Date().getTime('10-13-2018'));
now the calculations behind the scene is 2592000000 / 1000*60*60*24 (that is total milliseconds in one day) = 30 days

Javascript: Get epoch date as from predefined date is using todays date instead [duplicate]

This question already has answers here:
Convert UNIX to readable date in javascript
(3 answers)
Closed 4 years ago.
JSFiddle: https://jsfiddle.net/u8w3v9fd/1/
I am trying to get the day, month and year from a date that is passed form the database in the format: DD/MM/YYYY. However I can't even seem to get the correct date to show.
Here is my code:
var time = "1522843537";
var regDateOriginal = new Date(time);
var regDate = new Date();
regDate.getMonth(regDateOriginal);
regDate.getHours(regDateOriginal);
regDate.getDate(regDateOriginal);
document.write("<p style='color: #fff'>" + regDate.getDate(regDateOriginal) + "</p>");
As you can see, this is returning:
21
Which is todays date. It should be 4
I have googled it and hacked around with various versions for the past 45 mins. I am a junior and would really appreciated a nicely commented piece of code so I can learn instead of just copying and pasting.
Thank you for your help.
From here
var time = 1522843537;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(time);
console.log(d.getDate());
Of course, you can still do all the other Date functions as needed.

how to convert particular time into UTC timestamp [duplicate]

This question already has answers here:
How do I get a timestamp in JavaScript?
(43 answers)
How to set Hours,minutes,seconds to Date which is in GMT
(3 answers)
Closed 5 years ago.
I'm having a time in this format like
var time = "22:00:00"
I need to convert this into UTC time format like 1567890764
I'm using this one to convert time into UTC.
Math.floor(new Date().getTime() / 1000) //it return current UTC timestamp
how to pass the "time" variable and get UTC timestamp for that particular time?
You can just create UTC Timestamps with the full date.
You can use the .getTime() function of the Date object. You will get the milliseconds since 1970/01/01 and then divide it with 1000 to get the seconds.
let datestring = "2017-10-21 13:22:01";
let date = new Date(datestring);
console.log(date.getTime() / 1000); // will return 1508584921
You can also take a look at Moment.js which is great for handling Date and Time in Javascript.
EDIT:
If you want todays date 22:00:00 just init new Date and set the time like this:
let date = new Date();
date.setHours(22);
date.setMinutes(0);
date.setSeconds(0);

How to compare date in javascript in this format? [duplicate]

This question already has answers here:
compare sql date to javascript date
(4 answers)
Closed 5 years ago.
How to compare today's date time with 2016-06-01T00:00:00Z format in javascript ?
I get 2016-06-01T00:00:00Z date format from backend. I want to check this with todays date, but not sure of how to check in that format.
I am extremely new to javascript.
If you search a little you can found the solution.
You have to parse your string into Js Date and compare it with today's date.
var stringDate ="2016-06-01T00:00:00Z";
var jsDate = new Date(stringDate).getTime(); //getTime() => time in ms
var today = new Date().getTime();
console.log("date is oldest than today :", jsDate < today)
Using my comment on the question, you can quickly do it in one line. #Alexis answer is a bit overkill (no offense)
var result = new Date("2016-06-01T00:00:00Z") > new Date ? "After now" : "Before now";
use the Date Object and Date#getTime which returns the number of milliseconds since the unix epoch. Pretty simple.
let
dateStr = "2016-06-01T00:00:00Z"
d1 = new Date(dateStr),
d2 = new Date(),
d1IsBeforeD2 = d2.getTime() > d1.getTime()
;
console.log(d1IsBeforeD2);

How to subtract date/time in JavaScript? [duplicate]

This question already has answers here:
How do I get the difference between two Dates in JavaScript?
(18 answers)
Closed 8 years ago.
I have a field at a grid containing date/time and I need to know the difference between that and the current date/time. What could be the best way of doing so?
The dates are stored like "2011-02-07 15:13:06".
This will give you the difference between two dates, in milliseconds
var diff = Math.abs(date1 - date2);
In your example, it'd be
var diff = Math.abs(new Date() - compareDate);
You need to make sure that compareDate is a valid Date object.
Something like this will probably work for you
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.
You can just substract two date objects.
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01"); // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.
Date.prototype.diffDays = function (date: Date): number {
var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
return (utcThis - utcOther) / 86400000;
};
Test
it('diffDays - Czech DST', function () {
// expect this to parse as local time
// with Czech calendar DST change happened 2012-03-25 02:00
var pre = new Date('2012/03/24 03:04:05');
var post = new Date('2012/03/27 03:04:05');
// regardless DST, you still wish to see 3 days
expect(pre.diffDays(post)).toEqual(-3);
});
Diff minutes or seconds is in same fashion.
Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:
subtractDates: function(date1, date2) {
return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
return moment().subtract(dateSince).milliseconds();
},
You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

Categories

Resources