samedi 10 janvier 2015

Data Calculator wrong sometimes


Vote count:

0




I am working on an open source application and have it running, just ironing out some of the kinks, but am a touch stuck. There is a place where the data is calculated onkeyup and displayed.


The Input and display:



<input type="date" class="input-small" name="dob" id="dob"
onkeyup="showAge();" oninput="showAge();" required
pattern="^[12]\d{3}-(0?[1-9]|1[0-2])-([012]?[0-9]|3[01])$"
data-validation-pattern-message="Must be a valid ISO8601 date."
placeholder=<?php echo _("YYYY-MM-DD"); ?>
value="<?php echo $edata["dob"]; ?>">
<span class="help-inline" id="age">Age: ?</span>


The Script:



function showAge(ind) {

document.getElementById('age').innerHTML = "Age: "+
getAge($('#dob').attr('value'));

}

function getAge(a) {
a = new Date(Date.parse(a.replace(/-/g, "/")));
var b = new Date,
years = b.getYear () - a.getYear(),
months = b.getMonth() - a.getMonth(),
days = b.getDate () - a.getDate();
if (b <= a) return "Invalid DOB."
months < 0 && (years --, months + 12);
days < 0 && (months--, days += 31);
months < 0 && (years --, months = 11);

a = [], b = function(b, c) {
b > 0 && a.push(b + c + (b > 1 ? "s" : "")) }
b(years , " year" );
b(months, " month");
b(days , " day" );
a.length > 1 && (a[a.length - 1] = "and " + a[a.length - 1]);
return(!a.length ? "0 days" : "" ) +
a.join(a.length > 2 ? ", " : " ") + " old."
}


For instance, today is 1/10/2015. If I enter a date of 1/10/2014 it displays Age: 1 Year


If I enter 11/01/2014, it displays 11 Months Old which is wrong, it should be displaying 2 Months.


I have a feeling I am missing something very easy, just don't see it. Help?



asked 42 secs ago







Data Calculator wrong sometimes

Aucun commentaire:

Enregistrer un commentaire