Compare dates in JavaScript [duplicate] - javascript

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I want to compare following date in Javascript. Please help me.
$fromdate=2014-12-08
$todate=2014-12-12
I want to compare both the dates with current date. Please tell me how to code in if loop.

You can construct a Date object and then compare them however you want:
// Date months are 0-based
var fromDate = new Date(2014, 11, 8);
var toDate = new Date(); // Today
// Then you can calculate the difference between them
var seconds = (toDate.getTime() - fromDate.getTime())/1000;
var minutes = ~~ (seconds/60);
var hours = ~~ (minutes/60);
var days = ~~ (hours/24);
Then you can use the diff to calculate how many seconds, hours, days etc. there are between them.

A date can be represented numerically as a count of milliseconds from an epoch (01 January, 1970 UTC in javascript).
Create a Date object for today, start and end dates.
Get the numerical representation of these dates by using the method getTime
Now compare today's representation with the start and end representations.
IF the numerical value of today is greater than or equal to the start numerical value, AND
is less than or equal to the end numerical value, THEN
today falls within the supplied range, ELSE
it does not.

Related

Compute an age with d3-time

I'm trying to compute the age of an individual using D3.js.
I have the following code :
d3.timeYear.count(Birth_date, Current_date);
Birth_date being an individual's birth date (a Date object), and Current_date being, well, the date at which I'd like to compute the individual's age. To be able to answer "if you were born on May 5th, 1975, how old were you on May 3rd, 1976".
d3.timeYear.count() seems to floor the dates to the beginning of the year, so that in my example my code will return 1 on January 1st, 1976, even though the guy was 5 months away from his first birthday.
I could count the number of days instead of years, but I might get wrong results locally depending on the number of days in the year.
The following is based on the JavaScript Date object and should do the job:
function age(by,bm,bd){
const D=new Date(), y=D.getFullYear(),
md=D.getMonth()-bm, dd=D.getDate()-bd;
return y-by-(md>0||!md&&dd>=0?0:1);
}
console.log(age(1992,8,26))
Basically I return the difference between the full year of today and the birthday. But I also check, whether the current month is either greater than the birthday-month or (||) if the month-difference is zero (!md is true) and (&&) the day-difference dd is greater than zero. If that is the case I subtract 0 otherwise 1 from the year-difference.
And please be aware that my age() function expects the month to be entered in JavaScript notation. This means that 8 in the above example refers to the month of September.
The answer by Carsten Massman has inspired me to make this function, which solves my problem :
function age(birthdate, currentdate){
const bDay = birthdate.getDate(); // Get the birthdate's day.
const bMonth = birthdate.getMonth(); // Get the birthdate's month.
const currYear = currentdate.getFullYear(); // Get the current date's year.
const currBirthday = new Date(currYear + "/" + (bMonth + 1) + "/" + bDay); // Contruct the date of the birthday in the current year
const daysToBirthday = d3.timeDay.count( d3.timeYear.floor(currBirthday), currBirthday); // Count the # of days since Jan. 1st this year
// Offset the current date in the past by the number of days computed above.
const offsetCurrent = d3.timeDay.offset(currentdate, -daysToBirthday);
// Compute the number of years between the two dates (floored to the beginning of their respective year).
return d3.timeYear.count(birthdate, offsetCurrent);
}
This computes the age for any birth date, and at any point in time afterwards, using mostly d3-time and a little bit of vanilla javascript's Date methods.

Convert 7:27:02 AM UTC time to local time-zone in Javascript. I'm getting 7:27:02 AM from the server [duplicate]

This question already has answers here:
Convert UTC date time to local date time
(38 answers)
Closed 3 years ago.
I'm trying to convert UTC time 7:27:02 AM to the local timezone. Converting just HH:MM:SS AM. Currently, I'm in GMT05:30.
Here, first, on lines 1 and 2, you get the current date and the current time zone offset, which is the difference in minutes (which you have to convert to milliseconds) between the UTC time and the local time. Then you'll get the timestamp from the date that you want, which is 7:27:02 AM (for PM you'll have to sum 12 hours), and subtract the offset. Then you just have to convert the timestamp to Date Object.
var date = new Date();
var offset=new Date().getTimezoneOffset()*60000;
var date2 = new Date(date.getFullYear(),date.getMonth(),date.getDay(),7,27,2).getTime()-offset
date2=new Date(date2)
console.log(date2)

Add 30 days to the time now [duplicate]

This question already has answers here:
Add 30 days to date (mm/dd/yy)
(4 answers)
Closed 6 years ago.
I'm using Date.now() to get the current date.
I then need to add 30 days to this.
How can I do this?
Would I just work out how many seconds in 30 days, then add this on?
var d = new Date();
console.log(d);
d.setDate(d.getDate() + 30);
console.log(d);
Date.prototype.getDate returns current date day number.
Date.prototype.setDate set date number of given date to value passed to it.
If value exceeds normal date range of month date extra value will handle needed math and change month (or year if necessary) and shows correct result.
var date = new Date;
date.setDate(date.getDate() + 30);
console.log(new Date, date);

Get number of days prior to the specified date Javascript [duplicate]

This question already has answers here:
Date difference in Javascript (ignoring time of day)
(15 answers)
How to subtract days from a plain Date?
(36 answers)
Closed 6 years ago.
I'm reading the value of the date input and need to workout if there is 42 days or more between the specified date and today's date. This is what I've tried so far:
var sdate = new Date($("#holiday-editor input[name=StartDate]").val()); //This is returing date in the string format
var priorDate = new Date().setDate(sdate - 42).toString(); // This is returning some abstract int value
var dateNow = new Date().getDate().toString(); // this is returning 5 even though I'd like to get today's date in the string format
if (dateNow > priorDate) {
$("#HolidayBookedLate").show();
}
If you manipulate dates a lot in your app I'd suggest to use moment.js. It's only 15kb but it has lots of useful features to work with dates.
In your case you can use diff function to get amount of days between two dates.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Sorting based on upcoming birthday

I'm building a simple birthday reminder app where I get the names and birthdays in JSON and I need to display the names sorted based on whose birthday is coming next.
My logical thought would be to get the current day and month subtract that from the birthday and then do some kind of sort. But then how would do I handle -ve results or situations like when we are in Dec etc. I was guessing there might have been an simpler solution, but I'm quite clueless.
Here is a plunkr with the base working code: http://plnkr.co/edit/AkP6FRRG917TDdTtfWM7?p=preview
As others suggested, convert the string to a unix timestamp or date.
Here's an updated Plunker.
The controller adds a fromNow variable to the data:
$scope.friends.forEach(function(data){
var day = data.birthday.split("/")
var currentYear = new Date().getFullYear();
var birthdayDate = new Date(currentYear, day[0] - 1, day[1])
var now = new Date().valueOf();
if (birthdayDate.valueOf() < now){
birthdayDate.setFullYear(currentYear+1)
}
data.fromNow = birthdayDate.valueOf() - now;
})
Get the individual date/month parts (so we get a list like ["02","14","1985"])
Create a date object based on the current year, the month day[0] and the day day[1]. (Note we subtract 1 from the months because months are 0-based in in Javascript).
Get a numeric value for the current date/time
If the birthday is in the past add one year
Assign the number of milliseconds between now and the birthday to fromNow
You'd need to modify it so that if someone's birthday is today it doesn't add a year, thus placing it last in the list.
Also note I've added quotes to the orderBy parameter:
<tr ng-repeat="friend in friends| orderBy:'fromNow' ">
I would go about this by converting the dates to unix timestamps (int values) and doing a simple sort on them.
Convert date to timestamp using javascript Date.parse()
Convert the current date and birthdate to UNIX time and compare them based on the differences between these two values
birthdates = [new Date(1988,01,27), new Date(2013,01,01)];
birthdates.sort(function(firstDate,secondDate){
//calculate the difference between first date and current date
firstDifference = new Date() - firstDate;
//calculate difference between second date and current date.
secondDifference = new Date() - secondDate;
//return the smallest value.
return firstDifference - secondDifference;
});
//display the sorted array.
alert(birthdates);

Categories

Resources