如何将 Luxon DateTime 格式转换为字符串或数字?

How to convert Luxon DateTime format into string or numbers?

我正在使用以下代码为我的项目设置 Luxon 时钟。

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;

现在,我在另一个地方使用这个组件来定义当前日期的月份#。

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'.

当我在控制台打印这个时,我得到了一个完整的 react.element 对象。我需要能够将“12”用作 getData() 中的数字(12 月)用于 month 变量。 如果需要,如何将此对象转换为数字类型或字符串类型? P.S。我尝试使用 pareInt()。不起作用。

尽管我仍然在评论中提倡我的观点,但如果你想继续你选择的方式,我完全尊重。因此,如果您想访问组件的值,您可以通过调用将在您的案例中保存该值的子组件来实现。

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

因为您只是在组件中使用当前时间的月份,您可以使用
const month = DateTime.local().setZone(place?.timezone).toFormat('M')
添加 .reconfigure({ outputCalendar: calendar }) and/or .plus({ days: daysOffset }) 如果需要

与其将此逻辑放在 React 组件中,不如将其移至 custom React hook。这使您可以随心所欲地轻松重用其 return 值。

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

const useLiveDataTime = ({
  timezone,
  daysOffset,
  format,
  calendar,
}: IProps) => {
  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 timeLive?.toFormat(format);
}; 

export default useLiveDataTime;

然后您可以将值作为字符串检索,以便将其传递给其他函数或呈现它。

import React from 'react';
import useLiveDataTime from '<path-to>/use-live-date-time';

const SomeComponent: React.FC = () => {
    const month = useLiveDataTime({ timezone: 'Europe/London', format: 'M' });
    console.log(month);
    getData(month);

    return <span>{month}</span>;
};