Felipe Vegners
Felipe Vegners

Reputation: 27

How to get day (2-digit) from date string

I have a date string in variable called dateEnd like this Mon Nov 20 2017 23:59:59 GMT-0200 on my react component and I want to extract the day (20) and convert it to a number.

This is my code:

let dateEnd = rangePicker['endDate'] && rangePicker['endDate'].toString();

How can I do this?

I've tried some like this:

let dateEndNum = parseInt(dateEnd.replace(/^\D+|\D.*$/g, ""), 10);

But returns me a error, because .replace is not defined.

In addition, I want to get the initial date and the end date to calculate how many days has between those dates.

Upvotes: 1

Views: 319

Answers (3)

Martin Shishkov
Martin Shishkov

Reputation: 2837

Your issue is not related with react. However I suggest you try out moment.js - it is a super powerful js library for handling datetime objects. In your case:

const momentDate = moment("Mon Nov 20 2017 23:59:59 GMT-0200");
const extractedDays = momentDate.date();

Upvotes: 0

laurent
laurent

Reputation: 90776

This would return a boolean.

let dateEnd = rangePicker['endDate'] && rangePicker['endDate'].toString();

What you want is something like this:

let dateEnd = rangePicker['endDate'] ? rangePicker['endDate'].toString() : '';

Upvotes: 1

Gilad Bar
Gilad Bar

Reputation: 1322

Although this isn't related to React, I recommend using momentjs, you can create a moment object using the date string, and one of the many functions can get you want you want.

Upvotes: 0

Related Questions