Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set timezone React-Datepicker

I'm using the react-datepicker to let user select a date. However, right now it uses local time (PDT), but I want to hardcode it to use a specific timezone (PST).

I tried using utcOffset prop but it doesn't seem to be doing anything. Does anyone know how to accomplish this?

like image 293
MarksCode Avatar asked Oct 29 '18 18:10

MarksCode


People also ask

How do I change the timezone on Datepicker?

Code: $(document). ready(function () { $('#myDate'). datepicker({ }); var a = new Date(); var timeZoneOffset = +5*60 //Set specific timezone according to our need.

How do you set date picker in react?

Setting Calendar date range in Datepicker. To do so, we import the addDays API from the date-fns library to the top of our React component. It will add the specific number of days to the assigned date to set the range. The addDays() method usually takes two parameters: Date: The date that needs to be updated.

How do I change date format in Datepicker in react?

You can control the format of the DateTimePicker by using the format property. The format property accepts string parameters and, by default, is set to 'MM/dd/yyyy HH:mm:ss' . When format is set and the input element is not focused, the value is formatted accordingly.

What is react DayPicker?

React DayPicker v8 DayPicker is a date picker component for React. $ npm install react-day-picker date-fns # using npm.


4 Answers

For my part I set the defaultTimezone before rendering the React-dates plugin. React-dates will just use the default timezone.

moment.tz.setDefault('America/Los_Angeles');
like image 70
Matt2772 Avatar answered Sep 17 '22 16:09

Matt2772


This works for me:

import React, { ComponentProps } from "react"
import DatePicker from "react-datepicker"
import moment from "moment"

interface Props {
  timezone: string
}

const DatePickerWithTimezone = ({
  selected,
  onChange,
  timezone,
  ...props
}: Props & ComponentProps<typeof DatePicker>) => (
  <DatePicker
    selected={selected ? setLocalZone(selected, timezone) : null}
    onChange={(v, e) => {
      onChange(v ? setOtherZone(v, timezone) : null, e)
    }}
    {...props}
  />
)

const setLocalZone = (date: Date, timezone: string) => {
  const dateWithoutZone = moment
    .tz(date, timezone)
    .format("YYYY-MM-DDTHH:mm:ss.SSS")
  const localZone = moment(dateWithoutZone).format("Z")
  const dateWithLocalZone = [dateWithoutZone, localZone].join("")

  return new Date(dateWithLocalZone)
}

const setOtherZone = (date: Date, timezone: string) => {
  const dateWithoutZone = moment(date).format("YYYY-MM-DDTHH:mm:ss.SSS")
  const otherZone = moment.tz(date, timezone).format("Z")
  const dateWithOtherZone = [dateWithoutZone, otherZone].join("")

  return new Date(dateWithOtherZone)
}

export default DatePickerWithTimezone
like image 38
Martin Liptak Avatar answered Sep 20 '22 16:09

Martin Liptak


since datepicker doesn't use moment.js anymore i tried to implement a hacky solution for this issue, assuming the initial value is a string for instance:

export const formatUTC = (dateInt, addOffset = false) => {
    let date = (!dateInt || dateInt.length < 1) ? new Date : new Date(dateInt);
    if (typeof dateInt === "string") {
        return date;
    } else {
        const offset = addOffset ? date.getTimezoneOffset() : -(date.getTimezoneOffset());
        const offsetDate = new Date();
        offsetDate.setTime(date.getTime() + offset * 60000)
        return offsetDate;
    }
}

inside date i call the formatter like this:

selected={formatUTC(this.props.input.value,true)}
                    onChange={date => formatUTC(date)}
like image 43
Julian Schroeter Avatar answered Sep 18 '22 16:09

Julian Schroeter


I've been thru this, If you decided that you want to just ignore your local offset then you can hardcode the zone. Observation just to give a complete answer: PST will always be -08:00, but if you want for example pacific time, right now is -07:00, in this case, you may want to install 'moment.timezone' then import moment from 'moment-timezone' and just get the current offset with moment.tz('US/Pacific').format('Z')

The code in typescript (I can change it to Javascript if you want):

interface ICalendarInputProps {
  handleChange: (newDate: moment.Moment) => void;
}

const CalendarInput = ({ handleChange }: ICalendarInputProps) => {
  const onChange = (date: Date) => {
    handleChange(moment(`${moment(date).format('YYYY-MM-DDThh:mm:ss')}-08:00`));
    // This is to get the offset from a timezone: handleChange(moment(`${moment(date).format('YYYY-MM-DDThh:mm:ss')}${moment.tz('US/Pacific').format('Z')}`));
  };

  return (<DatePicker onChange={onChange} />);
};

export default CalendarInput;
like image 43
Manuel Machado Avatar answered Sep 19 '22 16:09

Manuel Machado