0

I get the date from server in such format: 2019-01-24 00:00:00

How to convert it to 24-01-2019?

I use:

new Date(dateFromServer).toLocaleDateString()

but it returns 01/24/19.

chazsolo
  • 7,873
  • 1
  • 20
  • 44
lecham
  • 2,294
  • 6
  • 22
  • 41
  • var d = new Date(dateFromServer); var datestring = (d.getMonth()+1) + "/" + d.getDate() + '/' +d.getFullYear() – Deepak Singh Mar 28 '19 at 14:23
  • @DeepakSingh - month/day/year is what OP is already getting ... your suggestion results in a less correct answer, because it doesn't even have the leading 0 in the month ... OP wants dd-mm-yyyy – Jaromanda X Mar 28 '19 at 14:50

2 Answers2

0

as seen here Format date to MM/dd/yyyy in JavaScript

var date = new Date(dateFromServer);
alert(date.getDate() + '-' + (date.getMonth() + 1) + '-' +  date.getFullYear());
Marnix Harderwijk
  • 1,313
  • 9
  • 14
0

Avoid answers that suggest parsing, it doesn't make sense to parse a string to a Date and reformat it just to get back the values you started with, given the risks of using the built–in parser (e.g. in Safari, new Date('2019-01-24 00:00:00') returns an invalid Date).

To reformat a date, just split it into the parts and put it back as you want:

// @param {string} s - timestamp in format YYYY-MM-DD HH:mm:ss
function reformatDateString(s) {
  var b = s.split(/\D/);
  return `${b[1]}/${b[2]}/${b[0]}`
}

console.log(reformatDateString('2019-01-24 00:00:00'));
RobG
  • 142,382
  • 31
  • 172
  • 209