React应用中卡片时间显示为ISO格式的格式化需求问询
解决React预约卡片中ISO时间格式显示问题
方法一:原生JavaScript格式化(无额外依赖)
利用浏览器内置的Intl.DateTimeFormat API,直接将ISO时间转换为友好的本地格式:
修改组件中时间渲染的代码:
<Typography variant="h6">Time : {new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false // 设为true可切换为12小时制 }).format(new Date(time))}</Typography>
如果只需要显示时分,移除second配置项即可;若需要包含秒数,添加second: '2-digit'参数。
方法二:使用date-fns库(推荐复杂场景)
对于需要更多日期操作或兼容旧浏览器的场景,推荐轻量的date-fns库:
- 安装依赖:
npm install date-fns
- 在组件中导入并使用:
import { format } from 'date-fns'; import { zhCN } from 'date-fns/locale'; // 渲染时间部分 <Typography variant="h6">Time : {format(new Date(time), 'HH:mm:ss', { locale: zhCN })}</Typography>
自定义格式示例:'yyyy-MM-dd HH:mm'(显示年月日时分)、'MM/dd hh:mm a'(月/日 12小时制带AM/PM标识)。
补充:合并日期与时间字段
若date和time为分离的ISO字符串,可合并后统一格式化:
const fullDateTime = new Date(`${date}T${time}`); <Typography variant="h6">预约时间 : {format(fullDateTime, 'yyyy-MM-dd HH:mm', { locale: zhCN })}</Typography>
内容的提问来源于stack exchange,提问作者codertraveller
相关产品推荐
相关产品推荐

