1

I have a variable has a value of 2017-11-10 and like to get 3 days before from 2017-11-10 which is 2017-11-7

Seems like it only works if you have entire timestamp. However, I removed time from my timestamp.

let d = new Date();
d.setDate(d.getDate()-1);

Is there any ways to do this without time?

Skate to Eat
  • 2,554
  • 5
  • 21
  • 53
  • 1
    You would parse the string to get a `Date` object (one way or another), then set the date to current minus 3, then format the `Date` as a string without time. – nnnnnn Nov 14 '17 at 02:00
  • I think your question is a duplicate of https://stackoverflow.com/questions/1296358/subtract-days-from-a-date-in-javascript. You could also see https://www.w3schools.com/js/js_date_formats.asp regarding date formats in javascript. Essentially you should have no problem with the format of YYYY-MM-DD that you are using. – noddy Nov 14 '17 at 02:01

2 Answers2

2

Here are few options to get a date string in yyyy-m-d format:

var d = new Date( new Date("2017-11-10" + "z") - 3 * 864e5 ) // specify Zulu time zone to avoid conversion to local time

console.log( d.toJSON().slice(0, 10) ) // "2017-11-07"

console.log( d.toJSON().slice(0, 10).replace('-0', '-') ) // "2017-11-7"

console.log( d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() ) // "2017-11-7"

Timezone information can be added to the date string to avoid conversion to local time:

console.log( new Date("2000-1-2") ) // "2000-01-01T05:00:00.000Z" ("T05:" because converted to local time)

// correct "2000-01-01T00:00:00.000Z"
console.log( new Date("2000-01-02") )   
console.log( new Date("2000-1-2 Z") )  
console.log( new Date("2000-1-2 GMT") ) 
console.log( new Date("2000-1-2 UTC") ) 

console.log( new Date("2000-1-2 z-1234") ) // "2000-01-02T12:34:00.000Z" ha ..
Slai
  • 22,144
  • 5
  • 45
  • 53
  • @Ohsik if any of the dates are not in `yyyy-mm-dd` format, see the updated version. – Slai Nov 14 '17 at 16:13
0

You can just init your date string to javascript Date as below example

let d = new Date(2017, 10, 10);
d.setDate(d.getDate()-3);
i3lai3la
  • 980
  • 6
  • 10