Home > Enterprise >  How to convert Luxon DateTime format into string or numbers?
How to convert Luxon DateTime format into string or numbers?

Time:12-08

I am using the following code to set up a Luxon clock for my project use.

import { DateTime } from 'luxon';
import React, { useEffect, useState } from 'react';

interface IProps {
  timezone: string;
  format: string;
  calendar?: string;
  daysOffset?: number;
}

const LiveDateTime: React.FC<IProps> = ({
  timezone,
  daysOffset,
  format,
  calendar,
}) => {
  const [timeLive, setTimeLive] = useState<DateTime>(DateTime.local());

  useEffect(() => {
    const interval = setInterval(() => {
      setTimeLive(
        DateTime.local()
          .setZone(timezone)
          .reconfigure({ outputCalendar: calendar })
          .plus({ days: daysOffset })
      );
    }, 1000);

    return () => clearInterval(interval);
  }, [timezone]);

  return <span>{timeLive?.toFormat(format)}</span>;
}; 
export default LiveDateTime;

Now, I am using this component in another place to define the month# of the current date.

const month = <LiveDateTime timezone={place?.timezone} format="M" />; // This returns '12' as a number in the UI (for December)
console.log(month)
getData(month); //this functions is supposed to return some data based on the given month.
//I get an error instead on this line that says, 'Argument of type 'Element' is not assignable to parameter of type 'number'.

When I print this in the console, I get an entire react.element object. I need to be able to use '12' as a number (for December) in getData()for the month variable. How can I covert this object into a number type or string type if necessary? P.S. I tried using pareInt(). doesn't work.

CodePudding user response:

Even though I am still advocating my opinion that is in the comments, I totally respect if you want to continue the way you have chosen. Therefore, if you want to access the value of the component you can do so by calling the children which will hold the value in your case.

console.log(month.props.children) // will return 12 as string

CodePudding user response:

As you're just using the month of the current time in the component you could just use
const month = DateTime.local().setZone(place?.timezone).toFormat('M')
adding a .reconfigure({ outputCalendar: calendar }) and/or .plus({ days: daysOffset }) if required

  • Related