Return dd-mm-yyyy from Date() object

Viewed 15004

Desired return value should be a string formatted as dd-mm-yyyy.

Im trying to give a format date dd-mm-yyyy to ISOString and adding GMT but the code gives me this format. How can i do?

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

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

5 Answers

For your example '2012-11-04 14:55:45'

You can do: new Date('2012-11-04 14:55:45').toISOString().split('T')[0] in a single line :)

You can convert the local date into a UTC date by adding the timezone offset, then calling toLocaleDateString (British format) while replacing the slashes with dashes and removing the comma.

// Adapted from: https://stackoverflow.com/a/55571869/1762224
const toLocaleUTCDateString = (date, locales, options) =>
  new Date(date.valueOf() + (date.getTimezoneOffset() * 6e4))
    .toLocaleDateString(locales, options);

// 'en-GB' === 'dd/mm/yyyy'
const formatDate = date =>
  toLocaleUTCDateString(date, 'en-GB', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
  .replace(/\//g, '-').replace(/,/, '');

const date = new Date();

console.log({
  'ISO-8601': date.toISOString(),
  'Custom': formatDate(date)
});
.as-console-wrapper { top: 0; max-height: 100% !important; }

Alternatively, you can try parsing the ISO 8601 string:

const formatDate = _date =>
  (([year, month, date, hour, minute, second, milliseconds]) =>
    `${date}-${month}-${year} ${hour}:${minute}:${second}`)
  (_date.toISOString().split(/[^\d]/g));

const date = new Date();

console.log({
  'ISO-8601': date.toISOString(),
  'Custom': formatDate(date)
});
.as-console-wrapper { top: 0; max-height: 100% !important; }

You can use custom function to generate date with hyphen:

const date = () => { 
  let d = new Date();
  return `${d.getDate()}-${d.getMonth()}-${d.getFullYear()}`;
 }
 let el = document.querySelector('p');
 el.innerText = date();
<p></p>

Related