0

I have the following code

import "./styles.css";
import {
  Col,
  Row,
  Form,
  InputGroup,
  Container
} from "reactstrap";
import React from "react";

import { useForm, Controller } from "react-hook-form";
import "react-datetime/css/react-datetime.css";
import Datetime from "react-datetime";

export default function App() {
  const onSubmit = (data) => {
    console.log(data);
  };

  const { control, handleSubmit, watch } = useForm({
    defaualtValues: {
      timevar: new Date(new Date().setHours(0, 0, 0, 0))
    }
  });

  console.log(watch("timevar"));

  return (
    <Container>
      <Form onSubmit={handleSubmit(onSubmit)}>
        <Row className="m-3">
          <Col>
            <InputGroup className="mb-3">
              <Controller
                name="timevar"
                control={control}
                render={({ field }) => (
                  <Datetime
                    {...field}
                    timeFormat={"h:mm A Z"}
                    dateFormat={false}
                    value={field.value}
                  />
                )}
              />
            </InputGroup>
          </Col>
        </Row>
      </Form>
    </Container>
  );
}

The timevar will be in localtime zone

I want to get the value of timevar as hh:mm:ss and this will be a UTC time zone converted value

How can i do this. Is there any way i can do it in the component itself or do i have to get this done in the onSubmit function

Showing what I want in screenshot

enter image description here

codesandbox

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

0

I suggest you to add more information about how you are going to use that timevar, because it may dramatically ease your task.

If timevar should be processed anyhow after the form is submitted, for example sent via network request, then the easiest way is to convert it to UTC and then to string by doing:

const onSubmit = (data) => {
  const { timevar } = data; // make sure that timevar is a moment object.
  const result = timevar.utc().format("hh:mm:ss");
}

If you want to use string representation in render, then you could use useMemo to calculate the string on each date change, like:

import { useMemo } from "react";

...

const timevar = watch("timevar");
const timeString = useMemo(() => {
  // Again, make sure that timevar is a moment object.
  return timevar.utc().format("hh:mm:ss")
}, [timevar]);


// use timeString in render method.

And finally, if you don't care much about performance, and you feel pretty confident with moment's UTC functions you may transform all inputs and outputs on the input component, like this:

<Controller
  ...
  render={({ field }) => (
    <DateTime
     ...
     value={moment.utc(field.value, "hh:mm:ss")}
     onChange=(e => {
       // Make sure that DateTime pass a moment object to onChange.
       field.onChange(
         e.target.value.utc().format("hh:mm:ss")
       );
     }
  }
/>