BNC Stocks
BNC Stocks

Reputation: 53

Convert all dates in an array to format MM/DD/YYYY javascript

I have an array of dates in the format :

dates_arr = [
    Thu Aug 13 2020 00:00:00 GMT-0400 (Eastern Daylight Time),
    Fri Aug 14 2020 00:00:00 GMT-0400 (Eastern Daylight Time),
    Sat Aug 15 2020 00:00:00 GMT-0400 (Eastern Daylight Time),
    Sun Aug 16 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
]

I would like to convert all the dates to the format MM/DD/YYYY and replace the array with them.

Upvotes: 0

Views: 4403

Answers (2)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

I would like to convert all the dates to the format MM/DD/YYYY and replace the array.

You could do it as follows -

Correct Code -

let dates_arr = [
  'Thu Aug 13 2020 00:00:00 GMT-0400 (Eastern Daylight Time)',
  'Fri Aug 14 2020 00:00:00 GMT-0400 (Eastern Daylight Time)',
  'Sat Aug 15 2020 00:00:00 GMT-0400 (Eastern Daylight Time)',
  'Sun Aug 16 2020 00:00:00 GMT-0400 (Eastern Daylight Time)'
];
dates_arr = dates_arr.map((element) => {
  var d = new Date(element);
  return `${d.getMonth()+1}/${d.getDate()}/${d.getFullYear()}`;
})
console.log("Dates in the format MM/DD/YYYY : \n", dates_arr);


Explanation :

  • The strings which are present in dates_arr are the default way in which Javascript will output the dates. We are taking each of those strings and mapping over the dates_arr using map() function and simply returning the dates in the required format. This will create a new array with strings of date in the form we need them to be.

  • Firstly, I am creating a date object in the code using new Date(element). The Date() constructor can take in date string and form date object on which we can apply various in-built methods provided by JS as given below.

  • There are different methods which date provides us like

    1. getMonth() which returns the month from 0-11
    2. getDate() which returns the day of the month from 1-31 and
    3. getFullYear() which returns the year in the date.

    I have used these methods to get the date string into the desired format. There are various other methods as well which you can read more on here.

  • Also, if you are not aware, I am using template literals in the return statement which is just a syntactic sugar added in ES6. The return statement does the same thing as -

    return ((d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear())
    

    But using the template literals is just a more efficient way of writing such statements.

Upvotes: 2

Pablo Roldan
Pablo Roldan

Reputation: 21

var formattedDate = dates_arr.map(date=>dateFormat(date)); 
function dateFormat(date){
    const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'short', day: '2-digit' }) 
    const [{ value: month },,{ value: day },,{ value: year }] = dateTimeFormat .formatToParts(date )
    return `${month}/${day}/${year}`
 }

Upvotes: 0

Related Questions