Skip to content

Instantly share code, notes, and snippets.

@maxmckenzie
Last active September 20, 2021 09:37
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 maxmckenzie/d345b47f261ef5716cc7618c2c82fd29 to your computer and use it in GitHub Desktop.
Save maxmckenzie/d345b47f261ef5716cc7618c2c82fd29 to your computer and use it in GitHub Desktop.
Construct and convert date object from datetime-local input
const [myDate, setMyDate] = useState()
const pad2 = (num: number): string => num < 10 ? '0' + num : num.toString();
const utcAsLocalString = (date: Date | undefined): string | undefined => {
if (date == null) return undefined;
return (date.getFullYear() + '-' + pad2(date.getMonth()) + '-' + date.getDate() + 'T' + pad2(date.getHours()) + ':' + pad2(date.getMinutes()) + ':' + pad2(date.getSeconds()))
}
<input
type="datetime-local"
class="form-control"
onChange={(e) => setMyDate(new Date((e.target as any).value))}
value={myDate ? utcAsLocalString(myDate) : null}
onFocus={() => {}}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment