2

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>
omikes
  • 7,248
  • 8
  • 36
  • 47
anatp_123
  • 1,023
  • 2
  • 9
  • 22

4 Answers4

5

var date = new Date('Mon Aug 14 2017 00:00:00 GMT-0500 (CDT)');
var newdate= (date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear();
samnu pel
  • 858
  • 5
  • 12
  • 3
    Is this really the correct answer? It does not have preceding zero for one digit month or day. Example that I get is `5/1/1993` and this is not mm/dd/yyyy – Undefined function May 10 '21 at 18:02
2

Just for fun, here's how you could do it with moment.js.

moment('2017-05-05').add(13, 'day').format('MM/DD/YYYY');

fiddle link

JavaKungFu
  • 1,234
  • 2
  • 11
  • 24
1

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"
Vijay Jagdale
  • 1,937
  • 2
  • 15
  • 16
  • 1
    for IE 11 compatibility: new Date().toLocaleString().split(/\/|,| /).slice(0, 3).map(function (n) { return (n.replace(/\u200E/g,"")<10?'0':'') + '' + n}).join("/"); – Vijay Jagdale Feb 07 '20 at 23:12
0

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));
omikes
  • 7,248
  • 8
  • 36
  • 47