Javascript Subtract Set Date by Todays Date Within Array - javascript

currently I have an array that is pulling a future date, and I'm trying to do the "future date" - "todays date" within an array to get a number. The format that the future date is currently being outputted as is below.
2021-06-21T16:23:26.182Z
I was wondering how I could trim the date when it's being pulled within an array, and then subtract the future date from todays date, to give a number output.
Currently within the array the future date property is being pulled as shown below.
futureDate: machine.future.date
Would I just do the "split" function on the date to trim it down to 2021-06-21? Any help would be much appreciated, thanks!

var futuredate="2021-06-21T16:23:26.182Z";
var dif = new Date(futuredate).setHours(0,0,0,0) - new Date().setHours(0,0,0,0);
// dif is in milliseconds
// days difference = dif / 1000 / 60 / 60 / 24
// years difference = dif / 1000 / 60 / 60 / 24 / 365
To address your comment, you can map one array to another - getting the diff value along the way, like:
var arr = ["2021-06-21T16:23:26.182Z", "2021-06-22T16:23:26.182Z"];
var difarr = arr.map(futuredate => {
return (new Date(futuredate).setHours(0,0,0,0) - new Date().setHours(0,0,0,0)) / 1000 / 60 / 60 / 24 ;
})
//difarr is an array of the difference in days (in this example)

Related

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

Javascript - unexpected behavior in dates calculations

I'm a newbie and recently started to read Beginning Javascript, by McPeak and Wilton. The authors propose an exercise about dates calculation. This is the exercise
Using the Date type, calculate the date 12 months from now.
I tried to solve it with this code
//gets today's date
var today = new Date();
//this line transforms the date in milliseconds
var daysAsMilliseconds = 1000* 60 * 60 * 24 * today.getDate();
//creates a new Date object
console.log(new Date(today.setDate(365) + daysAsMilliseconds));
The result I get here is correct(August 11th 2018).
Later, I wonder if it was really necessary to create 2 variables and tried this solution:
var today = new Date();
console.log(new Date(today.setDate(365) + (1000 * 60 * 60 * 24 * today.getDate())));
Here the solution was incorrect. The console showed August 31 2018. Why?
If necessary, here you will find the repl.it with the code
You call setDate, before you call getDate , therefore getDate will always return 365. Simply swapp it:
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365))
Or its may easier to work with months directly:
today.setMonth(today.getMonth() + 12);
var intwelvemonths = today;
All you need to do is add 1 to the year:
var yearFromNow = new Date();
yearFromNow.setYear(yearFromNow.getFullYear() + 1);
Setting the date to 365 makes no sense; .setDate() is for day-of-month, so setting it to that constant moves the date a year (usually) from the last day of the previous month. And you don't need to do any other math outside of the date API; just increment the year, and you're done.
You're calling today.setDate(365) before you're adding the results of today.getDate(): today.getDate() will give the date that you set, not today's date.
Changing the order of operations will do the trick:
var today = new Date();
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365));
I recommend you to use a package as moment.js because it manage a lot of date formats, and it has very good implementations for date managing.
Using moment js for add.
moment().add(Number, String);
Example
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours(); // 5
m.add(1, 'days').hours(); // 5
For more docs see moment().add() docs

Javascript: Calculate time difference between 2 days with conversion to UTC

I have a start and end dates, I need to convert them to UTC and calculate how many days are in between (including).
So for example:
(01/08/15 10:00 GMT+3) - (04/08/15 10:00 GMT+3) will return 4
(01/08/15 00:00 GMT+3) - (04/08/15 10:00 GMT+3) will return 5
The following code works for those dates like the first case, but not for the second (where after the conversion there is an additional day):
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
var totalDays = Math.floor((endDateInUTC - startDateInUTC) / (1000 * 60 * 60 * 24)) + 1;
I tried changing the Math.floor to Math.round but that just adds me a day in some scenarios.
What am I doing wrong?
function calculate(start, end)
{
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
return Math.floor(millisecondsToDays = (Date.parse(endDateInUTC) - Date.parse(startDateInUTC)) / 1000 / 3600 / 24);
}
console.log(calculate(new Date("2015/08/01 10:00:00"), new Date("2015/08/04 10:00:00")));
console.log(calculate(new Date("2015/08/01 00:00:00"), new Date("2015/08/04 10:00:00")));
//the answer in both cases will be 3
Use Date.parse here. It will convert the dates into timeStamps. you can subtract these and then calculate the amount back to days. Use Math.floor to round down, since 6.25 is 6 days and 6 hours.
timeStamps are the amount of milliseconds that have passed since 1970/01/01 00:00:00. That date is always UTC. When you have two timestamps you can calculate the difference between them. Date.parse() returns the timestamp on a valid date. new Date(timestamp) will return the date based upon the timestamp.
To get date barriers you can do an extra calculation:
(start time + 24 * days + end time) / 24
Round this figure down and you get the day barriers.
Example:
21 + 24 * 3 + 7 = 100
103 / 24 = 4.1666666.....
Math.floor(4.166666) = 4;
I ended up gathering a pretty simple solution combining some bits of Mouser's answer (Thanks!)
function calcStreamDaysInUTC(start, end) {
try {
// Translate to UTC
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
// Reset everything but the date
startDateInUTC.setHours(0);
startDateInUTC.setMinutes(0);
startDateInUTC.setSeconds(0);
endDateInUTC.setHours(0);
endDateInUTC.setMinutes(0);
endDateInUTC.setSeconds(0);
var totalDays = (endDateInUTC - startDateInUTC) / (1000 * 60 * 60 * 24) + 1;
return totalDays;
} catch (e) {
return -1;
}
}

Check Date range in Javascript and angular js

I have to check the given date which is dd/MM/yyyy format that it should fall within 90 days range in java script?
Take the difference between two dates and divide it by the number of milliseconds in a day.
var difference = (new Date().getTime() - startDate.getTime())/(1000*60*60*24.0)
Find out if the difference between the two dates is more than 90 days
alert Math.abs(difference) < 90 ? "Valid Time" : "Invalid Date Range"
Full working example:
var startDate = new Date('2015-01-01 00:00:00');
var difference = (new Date().getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24.0);
alert(Math.abs(difference) < 90 ? "Valid Time" : "Invalid Date Range");

JavaScript: check if date A is at most 3 times earlier/late than date B

I have to write a JavaScript function that checks if two dates (formatted dd/MM/yyyy) make a time interval of at most 3 months.
I can retrieve the two values from two textboxes (no need to check formatting, I have been given a calendar control that automatically formats the date correctly).
I have almost no experience with JavaScript. Can you help me?
Examples:
15/2/2011, 13/2/2011 -> return true
6/1/2011, 5/10/2010 -> return false
I already check that date A is later than date B (the calendar does it for me)
No need for a ton of code:
function days_between(date1, date2) {
return Math.round(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24)) > 90;
}
date1 and date2 are Date objects e.g.
var date1 = new Date('mm/dd/yyyy');
You can find difference between two dates and return value accordingly.
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// check converting back to days and return
return (Math.round(difference_ms/ONE_DAY) >90);
}
If you are unable to check or parse date correctly then you should use
var x=txtDate1.split("/"); //Here txtDate1 and txtDate2 are values from your textbox
var y=txtDate2.split("/");
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])

Categories

Resources