Return dd-mm-yyyy from a Date () object

The desired return value must be a string formatted as dd-mm-yyyy.

I am trying to give a dd-mm-yyyy format date for ISOString and add GMT, but the code gives me this format. How can i do this?

new Date().toISOString()
    .replace(/T/, ' ').      // replace T with a space
    .replace(/\..+/, '');     // delete the dot and everything after

'2012-11-04 14:55:45'

+4
source share
2 answers

im looking for date format 04-11-2012

Using today's date (which is currently an ISO string, "2016-03-08T13: 51: 13.382Z"), you can do this:

new Date().toISOString().replace(/T.*/,'').split('-').reverse().join('-')

The result of this:

-> "08-03-2016"

It:

  • Capture date.
  • Converts it to an ISO string.
  • Replaces "T" and everything after it.
  • Converts it to an array, breaking it into any hyphen character ('-'). ( ["2016", "03", "08"])
  • . (["08", "03", "2016"])
  • , .

, (2012-11-04T14: 55: 45.000Z) :

var input = "2012-11-04T14:55:45.000Z",
    output;

output = new Date(input).toISOString().replace(/T.*/,'').split('-').reverse().join('-');

document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = output;
<p><strong>Input:</strong> <span id=input></span></p>
<p><strong>Output:</strong> <span id=output></span></p>
Hide result
+4

new Date().toLocaleDateString("en-US"); . "3/8/2016" .

new Date().toLocaleDateString().replace(/\//g, '-'); . "3-8-2016" .

0

All Articles