Adam
Adam

Reputation: 2552

Subtract x days from a String Date - React

Suppose I've got a date in string format, such as "2021-07-19". How can I subtract x days from this date that is represented as a string?

I have tried to convert the string into a date first, then subtract the number of days, and convert back to a string, but that doesn't work.

const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = previousDayDate.toString()

The ultimate result should be "2021-07-18". Instead, I get the date as a full string: Sun Jul 18 2021 01:00:00 GMT+0100 (British Summer Time)

Upvotes: 0

Views: 878

Answers (4)

RobG
RobG

Reputation: 147453

The reason you get the wrong date is that "2021-07-19" is parsed by built–in parsers as UTC, but all the other methods you're using are local, so you appear to get the wrong date or time. Other than that, your algorithm is sound. Just parse the string as local to being with:

// Parse string in YYYY-MM-DD format as local
function parseISOLocal(s) {
  let [Y, M, D] = s.split(/\W/);
  return new Date(Y, M-1, D);
}


console.log(parseISOLocal('2021-07-20').toString());

This is a very common issue.

Upvotes: 1

Adam
Adam

Reputation: 2552

Thank you all for the suggestions. I followed the same convention as Spencer's comment above (How to format a JavaScript date?) by doing:

const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)

const previousDayString = previousDayDate.toLocaleDateString("en-CA").split(",")[0]

console.log(previousDayString)

Upvotes: 0

Kinglish
Kinglish

Reputation: 23664

Note, the snippet below didn't work in my locale until I changed the input date to YYYY-MM-DD.

// const dateString = "2021-19-07" - your format
const dateString = "2021-07-19" // format testable in my locale
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = `${previousDayDate.getFullYear()}-${('0' + (previousDayDate.getMonth()+1)).slice(-2)}-${('0' + previousDayDate.getDate()).slice(-2)}`;
console.log(previousDayDateString)

Upvotes: 0

Sirajeddine Aissa
Sirajeddine Aissa

Reputation: 26

Using Moment.js

const dateString = moment("2021-07-19", "YYYY-MM-DD").startOf("day")
const previousDayDateString = dateString.subtract(1, "days").format("YYYY-MM-DD");

Upvotes: 0

Related Questions