You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native如何获取当前星期几?能否转为函数组件?

React Native 实时时间展示:类组件转函数组件及优化方案

一、类组件转函数组件实现

下面是将你提供的类组件转为函数组件的版本,使用React Hooks替代类组件的生命周期和状态管理:

import { useState, useEffect } from 'react';
import { View, Text } from 'react-native';

export default function NowShowing() {
  const [currentTime, setCurrentTime] = useState('');
  const [currentDay, setCurrentDay] = useState('');
  const daysArray = [
    'sunday',
    'monday',
    'tuesday',
    'wednesday',
    'thursday',
    'friday',
    'saturday',
  ];

  const getCurrentTime = () => {
    const now = new Date();
    let hour = now.getHours();
    let minutes = now.getMinutes();
    const am_pm = hour >= 12 ? 'PM' : 'AM';

    // 处理分钟补零
    minutes = minutes < 10 ? `0${minutes}` : minutes;
    // 转换为12小时制
    hour = hour % 12 || 12;

    setCurrentTime(`${hour}:${minutes} ${am_pm}`);
    
    // 获取星期几
    const dayIndex = now.getDay();
    setCurrentDay(daysArray[dayIndex].toUpperCase());
  };

  useEffect(() => {
    // 初始化获取时间
    getCurrentTime();
    // 设置定时器每秒更新
    const timer = setInterval(getCurrentTime, 1000);
    // 组件卸载时清除定时器
    return () => clearInterval(timer);
  }, []);

  const now = new Date();
  return (
    <View>
      <Text>{currentTime}</Text>
      <Text>
        {currentDay} | {now.getMonth() + 1}/{now.getDate()}/{now.getFullYear()}
      </Text>
    </View>
  );
}

代码说明:

  • 使用useState管理currentTime和currentDay状态,替代类组件的this.state
  • 使用useEffect处理初始化和定时器逻辑,替代componentDidMount和componentWillUnmount
  • 优化了Date对象的创建,只实例化一次now复用,避免多次创建
  • 简化了12小时制和AM/PM的判断逻辑,代码更简洁
  • 修复了原类组件中daysArray多一个sunday的冗余问题
  • 修复了原代码中月份显示错误的问题(getMonth()返回0-11,因此加1得到实际月份)

二、其他展示星期几的方法

除了手动维护星期数组的方式,还可以使用JavaScript内置的Intl.DateTimeFormatAPI,更简洁且支持多语言:

方法1:直接获取本地化星期全称

const getCurrentDay = () => {
  const now = new Date();
  // 获取大写的英文星期全称
  const dayName = new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(now);
  return dayName.toUpperCase();
};

方法2:获取星期缩写

如果需要缩写形式(如SUN、MON),可以调整参数:

const getCurrentDayShort = () => {
  const now = new Date();
  const dayName = new Intl.DateTimeFormat('en-US', { weekday: 'short' }).format(now);
  return dayName.toUpperCase();
};

这种方法不需要手动维护星期数组,系统会根据指定的语言自动返回对应名称,扩展性更强。

内容的提问来源于stack exchange,提问作者randelski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:25:37