jammy
jammy

Reputation: 977

method to get the date in reactjs

What does this piece of code does and can how can it be broken in parts to understand it's functioning ?

let date = this.state.month.clone().startOf("month").add("w" -1).day("Sunday");

Upvotes: 0

Views: 822

Answers (3)

Nicholas
Nicholas

Reputation: 3784

let date = this.state.month.clone().startOf("month").add("w" -1).day("Sunday");

It takes the month variable, clones it. It goes to the start of it. It ads -1 week and makes the week start with Sunday.

Upvotes: 0

Chris
Chris

Reputation: 59491

Here's a quick explanation:

//this gets and copies the current month
let date = this.state.month.clone()

//change the previous moment by setting it to the start of this month.
.startOf("month")

//change the previous moment by setting it to 1 week earlier
.add("w" -1)

//change the previous moment by setting it to that weeks Sunday
.day("Sunday");

In other words, this will give you last months last Sunday. So if today is Thursday January 4th 2018 (or any other day of January), this will return Sunday December 31st 2017 at 00:00:00

Upvotes: 0

Krasimir
Krasimir

Reputation: 13529

month.clone is about cloning the moment object. This is needed because with the methods afterwards you'll modify it. Or in other words the moment way of achieving immutability. startOf is setting the moment object to the beginning of the current month. I don't understand the add("w" -1). I guess it is move it to a week earlier but if that's the case then should be add(-1, "w"). day("Sunday") is moving the moment object to that day of the week (i.e. the week starts at this day). At the end if you add .toString() you'll see what's the produced date.

var now = moment();

console.log(now.toString());
console.log(now.clone().startOf('month').toString());
console.log(now.clone().startOf('month').add(-1, "w").toString());
console.log(now.clone().startOf('month').add(-1, "w").day("Sunday").toString());

outputs:

"Thu Jan 04 2018 14:31:07 GMT+0200"
"Mon Jan 01 2018 00:00:00 GMT+0200"
"Mon Dec 25 2017 00:00:00 GMT+0200"
"Sun Dec 24 2017 00:00:00 GMT+0200"

Upvotes: 2

Related Questions