Calculate Days Left To A Specific Date With Javascript
I was trying to calculate the days left until a specific date. I know that there are a million different approaches and tutorials about it, but I wanted to write a code by myself.
Solution 1:
When you parse num
to set date[x]
, you need to reset num
to ''
.
...
else {
date[x] = parseInt(num, 10);
x++;
num = '';
}
You might consider using String.split()
to separate your input at the periods.
Solution 2:
My Solution is:
functionisNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var daysLeft = function(input) {
var num = '';
var date = [];
var x = 0;
for (i = 0; i < input.length; i++) {
if (!isNaN(input.charAt(i)) && isNumeric(input.charAt(i))) {
num += input.charAt(i);
}
else {
date[x] = parseInt(num, 10);
x++;
num = '';
}
}
date[x] = parseInt(num, 10);
var inputDate = newDate(date[2], date[1], date[0]);
var today = newDate();
var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
returnMath.ceil(timeDiff / (1000*3600*24));
};
But a better would be:
functionparseDate(input) {
var parts = input.split('-');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])returnnewDate(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}
var daysLeft = function(input) {
var inputDate = parseDate(input);
var today = newDate();
var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
returnMath.ceil(timeDiff / (1000*3600*24));
};
Solution 3:
You should use something like this:
var daysLeft = function(input) {
var num = '';
var date = [];
var x = 0;
for (i = 0; i < input.length; i++) {
if (!isNaN(input.charAt(i))) {
num += input.charAt(i);
}
else {
date[x] = parseInt(num, 10);
x++;
num='';
}
}
date[x] = parseInt(num, 10);
var inputDate = newDate(date[2], date[1], date[0]);
var today = newDate();
var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
returnMath.ceil(timeDiff / (1000*3600*24));
};
daysLeft("11.12.2014");
Post a Comment for "Calculate Days Left To A Specific Date With Javascript"