React Native中如何获取当前日期?新手遇实现问题
React Native 获取当前日/月/年的正确姿势
嘿,我来帮你搞定这个日期获取的问题~你当前的代码里有几个容易踩的小坑,导致结果不符合预期:
getDay()方法返回的是星期几(0代表周日,6代表周六),不是当月的具体日期,要获取日期得用getDate()getYear()已经被废弃了,它返回的是当前年份减去1900(比如2024年返回124),正确的用法是getFullYear()getMonth()返回的是从0开始的月份索引(0=1月,11=12月),所以需要加1才能得到实际的月份数字
修正后的类组件代码示例
因为你用到了this.state,推测你用的是类组件,这里给你调整后的代码:
// 初始化state this.state = { currentDay: new Date() }; // 打印正确的日期信息 const currentDate = this.state.currentDay; console.log('完整日期:', currentDate); console.log( 'Day: ' + currentDate.getDate(), 'Month: ' + (currentDate.getMonth() + 1), 'Year: ' + currentDate.getFullYear() );
函数组件写法(如果后续迁移到函数式)
要是你之后用函数组件,也可以这样实现:
import { useState, useEffect } from 'react'; function DateDisplay() { const [currentDay, setCurrentDay] = useState(new Date()); useEffect(() => { const date = currentDay; console.log('完整日期:', date); console.log( 'Day: ' + date.getDate(), 'Month: ' + (date.getMonth() + 1), 'Year: ' + date.getFullYear() ); }, [currentDay]); return ( // 这里放你的组件UI内容 ); }
进阶:格式化带前导零的日期
如果需要更规范的格式(比如两位数字的日/月),可以手动处理:
const date = new Date(); const day = String(date.getDate()).padStart(2, '0'); // 日期补零,比如5变成05 const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零 const year = date.getFullYear(); console.log(`${year}-${month}-${day}`); // 输出示例:2024-05-20
这样应该就能得到你想要的日、月、年啦~
内容的提问来源于stack exchange,提问作者user11279547
相关产品推荐
相关产品推荐

