I have a string that looks like '1/11/2018 12:00:00 AM' and I want to reformat it to dd-mm-yyyy. Keep in mind that the month can be double digit sometimes.
Asked
Active
Viewed 2,163 times
0
-
use https://momentjs.com/ – GottZ Apr 10 '18 at 08:08
-
4Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – sulaiman sudirman Apr 10 '18 at 08:09
3 Answers
0
You can do somethink like this :
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);
However best way is with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');

Léo R.
- 2,620
- 1
- 10
- 22
-
I am trying the moment.js but still I get 'Thu Jan 11 2018 00:00:00 GMT+0100' after conversion – Sebastian Apr 10 '18 at 08:16
0
You can use libraries like moment.js. Assuming either you do not want to use any external library or can not use it, then you can use following custom method:
function formatDate(dateStr) {
let date = new Date(dateStr);
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return day + '-' + month + '-' + year;
}
console.log(formatDate('1/11/2018 12:00:00 AM'));

GauravLuthra
- 1,027
- 9
- 8
0
function convertDate(oldDate) {
var myDate = new Date(Date.parse(oldDate)); //String -> Timestamp -> Date object
var day = myDate.getDate(); //get day
var month = myDate.getMonth() + 1; //get month
var year = myDate.getFullYear(); //get Year (4 digits)
return pad(day,2) + "-" + pad(month, 2) + "-" + year; //pad is a function for adding leading zeros
}
function pad(num, size) { //function for adding leading zeros
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
convertDate("1/11/2018 12:00:00 AM"); //11-01-2018

alexP
- 3,672
- 7
- 27
- 36