2

Please help. I tried this code but I wasn't able to change it's format. I need the date to accept the format YYYY/MM/DD

<script type="text/javascript">
    function ageCount() {
        var date1 = new Date();
        var dob = document.getElementById("dob").value;
        var date2 = new Date(dob);
        var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
        //Regex to validate date format (dd/mm/yyyy)       
        if (pattern.test(dob)) {
            var y1 = date1.getFullYear();
            //getting current year            
            var y2 = date2.getFullYear();
            //getting dob year            
            var age = y1 - y2;
            //calculating age                       
            document.getElementById("ageId").value = age;
            doucment.getElementById("ageId").focus();
            return true;
        } else {
            alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
            return false;
        }

    }
</script>
Mathew P. Jones
  • 843
  • 1
  • 11
  • 20
  • Check this http://stackoverflow.com/questions/8152426/how-can-i-calculate-the-number-of-years-betwen-two-dates – malkam Jul 08 '14 at 07:07

2 Answers2

0

just take this javascript date manipulation library [closed]

I wrote a javascript date library called moment.js

https://github.com/moment/moment

It creates date wrapper objects so that it doesn't have to modify Date.prototype.

It includes parsing from strings, date objects, and unix timestamps.

It can format based on replacement patterns ("dddd, MMMM Do YYYY, h:mm:ss a") and also includes time ago ("2 days ago", 6 months ago")

Community
  • 1
  • 1
Mathew P. Jones
  • 843
  • 1
  • 11
  • 20
0

You just need to change the regex from

var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

to

var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;

And it should do.

Check Here : http://jsfiddle.net/fP875/

WARNING

But remember the regex you are using is not exactly correct. You'll need a more precise regex to check date.

Your regex will accept dates like 2014-23-56 or 9999-99-99.

I'll recommend this : https://stackoverflow.com/a/18759740/3603806 if you need accurate dates and not just formatting.

http://jsfiddle.net/EywSP/856/

http://jsfiddle.net/EywSP/854/

Community
  • 1
  • 1
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43