How to subtract a date via Datepicker? - javascript

I have an add date and I need to know how many days ago this record was added, so today - adddate. This is in mm/dd/yyyy format (10/16/2014) and I wanted to know if there is an easy way to get the difference without adding a new plugin. Thanks!
var today = $.datepicker.formatDate('mm/dd/yy', new Date());
var adddate = $('#adddate').val();
alert(today - adddate);

Assuming both values are inside inputs, this works.
var d1 = $('#adddate').datepicker('getDate');
var d2 = $('#today').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
alert(diff)

Related

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

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")
}

how to find difference in days between day and month irrespective of years

I want to know the difference between to two dates irrespective of year..
For Example : format date/month/year
For example difference of today date to some date lets take 01/06
The expected answer for this will be around 185 days..
I tried below example..Let me know whats wrong with this
var a = moment('06/01','M/D');
console.log(a);
var b = moment();
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
I dont want to use momet.js atmost. If it can be done with javascript its so good for me.
A nice trick could be to set the year to always the same.
var a = moment('2015/06/01','Y/M/D');
console.log(a);
var b = moment().set('year', 2015);
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
The problem about your question in general is how to deal with leap years; how the script should know the difference between 2/20 and 3/1 ? You have to consider how to solve this.
Barth Zaleweski is 100% on track with that. If you want to use straight javascript:
var today = new Date();
var otherDate = new Date(today);
otherDate.setMonth(5); // Set the month (on scale from 0 to 11)
otherDate.setDate(1); // set day
var seconds = (otherDate.getTime() - today.getTime()) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
console.log(days);
There are methods for setting hour/minute/second as well, but if you don't do anything they'll be the same as the start, and you can obviously call those same methods on your start time if you don't want to use today.
Can try using this:
var str1 = '06/01', str2 = '02/28', d1, d2, diff;
function setDate(str, date) {
var date = new Date(),
dateParts = str.split('/'),
monthIndex = parseInt(dateParts[0], 10) - 1,
day = parseInt(dateParts[1], 10);
date.setMonth(monthIndex);
date.setDate(day);
return date
}
d1 = setDate(str1);
d2 = setDate(str2);
diff = Math.round(Math.abs((d1 - d2) / (24 * 60 * 60 * 1000)))
console.log(diff) // returns 93
The rounding is due to differences in daylight savings (or other locale time shifts within the year) that can cause decimal values returned.
It is probably better to use UTC for this
If current year is leap year and dates span end of February then Feb 29 would also be counted
DEMO
If it is this year then I am getting a difference of 147 using a library that I have been working on (AstroDate) which doesn't rely on javascript's Date object, it's all done with pure math.
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2015","6","1").jd() - new AstroDate("2015","1","5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>
If it was next year, which is a leap year then I am getting 148
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2016", "6", "1").jd() - new AstroDate("2016", "1", "5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>

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

Efficiently create Javascript Date from Today -1 Years (time) in Unix time

I currently am using this to create a Unix time stamp for time (now) -1 year's time.
Can someone please share a better and more efficient way to do this?
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var lastYear = parseInt(currentYear) - 1;
var lastYearDateObj = new Date(lastYear, currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes());
var lastYearTime = lastYearDateObj.getTime() / 1000;
Thank you!
I don't understand what your division by 1000 is about. You can add it to the end if you like:
var date = new Date();
date.setFullYear(date.getFullYear() - 1);
// date.getTime() / 1000 // if you want.

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