Last active
December 19, 2019 20:48
-
-
Save weirdwater/335e2b2f816144db8206de236968d034 to your computer and use it in GitHub Desktop.
UTC Datepicker
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
import React, { useState } from 'react'; | |
import ReactDatePicker from 'react-datepicker'; | |
export const DatepickerTest = () => { | |
const [date, setDate] = useState(new Date()) | |
return ( | |
<div> | |
<p>Actual value: {date.toString()}</p> | |
<p>Offset to UTC: {offsetToUTC(date).toString()}</p> | |
<ReactDatePicker | |
selected={offsetToUTC(date)} | |
showTimeInput={true} | |
// We revert the offset here to avoid confusion. According to the Date object the timezone is still the user's timezone, just a few hours earlier or later. | |
onChange={d => d && setDate(offsetFromUTC(d))} /> | |
</div> | |
); | |
} | |
// Date.prototype.getTimezoneOffset() returns difference between the current timezone and UTC in minutes. | |
// CET for example returns -60. Javascript timestamps are in milliseconds, so we convert the offset to | |
// milliseconds before offsetting the timestamp. | |
const offsetToUTC = (d: Date) => new Date(d.valueOf() + d.getTimezoneOffset() * 60000) | |
// To invert the offset we simply multiply the offset by -1. | |
const offsetFromUTC = (d: Date) => new Date(d.valueOf() + d.getTimezoneOffset() * -1 * 60000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment