Search code examples
javascriptdatetostringdatejs

Javascript llegal radix 0 when converting Date object into time string (dd.mm.yyyy)


I am trying to convert a DateObject into readable format (dd.MM.yyyy) with DateJS. I get an error:"llegal radix 0" when trying to convert it into a string.

Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pick the date</title>
<link type="text/css" href="css/smoothness/jquery-ui-1.8.14.custom.css" rel="Stylesheet" /> 
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.14.custom.min.js"></script>
<script src="inc/date-fi-FI.js" type="text/javascript"></script>
<script type="text/javascript">
    function parseDate() {
        var date = $('#date').val();
        var parsedDate = Date.parse(date);
        alert('Parsed date: '+parsedDate);
    }
    function jämförMedIdag (datum) {
        if (datum == null || datum == "") {
            alert('Inget datum!');
            return;
        }
        /*resultat = Date.compare(Datum1,Datum2);
        alert(resultat); */
        var datum = Date.parse(datum);
        var dagar = datum.getDate();
        var månader = datum.getMonth();
        var år = datum.getYear();
        var nyttDatum = new Date();
        nyttDatum.setFullYear(år,månader,dagar);
        var idag = new Date();

        if(nyttDatum>idag) {
            var svar = nyttDatum - idag;
            svar = svar.toString("dd.MM.yyyy");
            alert(svar);
            return(svar);
        } else {
            var svar = idag - nyttDatum;
            svar = svar.toString("dd.MM.yyyy");
            alert(svar);
            return(svar);
        }
    }
</script>
</head>

<body>
<form>
    <input type="text" name="date" id="date" value ="13.03.1990" />
    <input type="button" onclick="jämförMedIdag(document.getElementById('date').value)" value="Compare the date" />
</form>
</body>
</html>

See it in action: http://resk.latvalashop.com/date.php


Solution

  • Subtracting Dates does not return a new Date, but a number. To convert it to a Date, try this:

    new Date(endDate - startDate).toString("dd.MM.yyyy");
    

    However, if you are trying to see the difference (like 1 month), this won't help, because it will start at 1 January 1970.

    To be precise, the number you get is the amount of milliseconds since 1 January 1970. So the difference expressed as a number is the difference in seconds. A week is 7 * 24 * 60 * 60 * 1000 milliseconds, so use something along the lines of:

    if(endDate - startDate > 7 * 24 * 60 * 60 * 1000) {
        alert("Difference is more than a week");
    }