Skip to content

Instantly share code, notes, and snippets.

@kristopolous
Last active January 25, 2022 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopolous/d956c148ddcb628d54ec5118a139b9dc to your computer and use it in GitHub Desktop.
Save kristopolous/d956c148ddcb628d54ec5118a139b9dc to your computer and use it in GitHub Desktop.
simple datepicker using Intl.DateTimeFormat
// this is more a guide than working code.
constructor(props) {
super(props);
let minimum_age = 21;
this.endyear = (new Date().getYear() + 1900) - minimum_age;
this.state = {
dob_year: this.endyear,
dob_month: 0
});
this.datepicker = this.datepicker.bind(this);
}
datepicker() {
// this is the range (here, it's 100) - the end year
// so we accomodate up to 121 year olds, which there has been
// only one of as of this authorship.
let startyear = this.endyear - 100;
let {dob_year, dob_month} = this.state;
// We figure out how many days are in a month by "this one
// really weird trick"!
//
// In JS months are 0 based and we are doing 1 based
// for our storage.
//
// This means that say (2021, 1) is actually february.
//
// Also you can do "negative" days. This means that
//
// 2021, 1, 0
//
// Means 1 day before February 1st, in this case, January 31st.
//
// .getDate() gets the numerical day of the month from the input
// date.
//
// So this function goes one month ahead (dob_month), one day behind
// (0), and queries for what day of the month that is.
let maxday = new Date(dob_year, dob_month, 0).getDate();
return <div>
<select onChange={(e) => this.setState({dob_year: e.target.value})} >
{
Array(this.endyear - startyear).fill().map((e,i) =>
<option>{ this.endyear - i }</option>
)
}
</select>
// Instead of including the names of the months, which is a dumb idea
// we defer to the navigator's first language as the locale and then
// create 12 dates and ask Intl.DateTimeFormat what it would call the
// month for these given dates
// That + sign is a type conversion since values always come in as strings
<select onChange={(e) => this.setState({dob_month: +e.target.value})} >
{
Array(12).fill().map((e,i) =>
<option value={ i + 1 }>{
Intl.DateTimeFormat(navigator.languages[0],
{month: 'long'}).format( new Date(startyear, i) )
}
</option>
)
}
</select>
<select onChange={(e) => this.setState({dob_day: e.target.value})} >
{
Array(maxday).fill().map((e,i) =>
<option>{ i + 1 }</option>
)
}
</select>
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment