React – Formatting Dates and a Date Picker with a Range

Overview
Examples for handling dates in React with Moment & Date FNS, and a date picker that can disable days outside a date range.
Moment.js
Moment.js is a popular JS library for handling Date Time formatting operations. You can get all the details from their website here.
npm install moment
Example of formatting a date from a records field labeled Date Created.
The original data looks like this: 2021-06-07T10:13:30.34
The formatted date: 06/07/2021
import moment from "moment";
...
return (
{moment(data.DateCreated).format('MM/DD/YYYY')}
)
Date FNS – Material Table Column
Formatting a date with Date FNS in a Material Table column definition. The current date is created with new Date() and then formatted with format() from date-fns.
import { format } from "date-fns";
...
{ title: 'End Date',
field: 'EndDate',
filtering: false,
render: rowData => {
var date = new Date(rowData.EndDate);
let currentDate = new Date()
if(date <= currentDate) {
return `Expired: ${format(date, 'MM/dd/yyyy')}`;
}
else {
return format(date, 'MM/dd/yyyy');
}
},
type: "date",
dateSetting: { locale: "en-US"},
}
If you are not able to import Date FNS then you
npm install date-fns
Example Start and End Dates
Example of a start of today and end date that is one month into the future.
var startDate = new Date();
var endDate = new Date(startDate.setMonth(startDate.getMonth() + 1));
Example of a start of today and end date that is 7 days into the future.
var today = new Date();
var startDate = today;
var endDate: new Date(today.setDate(today.getDay() + 7));
React Date Picker
React Date Picker has the option to only allow for a certain date range to become available.
npm install react-date-picker
The example below only shows the current date to 60 days into the future,
import InputReactDatePicker from 'shared/InputReactDatePicker';
...
<InputReactDatePicker label="From Date"
fieldName="FromDate"
minDays={0}
maxDays={60}
value={startDate}
handleDateChange={this.handleFromDateTimeChange}
/>
You must be logged in to post a comment.