-2

Hello I have to convert a date like D/M/YYYY to YYYY/MM/DD

Ex : 1/6/2015 --> 2015/06/01 not 2015/6/1

I have some conditions to be met :

  • When it convert the month like Jan "1" must give : 01, Feb "2" must give : 02 etc

  • I have to use Date()

    var st = "D/M/YYYY"
    var dt = new Date(st);
    
    var maFonction = function(userdate) {
      var day = st.getDate();
      var month = st.getMonth();
      var year = st.getFullYear();
      var maDate = year + "/" + day + "/" + month;
      return maDate;
    }
    
    console.log(maFonction(st));
    

I tried but it doesn't works.

Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
JeanA
  • 11
  • 3
  • Possible duplicate of [convert date from dd/mm/yyyy to yyyy-mm-dd in javascript](http://stackoverflow.com/questions/19709793/convert-date-from-dd-mm-yyyy-to-yyyy-mm-dd-in-javascript) – Oxi Jan 13 '16 at 09:58

2 Answers2

0

use this function to convert date from D/M/YYYY to YYYY/MM/DD

var convertDate = function (userdate){
    var d = userdate.split("/");
    return  d[2] + '/' +
            ('0' + d[1]).slice(-2) + '/' +
            ('0' + d[0]).slice(-2) + '/';
};

convertDate("3/1/2016"); // returns 2016/01/03
Narendra CM
  • 1,416
  • 3
  • 13
  • 23
0

Try this:

var date = new Date("1/6/2015");

var dt = ('0' + (date.getMonth()+1)).slice(-2) + '/'
             + ('0' + date.getDate()).slice(-2) + '/'
             + date.getFullYear();

alert(dt.split("/").reverse().join("/"));
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331