简体   繁体   English

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

[英]How to convert Luxon DateTime format into string or numbers?

I am using the following code to set up a Luxon clock for my project use.我正在使用以下代码为我的项目设置一个 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;

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.当我在控制台中打印它时,我得到了整个 react.element object。 I need to be able to use '12' as a number (for December) in getData() for the month variable.我需要能够在getData()中将“12”用作month变量的数字(用于 12 月)。 How can I covert this object into a number type or string type if necessary?如有必要,如何将此 object 转换为数字类型或字符串类型? PS I tried using pareInt(). PS我尝试使用pareInt()。 doesn't work.不起作用。

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

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如果需要,添加.reconfigure({ outputCalendar: calendar })和/或.plus({ days: daysOffset })

Rather than having this logic in a React component, you should move it to a custom React hook instead.与其在 React 组件中包含此逻辑,不如将其移至自定义的 React 挂钩 This allows you to easily reuse its return value however you like.这使您可以根据需要轻松地重用其返回值。

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;

You can then retrieve the value as a string so you can pass it to other functions, or render it.然后,您可以将该值作为字符串检索,以便将其传递给其他函数或呈现它。

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