0

I have a string "26-08-2016" and I want to convert it to "2016-08-26". I prefer when possible to do this using the date object. But I am afraid some regex solution is only available?

Ingvi Jónasson
  • 730
  • 8
  • 27

4 Answers4

6

You can try

var date = "26-08-2016";


var newdate = date.split("-").reverse().join("-");

Input : 26-08-2016

Output : 2016-08-26

Nitya Kumar
  • 967
  • 8
  • 14
1

Did you alredy try to use moment.js?

var mydate = moment("26-08-2016" , "DD-MM-YYYY").format("YYYY-MM-DD");
Vermicello
  • 308
  • 1
  • 6
  • 11
0

The Dateobject does expose an API which allows you to get certain values from the object such as date, month, hour, and timezone, which can be used to format a date string.

Simple formatting example using Date object methods.

var date = new Date();

var output = [date.getFullYear(), date.getMonth()+1, date.getDate()].join('-'); 

console.log( output ); //2016-8-26

The better way is probably to write a formatting function like so:

function formatDate(now) {
   var year = now.getFullYear();
   var month = now.getMonth()+1;
   var date = now.getDate();

   //Add '0' to month if less than 10
   month = (month.toString().length < 2)
      ? "0"+month.toString()
      : month;

   return [year, month, date].join('-');
   //return `${year}-${month}-${date}`; if you're using ES6
}

var now = new Date();

console.log(
   formatDate(now)
); // 2016-08-26

All available methods are found here at mozilla docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth

cbass
  • 2,548
  • 2
  • 27
  • 39
0

try this

montharray = [01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12];
var final_date = new Date("26-08-2016");     
var month_of_date = montharray[final_date.getMonth()];
final_date = final_date.getFullYear() + "-" + month_of_date + "-" + final_date.getDate();
Shakir Ahamed
  • 1,290
  • 3
  • 16
  • 39