How to format JavaScript date to mm/dd/yyyy?

Viewed 27262

Im getting the date like 'Wed Nov 08 2017 00:00:00 GMT-0800 (Pacific Standard Time)' and putting the value in an input.

Is there a way to parse the datetime into a date, add five days to it, and then format it like mm/dd/yyyy?

I made a https://jsfiddle.net/ax6qqw0t/

<script>
  startingDate = new Date(5/5/2017);
 var adjustedDate = addDays(startingDate,13);
$('#max_products').val(adjustedDate);
</script>
4 Answers

I'm sure you've solved this by now, but it looked like a fun one so I decided to take a stab at it using Intl.DateTimeFormat.

// get date for five days later
const date = 'Fri Dec 29 2017 00:00:00 GMT-0800 (Pacific Standard Time)';
const dateSet = new Date(date);
const fiveDaysLater = dateSet.setDate(dateSet.getDate() + 5);

// set up date formatting parameters
const ops = {year: 'numeric'};
ops.month = ops.day = '2-digit';

console.log(new Intl.DateTimeFormat([], ops).format(fiveDaysLater));

Here are useful one-liners to get date string in various formats:

Date formatted as m/d/yyyy and MM/DD/yyyy (padded zeroes)

>new Date().toLocaleString().split(",")[0]
"2/7/2020"
>new Date().toLocaleString().split(/\D/).slice(0,3).map(num=>num.padStart(2,"0")).join("/")
"02/07/2020"

Date formatted as yyyy-mm-dd, and yyyymmdd:

>new Date().toISOString().split("T")[0]
"2020-02-07"
>new Date().toISOString().split("T")[0].replace(/-/g,'')
"20200207"
Related