Return dd-mm-yyyy from Date() object
Asked Answered
U

5

19

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'

Uncrown answered 7/3, 2016 at 11:53 Comment(4)
Why not use a library like MomentJS ?Bright
I can't in this project. Other solutions?Uncrown
If "2012-11-04 14:55:45" is not the correct format, can you provide an example of the format you're looking for?Snotty
@Snotty im looking for 04-11-2012 date formatUncrown
M
23

im looking for 04-11-2012 date format

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

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

The output of this is:

-> "08-03-2016"

This:

  1. Grabs the date.
  2. Converts it to an ISO string.
  3. Replaces the 'T' and everything after it.
  4. Converts it into an array by splitting on any hyphen ('-') character. (["2016", "03", "08"])
  5. Reverses the order of the array. (["08", "03", "2016"])
  6. Joins the array back as a string, separating each value with a hyphen character.

Here is a demo using your date (2012-11-04T14:55:45.000Z) as input:

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>
Malagasy answered 8/3, 2016 at 13:52 Comment(1)
I am looking '2020-12-21' and new Date().toISOString().replace(/T.*/,'') this solved the issue . @james thanksSilsby
H
7

You can use new Date().toLocaleDateString("en-US"); to return only the date. This returns "3/8/2016" today.

new Date().toLocaleDateString().replace(/\//g, '-'); will change it to output with dashes. This will return "3-8-2016" today.

Hally answered 8/3, 2016 at 14:3 Comment(1)
new Date().toLocaleDateString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-') for two digit month/day values.Incubus
G
6

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 :)

Gannon answered 19/6, 2018 at 15:46 Comment(0)
R
1

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://mcmap.net/q/666153/-is-there-a-function-to-get-the-utc-date-in-the-locale-string-format
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; }
Radiography answered 9/4, 2021 at 18:52 Comment(0)
B
0

If you want to get date as dd-mm-yyyy format, You can use custom function to generate with day, month and full year metods of Date(), but day and month may return number less then 10, if date or month's number is less then 10, so you can check if it is, you add 0, otherwise you leave itself like following below:

const date = () => { 
  let d = new Date();
  let day = d.getDate()
  let month = d.getMonth()
  return `${day < 10 ? "0" + day : day}-${month < 10 ? "0" + month : month}-${d.getFullYear()}`;
 }
 let el = document.querySelector('p');
 el.innerText = date();
<p></p>
Birthstone answered 23/9, 2022 at 15:53 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Underwaist

© 2022 - 2024 — McMap. All rights reserved.