繁体   English   中英

如何将 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 object。 我需要能够在getData()中将“12”用作month变量的数字(用于 12 月)。 如有必要,如何将此 object 转换为数字类型或字符串类型? PS我尝试使用pareInt()。 不起作用。

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

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

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

与其在 React 组件中包含此逻辑,不如将其移至自定义的 React 挂钩 这使您可以根据需要轻松地重用其返回值。

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>;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM