Last active
September 20, 2021 09:37
-
-
Save maxmckenzie/d345b47f261ef5716cc7618c2c82fd29 to your computer and use it in GitHub Desktop.
Construct and convert date object from datetime-local input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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