Skip to content

Instantly share code, notes, and snippets.

@weirdwater
Last active December 19, 2019 20:48
Show Gist options
  • Save weirdwater/335e2b2f816144db8206de236968d034 to your computer and use it in GitHub Desktop.
Save weirdwater/335e2b2f816144db8206de236968d034 to your computer and use it in GitHub Desktop.
UTC Datepicker
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