【问题标题】:How to convert Luxon DateTime format into string or numbers?如何将 Luxon DateTime 格式转换为字符串或数字?
【发布时间】:2022-01-12 22:09:59
【问题描述】:

我正在使用以下代码设置 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 对象。我需要能够在getData()month 变量中使用“12”作为数字(12 月)。 如果需要,如何将此对象转换为数字类型或字符串类型? 附言我尝试使用 pareInt()。不工作。

【问题讨论】:

  • 您不应该仅仅为了转换时间而返回组件。有很多图书馆已经完成了这项工作,例如date-fns, luxon, moment。请随意选择适合您用例的那个,然后在组件本身中转换时间,而不是创建一个组件来转换时间。

标签: javascript reactjs typescript next.js luxon


【解决方案1】:

您应该将其移至custom React hook,而不是在 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>;
};

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 已经在问题中做到了。它不工作。我需要将月份的输出作为字符串。不是不同键值对的对象。
    • 不知道你的意思抱歉。我刚刚在我的答案中添加了屏幕截图。如果您访问 luxon 网站:moment.github.io/luxon/#,并在开发人员工具控制台中输入上述命令,您应该会以字符串形式获得月份作为输出。但是,在您的项目中运行这些命令时,您可能会得到一些不同的东西?
    • 如果您只想要一个仅在刷新时更改的月份值,这会很好(尽管该月份一年仅更改 12 次,这对于您的用例来说可能没问题)。 juliomalves 的回答 stackoverflow.com/a/70276633/9428323 是您想要保持价值不断更新的结果。尽管我认为您和他的示例中的 useEffect 仅在时区更改时才设置为运行,因此您可能需要将依赖数组 [timezone] 更改为空数组 []
    【解决方案3】:

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

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

    【讨论】:

    • 谢谢。对于项目需要时间/日期需要在不同的情况下以不同的格式使用很多,所以我认为编写整个代码一次更容易,然后只需调用组件并传递所需的格式、时区等。无论如何,所以打印month.props.children 对我没有帮助,因为当我自己打印月份时,这是我得到的对象类型(在下一条评论中添加)。如何从这里获得“12”作为数字?
    • month Object { "$$typeof": Symbol("react.element"), type: LiveDateTime(_ref) , key: null, ref: null, props: {…}, _owner: { …}, _store: {…}, … } "$$typeof": Symbol("react.element") _owner: Object { tag: 0, key: null, index: 0, … } _self: undefined _source: Object { fileName: "C:\\...-card-grid.tsx", lineNumber: 37, columnNumber: 17 } _store: Object { ... } key: null props: Object { timezone: "America/New_York", format: " M" } ref: null type: function LiveDateTime(_ref)​ : Object { … }
    • 我已经看到你在月份对象中有道具。你能控制台日志看看那是什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2011-03-12
    • 2021-11-06
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多