date time in javascript [duplicate] - javascript

This question already has answers here:
How to calculate the number of days between two dates? [duplicate]
(7 answers)
Closed 10 months ago.
I have a code script to calculate the number of days between today and an expected day:
let date1 = new Date(); //today
let date = new Date("04/19/2022") //expected day
let differenceInTime = date1.getTime() - date.getTime(); //difference by milliseconds
let differenceInDay = (differenceInTime - differenceInTime%(1000 * 3600 * 24))/(1000 * 3600 * 24); // JS does not supports dividing by whole so I implement this to get the number of days
The result is true for every cases, except that when I choose the day after today (tomorrow) as expected day, the result also is 0. Is there something not exact in my code?

the problem with your code is that on line 4 you kinda fix the differenceInTime to 0 decimals and difference between the expected day and today is less than 1 in days, so It'll be truncated.
You can do it easier this way. using Math methods or num.toFixed()
your code will be shorter and cleaner.
you don't even need date.getTime() cause date will automatically
convert to ms when you do mathematical operations on it.
let date1 = new Date(); //today
let date = new Date("04/20/2022"); //expected day
let differenceInMS = date1 - date; //difference in ms
let differenceInDay = (differenceInMS / 8.64e7).toFixed(1); // 8.64e+7 : a day in ms
console.log(differenceInDay);

Convert to Millisecond and then perform same logic

Related

Getting incorrect month difference between 2 dates

I have 2 dates like below :
Todays date = 2021-10-13 11:03:57.560
Old date = 2016-08-07 11:03:57.560
I want month difference from todays date Month - Old date Month = 10 - 8 = 2
Code:
console.log(moment().diff($scope.creationTime, 'months')); // returns 62
Expected: Current month - Old date month
Can anyone please help me with this?
Right now you get 62 because the two dates are 5 years and 2 months apart:
5 * 12 + 2 = 62
An easy way to drop the year difference is to use the remainder operator and do monthDifference % 12 which will give you only the number of months, regardless of the years:
function monthDiff(date1, date2) {
const monthDifference = moment(date1).diff(moment(date2), 'months');
return monthDifference % 12;
}
console.log(monthDiff("2021-10-13 11:03:57.560", "2016-08-07 11:03:57.560"));
console.log(monthDiff("2021-10-07 11:03:57.560", "2016-08-13 11:03:57.560"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Use month() from moment.js to get the months and simple math after that:
const today = moment();
const someday = moment('2011-01-01 00:00Z');
console.log(today.month())
console.log(someday.month())
console.log(Math.abs(today.month()-someday.month()))
You dont need moment to do that you use Date as well
new Date().getMonth - to get your current month
new Date('2016-08-07 11:03:57.560').getMonth() - to get the month of your old date
console.log(new Date().getMonth() - new Date('2016-08-07 11:03:57.560').getMonth())

How to get the number of days between two different date formats in react js? [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 1 year ago.
I have a date in the database (firebase realtime database) that I'm fetching and I want to calculate the number of days between the database date and today's date.
I've seen the following answers on stackoverflow.
How do I get the number of days between two dates in JavaScript?
How to calculate the number of days between two dates? [duplicate]
How to get the number of days between two dates?
However, not a single answer helps me because I have different date formats. For instance this is the date format I'm storing in the database:
var date = (new Date()).toDateString().split(' ').slice(1).join(' ');
console.log(date);
and for today's date, it doesn't matter because I only want to get the number of days between these two dates.
I tried multiple ways to convert the date format of that in the database and then using the approach in the mentioned stackoverflow's answer to calculate the number of days but that didn't work.
This should work:
let date = (new Date("Jul 05 2021")).getTime();
let today = (new Date()).getTime();
let msDay = 24 * 60 * 60 * 1000; // milliseconds per day
let days = Math.floor((today - date) / msDay);
Note: "Jul 05 2021" gets constructed in local time zone.
You can use momentjs for this:
const a = moment(date_one);
const b = moment();
const no_of_days = a.diff(b, 'days')
Try the below:
function datediff (date_one, date_two) {
let day_secs = 24 * 60 * 60 * 1000;
return Math.ceil((date_two - date_one) / day_secs);
}
Or
const dateDiff= (date, cDate) => Math.ceil(Math.abs(date - cDate) / (1000 * 60 * 60 * 24));
dateDiff(new Date('2021-07-05'), new Date('2020-07-05'));

calculate between expiration date and the current date then return the remaining days in javascript [duplicate]

This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Good day, I want to calculate the remaining days between the expiration date and the current date but it seems that the return is not what I expected.
function expiryDate(date_string) {
var date = date_string.split("/");
var year = parseInt(date[2]);
var day = parseInt(date[1]);
var month = parseInt(date[0]);
var expiration = new Date(month,day,year);
var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth()+1;
var curr_year = d.getFullYear();
var current_date = new Date(curr_month, curr_day, curr_year);
return (expiration - current_date) / (1000*60*60*24);
}
the code above will return the correct remaining days if the dates are the same for example.. the current date string was 05/01/2018 and the expiration is also the same and it will return 0, but when i move the expiration date to 1 day like 05/02/2018 the return is 28 days which is not correct.
How can I fix this problem?
As others have pointed out, months are zero indexed. Also, your method of zeroing the hours won't always work as expected because of daylight saving in some places. But rounding the result will remove DST effects.
There is no need for a library, your parse function and calculation can be be hugely simplified, you could easily remove another line from the following:
/* #param {string} date_string - date in m/d/y format
** #returns {number} days between today and expiry
*/
function expiryDays(date_string) {
var b = date_string.split(/\D/);
var expiry = new Date(b[2],--b[0],b[1]);
return Math.round((expiry - new Date().setHours(0,0,0,0)) / 8.64e7);
}
console.log(expiryDays('8/23/2018'));
// Or if you like obfuscated code
var expires = s=>Math.round((new Date(...(s.split(/\D/).reduce((a,v,i) => {a[(i+1)%3] = (i==0? v-1 : v);return a},[]))) - new Date().setHours(0,0,0,0))/8.64e7);
console.log(expires('8/23/2018'));
The Date object uses a zero-based month where January is 0, February is 1, etc. You seem to have tried in one place to compensate for that, but in the wrong way.
You need to fix this line like this:
var month = parseInt(date[0]) - 1;
And this line like this:
var curr_month = d.getMonth(); // No +1
Of course, using Moment.js, as suggested, is also a good idea, but I thought you might want to know how to get your own code working.
You can difference between two dates using momentjs's diff() function
Below is working code:
function expiryDate(date_string) {
var expiration = moment(date_string).format("YYYY-MM-DD");
var current_date = moment().format("YYYY-MM-DD");
var days = moment(expiration).diff(current_date, 'days');
return days;
}
alert("Days remaining = " + expiryDate("2018-05-05"));
console.log("Days remaining = " + expiryDate("2018-05-05"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
initially working with times is a lot of work sometimes, and often you will invest a lot of time, maybe the moment.js library may be a solution for you depending on the need, specifically the isBetween
follow the link below.
moment.js
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')

How to get current day count of the quarter [duplicate]

I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.
I should get result as 6 but I am getting 5.
function SetDays(invoker) {
var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();
var oneDay=1000 * 60 * 60 * 24;
var difference_ms = Math.abs(end.getTime() - start.getTime())
var diffValue = Math.round(difference_ms / oneDay);
}
Can anyone tell me how I can get exact difference?
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by #kotpal in the comments).
Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.
Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);
This works for me:
const from = '2019-01-01';
const to = '2019-01-08';
Math.abs(
moment(from, 'YYYY-MM-DD')
.startOf('day')
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
) + 1
);
I made a quick re-usable function in ES6 using Moment.js.
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {
const getDateAsArray = (date) => {
return moment(date.split(/\D+/), date_format);
}
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;
}
console.log(getDaysDiff('2019-10-01', '2019-10-30'));
console.log(getDaysDiff('2019/10/01', '2019/10/30'));
console.log(getDaysDiff('2019.10-01', '2019.10 30'));
console.log(getDaysDiff('2019 10 01', '2019 10 30'));
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));
console.log(getDaysDiff('10-01-2019', '10-30-2019'));
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
// today
const date = new Date();
// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();
// Difference in Days
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

Difference between 2 Dates using jquery? calcualate Number of holidays within the period of time [duplicate]

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
Need differentiation of 2 Date objects..
Need to calculate cost based on total days of working or Total hours of working betn the date1 and date2
also need to calcualate Number of holidays within the period of time !
$(document).ready(function () {
$('#CostMaster_labour_deallocationdate').change(function(){
var date1 = $('#CostMaster_labour_deallocationdate1').val();
var date2 = $('#CostMaster_labour_deallocationdate').val();
});
});
Take a look at momentjs -
var a = moment([2007, 0, 29]); // you can pass date object
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Docs --> http://momentjs.com/docs/#/displaying/difference/
Use following Javascript Function::
function CheckDateDifference() {
var date1 = $('#CostMaster_labour_deallocationdate1').val();
var date2 = $('#CostMaster_labour_deallocationdate').val();
var diff = Math.round((date1 - date2 ) / 1000 / 60 / 60 / 24);
return diff;
};
1.Try using datejs framework to easily do all your date time calculations.
2.Else try this
function DateDiff(var /*Date*/ date1, var /*Date*/ date2) {
return date1.getTime() - date2.getTime();
}
This will return the number of milliseconds difference between the two dates. Converting it to seconds, minutes, hours etc. shouldn't be too difficult.

Categories

Resources