You need to enable JavaScript to run this app. 如何在React Native中获取Firestore日期并转换为dd/mm/yyyy格式
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native中获取Firestore日期并转换为dd/mm/yyyy格式

解决方案

核心原理

你存储到Firestore的JS Date对象会被自动转换为Firebase Timestamp类型,读取时需要先将其转回JS Date对象,再按目标格式拼接即可。

实现步骤

1. 定义日期格式化工具函数

可以直接在页面2的组件外或者工具文件中定义通用格式化方法,无需引入第三方依赖:

const formatFirestoreDate = (firestoreTimestamp) => {
  // 兼容两种转换方式:优先用Timestamp自带的toDate, fallback用秒数转毫秒构造Date
  const date = firestoreTimestamp.toDate 
    ? firestoreTimestamp.toDate() 
    : new Date(firestoreTimestamp.seconds * 1000);
  
  // 日期补零处理
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0'); // JS月份从0开始计数,需要+1
  const year = date.getFullYear();

  return `${day}/${month}/${year}`;
};

2. 修改FlatList渲染逻辑

把原来直接渲染秒数的部分替换为调用上面的格式化函数:

<FlatList
  ListEmptyComponent={<Text>Nothing Available</Text>}
  style={{ padding: 10, backgroundColor: "#D8E0E5E6" }}
  data={exampleState}
  keyExtractor={(item) => item.key}
  renderItem={({ item }) => (
    <Card
      title={formatFirestoreDate(item.title)}
      sub={item.sub}
      // onPress={() => {}}
    />
  )}
/>

可选简化方案(项目已安装日期库时使用)

如果你的项目中已经引入了dayjs、date-fns这类日期处理库,可以直接用库的格式化方法,无需自定义工具函数,以dayjs为例:

import dayjs from 'dayjs';

// 渲染时直接调用即可
title={dayjs(item.title.toDate()).format('DD/MM/YYYY')}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 04:24:08