Javascript - Find out if date is between two dates, ignoring year - javascript

I need to find out if my date is between two dates (for checking birthday whether its between +/- 10 days of current date) without taking care of year (because for birthday we don't need year).
I have tried the following but its typical match and will not ignore year. If i ll compare only date and month then overlap on month end makes problems.
(moment(new Date()).isBetween(moment(date).add(10, 'days'), moment(date).subtract(10, 'days')));

Here is the solution that i was end up with.
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = Math.abs(birthday - new Date) < 10*24*60*60*1000;
And if you are using moment then:
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = moment(new Date()).isBetween(moment(birthDate).subtract(10, 'days'), moment(birthDate).add(10, 'days'));

if(Math.abs(birthday - new Date) < 10/*d*/ * 24/*h*/ * 60/*min*/ * 60/*secs*/ * 1000/*ms*/)
alert("somewhat in the range");
You can just work with dates as if they were milliseconds. Just get the difference by subtracting them, then check if its smaller than 10 days in milliseconds.

You can use momentjs with methods subtract and add to find any date you want.
Example:
moment().add(7, 'days'); // next 7 days
moment().subtract(7, 'days'); // 7 days ago

This may be help you.
var birthDate = new Date("05/16/1993");
var day = birthDate.getDate();
var month = birthDate.getMonth();
var currentDate = new Date();
var tempDate = new Date();
var oneDay = 1000 * 60 * 60 * 24
var dayDifference = 10 // you can set here difference
tempDate = new Date(tempDate.setMonth(month,day))
var timeDiff = tempDate.getTime() - currentDate.getTime();
timeDiff = Math.round(timeDiff / oneDay)
if(-dayDifference <= timeDiff && timeDiff <=dayDifference){
alert("matched")
}
else{
alert("not matched")
}

Related

How to get date after n number of days in a date range?

Suppose I have a start date which is 3/Sep/2019 and end date 10/Sep/2019.
I want to get the date after 4 days from the starting date. So if my starting date is 3/sep/2019 I want to get 7/Sep/2019 but not 12/sep/2019 since this date comes after my end date.
How can I achieve this?
So far I'm getting dates after n number of dates like this:
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
date = new Date(res);
alert(date);
var days = 7;
var date = new Date();
var res = date.setDate(date.getDate() + days);
This is how you get a day 7 days after the date you already have. It wraps to the next month when appropriate as well.
Try the function I wrote below:
function getFutureDate(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
return date
}
const fourDays = getFutureDate(4)
console.log(fourDays)

how to use Date.toLocaleString() with changing timezones

I converted my start and end date to .ToLocalString and now I am trying to use math.abs to calculate difference between start and end date in numbers but its Value is NaN. Any suggestions on how to apply Math.abs in this situation are appreciated.
Note: Start date will be in EDT and EndDate will be in EST. But they
might or might not be in same timezone.
var startDate1 = new Date(homeCtrl.createStartDate);
var startDate = startDate1.toLocaleString();
var endDate1 = new Date(homeCtrl.createEndDate);
var endDate = endDate1.toLocaleString();
var timeDiff = Math.abs(endDate - startDate); //This is NaN
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); // Here it will add 1 extra day. Example: 11/06/2018 - 11/04/2018 = 2 days but this gives 3days are timezone change on 11/04/2018 and thats the issue.
I would use the unix timestamp.
var startDate1 = new Date(homeCtrl.createStartDate);
var startDate = startDate1.getTime();
var endDate1 = new Date(homeCtrl.createEndDate);
var endDate = endDate1.getTime();
var timeDiff = Math.abs(endDate - startDate);

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

Decrement the date by one day using javascript for loop?

$(document).ready(function() {
var date = new Date();
var data_new = [];var url ='http://www.domain.com /kjdshlka/api.php?date=2014-07-15';
$.getJSON(url,function(result) {
var elt = [date,result.requests];data_new.push(elt);console.log(data_new);
});
});
I am struggling to decrement the date by one day using javascript for loop.Here is my code,from the url im getting some requests.like if i decrease the date by one day other requests will come .Now i need this process for 7days using javascript for loop.Can anybody please tel me how to do ?
var date = new Date(); // Date you want, here I got the current date and time
date.setDate(date.getDate()-1);
getDate() will give you the date, then reduce it by 1 and using setDate() you can replace date again.
var today = new Date();
var yesterday = new Date(today.getTime() - (24 * 60 * 60 * 1000)); //(hours * minutes * seconds * milliseconds)
console.log(yesterday);
var now = new Date();
console.log(now);
var yesterday = new Date(now - 86400000);
console.log(yesterday);
/* In a Decrement Loop*/
for(var i=100;i>0;i--){
console.log(new Date(now - i*86400000));
}

Comparing two dates in JavaScript

I am currently trying to compare the launch_date with today's date. Let's say if the launch_date is within 3 years from today's date, it should perform something but I only managed to come out with some portion of the code:
var today = new Date();
var launch_date = 2011/10/17 00:00:00 UTC;
//if today's date minus launch_date is within 3 years, then do something.
Any guides? Thanks in advance.
To explicitly check for the three year range
var ld = new Date('2011/10/17 00:00:00 UTC')
if(today.getFullYear() - ld.getFullYear() < 3) {
//do something
}
This will fail on an invalid date string and possibly some other edge cases.
If you'll be doing a lot of date calculations I highly recommend Moment: http://momentjs.com/
you could always calculate the timespan in days and use that.
var getDays = function(startDate, endDate){
var ONE_DAY = 1000 * 60 * 60 * 24;
var difference = endDate.getTime() - startDate.getTime();
return Math.round(difference / ONE_DAY);
}
See this JsFiddle: http://jsfiddle.net/bj4Dq/1/
Try-
var today = new Date();
var launch_date = new Date("2011/10/17 00:00:00 UTC");
var diff = today.getYear() - launch_date.getYear();
if(diff <=3 )
alert("yes");
else
alert("no");
jsFiddle
you can create a Date object and invoke getTime() method (returns numer of milliseconds since 1970-01-01). Use one of this rows:
var yourDate = new Date(dateString) // format yyyy-mm-dd hh:mm:ss
var yourDate = new Date(year, month, day, hours, minutes, seconds, milliseconds)
After in the if statement use this condition:
var edgeDate = // new Date(dateString);
if ( (today.getTime () - yourDate.getTime ()) >= edgeDate.getTime() ){
// do something
}
Regards,
Kevin

Categories

Resources