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

React Native中如何将YYYY/MM/DD日期转换为MM/DD/YYYY等目标格式

解决方案

最低要求实现(07-11-2022 @ 3:00PM格式)

不需要引入额外依赖,直接拆分原始日期字符串重新拼接即可,修改后的代码如下:

{/* 内联实现版本 */}
<Text style={styles.centerText}>
  {gameDataObject.gameDate.split('-').slice(1).concat(gameDataObject.gameDate.split('-')[0]).join('-')} @ {gameDataObject.gameStartTime && convertTime(gameDataObject.gameStartTime)}
</Text> 
</View>

如果觉得内联写可读性差,可以提前拆分变量:

// 拆分原始YYYY-MM-DD格式的日期
const [originYear, originMonth, originDay] = gameDataObject.gameDate.split('-');
const simpleFormattedDate = `${originMonth}-${originDay}-${originYear}`;

// 渲染部分
<Text style={styles.centerText}>
  {simpleFormattedDate} @ {gameDataObject.gameStartTime && convertTime(gameDataObject.gameStartTime)}
</Text> 
</View>

期望格式实现(July, 11th 2022 @ 3:00pm格式)

通过简单的辅助方法即可实现月份英文转换、日期序数词拼接、时间大小写调整,无需引入第三方日期库:

// 月份英文映射表
const monthEnNameList = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
// 计算日期对应的序数词后缀(st/nd/rd/th)
const getDateSuffix = (dayStr) => {
  const day = Number(dayStr);
  const suffixRule = ["th", "st", "nd", "rd"];
  const remainder = day % 100;
  return day + (suffixRule[(remainder - 20) % 10] || suffixRule[remainder] || suffixRule[0]);
};

// 提前处理日期和时间格式
const [targetYear, targetMonth, targetDay] = gameDataObject.gameDate.split('-');
const fullFormattedDate = `${monthEnNameList[Number(targetMonth)-1]}, ${getDateSuffix(targetDay)} ${targetYear}`;
const formattedTime = gameDataObject.gameStartTime ? convertTime(gameDataObject.gameStartTime).toLowerCase() : '';

// 渲染部分
<Text style={styles.centerText}>
  {fullFormattedDate} @ {formattedTime}
</Text> 
</View>

注:如果你的gameDate字段不是YYYY-MM-DD格式的字符串,是时间戳或者标准Date对象,只需要替换前面取年、月、日的逻辑,从Date实例上用getFullYear()、getMonth()、getDate()拿到对应字段即可,后续拼接逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 22:24:12