-4

I am using pikaday's datepicker. It gives me output "Fri Sep 20 2013". How can I convert this date into yyyy-mm-dd format and I also would want following date of this selected date and set that one to another element. I tried this code

function formattedDate() {

    var fromdate = new Date(document.getElementById('datepicker').value);
        var dd = fromdate.getDate();
        var mm = fromdate.getMonth()+1; //January is 0!
        var yyyy = fromdate.getFullYear();
        if(dd < 10)
        {
            dd = '0'+ dd;
        }
        if(mm < 10)
        {
            mm = '0' + mm;
        }
        var fromdate1 = dd+'/'+mm+'/'+yyyy;
        fromdate.setDate(fromdate.getDate() + 2);
        document.getElementById('datepicker').value = fromdate1;
        var newdate = fromdate;
        document.getElementById('datepicker1').value = newdate;
//alert(newdate1);

}

But it doesn't work.

Miki
  • 40,887
  • 13
  • 123
  • 202
user2809860
  • 15
  • 1
  • 1
  • 1
  • 1
    @Phil ...if you read the whole post it would appear that english isn't this user's first language. The problem is explained clearly enough, he made an effort to figure it out on his own, and even provided a helpful code sample. What's the point of your comment? It certainly isn't something that's constructive or would make the guy feel better... – loriensleafs Oct 29 '15 at 19:06

2 Answers2

7
var date = new Date(dateString);
var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var properlyFormatted = "" + year + month + day;

Or

var date = new Date(dateString);
var properlyFormatted = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2);
6

Use momentjs — it's a library available for using in browser and node projects

In your case you should use this pattern:

moment().format("YYYY-mm-D");

And you can try it in console on momentjs's site:
monentjs

Vladimir Starkov
  • 19,264
  • 8
  • 60
  • 114