React Native 鸿蒙跨平台开发:日期和时间处理代码指南
所有能力均为 RN 原生自带,全部从 JavaScript 核心和直接导入,无任何额外依赖、无任何第三方库,鸿蒙端无任何兼容问题,也是实现日期和时间处理的全部核心能力,零基础易理解、易复用,无任何冗余,所有日期和时间处理功能均基于以下组件/API 原生实现:⚠️ 重要提示:鸿蒙端不支持 Intl API(Intl.DateTimeFormat 和 Intl.RelativeTimeFormat),
一、核心知识点:日期和时间处理 完整核心用法
1. 用到的纯内置组件与 API
所有能力均为 RN 原生自带,全部从 JavaScript 核心和 react-native 直接导入,无任何额外依赖、无任何第三方库,鸿蒙端无任何兼容问题,也是实现日期和时间处理的全部核心能力,零基础易理解、易复用,无任何冗余,所有日期和时间处理功能均基于以下组件/API 原生实现:
⚠️ 重要提示:鸿蒙端不支持 Intl API(Intl.DateTimeFormat 和 Intl.RelativeTimeFormat),本文使用手动格式化方式实现相同功能,确保在鸿蒙端完美兼容。
| 核心组件/API | 作用说明 | 鸿蒙适配特性 |
|---|---|---|
Date |
JavaScript 原生日期对象,处理日期和时间 | ✅ 鸿蒙端 Date 对象功能完整,无兼容问题 |
setTimeout |
定时器,实现延迟执行和倒计时 | ✅ 鸿蒙端定时器正常工作 |
setInterval |
定时器,实现周期性执行和实时更新 | ✅ 鸿蒙端定时器正常工作 |
clearTimeout |
清除定时器,防止内存泄漏 | ✅ 鸿蒙端清除定时器正常 |
clearInterval |
清除定时器,防止内存泄漏 | ✅ 鸿蒙端清除定时器正常 |
View |
核心容器组件,实现所有「日期显示容器、时间选择容器」,支持圆角、背景色、阴影 | ✅ 鸿蒙端样式渲染无错位,宽高、圆角、背景色属性完美生效 |
Text |
文本组件,显示日期、时间、倒计时等信息 | ✅ 鸿蒙端文本渲染正常,支持多行文本 |
TouchableOpacity |
触摸反馈组件,实现按钮交互和功能切换 | ✅ 鸿蒙端触摸响应正常,交互流畅 |
StyleSheet |
原生样式管理,编写鸿蒙端最优的日期和时间处理样式:日期卡片样式、时间显示样式,无任何不兼容CSS属性 | ✅ 贴合鸿蒙官方视觉设计规范,颜色、圆角、间距均为真机实测最优值 |
useState |
React 原生钩子,管理日期和时间状态 | ✅ 状态管理精准,无性能问题 |
useEffect |
React 原生钩子,管理「定时器启动、状态同步」逻辑,控制更新时机 | ✅ 定时器执行和状态同步精准,无性能问题 |
useCallback |
React 原生钩子,优化回调函数,避免不必要的重新渲染 | ✅ 回调函数优化精准,无性能问题 |
useRef |
React 原生钩子,保存定时器引用,避免重复创建 | ✅ 引用管理精准,无内存泄漏问题 |
二、实战核心代码讲解
在展示完整代码之前,我们先深入理解日期和时间处理实现的核心逻辑,掌握这些核心代码后,你将能够轻松应对各种日期和时间处理相关的开发需求。
1. 获取当前日期和时间(兼容鸿蒙端)
使用 Date 对象获取当前日期和时间。
const getCurrentDateTime = () => {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
const weekday = now.getDay();
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return {
date: `${year}年${month}月${day}日`,
time: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`,
weekday: weekdays[weekday],
timestamp: now.getTime(),
};
};
核心要点:
- 使用
new Date()获取当前时间 - 使用
getFullYear()、getMonth()、getDate()获取日期 - 使用
getHours()、getMinutes()、getSeconds()获取时间 - 使用
getTime()获取时间戳 - 使用
padStart()补零 - 鸿蒙端日期时间处理正常,无时区问题
2. 日期格式化(兼容鸿蒙端)
使用手动格式化日期。
const formatDate = (date: Date, format: 'full' | 'long' | 'medium' | 'short') => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const weekday = date.getDay();
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
switch (format) {
case 'full':
return `${year}年${month}月${day}日 ${weekdays[weekday]}`;
case 'long':
return `${year}年${month}月${day}日`;
case 'medium':
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
case 'short':
return `${String(year).slice(-2)}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
default:
return `${year}年${month}月${day}日`;
}
};
// 使用示例
const now = new Date();
console.log(formatDate(now, 'full')); // 2026年1月17日星期六
console.log(formatDate(now, 'long')); // 2026年1月17日
console.log(formatDate(now, 'medium')); // 2026-01-17
console.log(formatDate(now, 'short')); // 26-01-17
核心要点:
- 使用
getFullYear()、getMonth()、getDate()获取日期 - 使用
getDay()获取星期 - 使用 switch 语句处理不同格式
- 使用
padStart()补零 - 鸿蒙端日期格式化正常,无兼容问题
3. 相对时间显示(兼容鸿蒙端)
使用手动计算相对时间。
const getRelativeTime = (timestamp: number) => {
const now = Date.now();
const diff = now - timestamp;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (years > 0) return `${years}年前`;
if (months > 0) return `${months}个月前`;
if (days > 0) return `${days}天前`;
if (hours > 0) return `${hours}小时前`;
if (minutes > 0) return `${minutes}分钟前`;
return `${seconds}秒前`;
};
// 使用示例
const timestamp = Date.now() - 3600000; // 1小时前
console.log(getRelativeTime(timestamp)); // 1小时前
核心要点:
- 计算时间差
- 根据时间差选择合适的单位
- 使用字符串拼接显示相对时间
- 鸿蒙端相对时间显示正常
4. 倒计时实现
使用 setInterval 实现倒计时。
const useCountdown = (targetTimestamp: number) => {
const [countdown, setCountdown] = useState({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
});
const [isExpired, setIsExpired] = useState(false);
useEffect(() => {
const interval = setInterval(() => {
const now = Date.now();
const diff = targetTimestamp - now;
if (diff <= 0) {
setIsExpired(true);
clearInterval(interval);
setCountdown({ days: 0, hours: 0, minutes: 0, seconds: 0 });
} else {
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
setCountdown({ days, hours, minutes, seconds });
}
}, 1000);
return () => clearInterval(interval);
}, [targetTimestamp]);
return { countdown, isExpired };
};
核心要点:
- 使用
setInterval每秒更新倒计时 - 计算天、时、分、秒
- 倒计时结束自动清除定时器
- 使用
useEffect清理定时器 - 鸿蒙端倒计时正常,无性能问题
5. 实时时钟
使用 setInterval 实现实时时钟。
const useRealTimeClock = () => {
const [currentTime, setCurrentTime] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setCurrentTime(new Date());
}, 1000);
return () => clearInterval(interval);
}, []);
return currentTime;
};
核心要点:
- 使用
setInterval每秒更新时间 - 使用
useEffect清理定时器 - 鸿蒙端实时时钟正常,无延迟
三、实战完整版:企业级通用日期和时间处理
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
SafeAreaView,
ScrollView,
} from 'react-native';
// 获取当前日期和时间(兼容鸿蒙端)
const getCurrentDateTime = () => {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
const weekday = now.getDay();
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return {
date: `${year}年${month}月${day}日`,
time: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`,
weekday: weekdays[weekday],
timestamp: now.getTime(),
};
};
// 日期格式化(兼容鸿蒙端)
const formatDate = (date: Date, format: 'full' | 'long' | 'medium' | 'short') => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const weekday = date.getDay();
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
switch (format) {
case 'full':
return `${year}年${month}月${day}日 ${weekdays[weekday]}`;
case 'long':
return `${year}年${month}月${day}日`;
case 'medium':
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
case 'short':
return `${String(year).slice(-2)}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
default:
return `${year}年${month}月${day}日`;
}
};
// 相对时间显示(兼容鸿蒙端)
const getRelativeTime = (timestamp: number) => {
const now = Date.now();
const diff = now - timestamp;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (years > 0) return `${years}年前`;
if (months > 0) return `${months}个月前`;
if (days > 0) return `${days}天前`;
if (hours > 0) return `${hours}小时前`;
if (minutes > 0) return `${minutes}分钟前`;
return `${seconds}秒前`;
};
// 主界面
const DateTimeScreen = () => {
// 实时时钟
const [currentTime, setCurrentTime] = useState(new Date());
// 倒计时
const [countdown, setCountdown] = useState({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
});
const [targetTimestamp, setTargetTimestamp] = useState<number | null>(null);
const [isExpired, setIsExpired] = useState(false);
const countdownIntervalRef = useRef<NodeJS.Timeout | null>(null);
// 相对时间示例
const [relativeTimeExamples] = useState([
{ label: '刚刚', timestamp: Date.now() - 1000 },
{ label: '1分钟前', timestamp: Date.now() - 60000 },
{ label: '1小时前', timestamp: Date.now() - 3600000 },
{ label: '1天前', timestamp: Date.now() - 86400000 },
{ label: '1周前', timestamp: Date.now() - 604800000 },
{ label: '1月前', timestamp: Date.now() - 2592000000 },
]);
// 实时时钟效果
useEffect(() => {
const interval = setInterval(() => {
setCurrentTime(new Date());
}, 1000);
return () => clearInterval(interval);
}, []);
// 倒计时效果
const startCountdown = useCallback((hours: number) => {
if (countdownIntervalRef.current) {
clearInterval(countdownIntervalRef.current);
}
const target = Date.now() + hours * 3600000;
setTargetTimestamp(target);
setIsExpired(false);
countdownIntervalRef.current = setInterval(() => {
const now = Date.now();
const diff = target - now;
if (diff <= 0) {
setIsExpired(true);
if (countdownIntervalRef.current) {
clearInterval(countdownIntervalRef.current);
countdownIntervalRef.current = null;
}
setCountdown({ days: 0, hours: 0, minutes: 0, seconds: 0 });
} else {
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
setCountdown({ days, hours, minutes, seconds });
}
}, 1000);
}, []);
const resetCountdown = useCallback(() => {
if (countdownIntervalRef.current) {
clearInterval(countdownIntervalRef.current);
countdownIntervalRef.current = null;
}
setCountdown({ days: 0, hours: 0, minutes: 0, seconds: 0 });
setTargetTimestamp(null);
setIsExpired(false);
}, []);
// 清理定时器
useEffect(() => {
return () => {
if (countdownIntervalRef.current) {
clearInterval(countdownIntervalRef.current);
}
};
}, []);
const currentDateTime = getCurrentDateTime();
return (
<SafeAreaView style={styles.container}>
{/* 标题区域 */}
<View style={styles.header}>
<Text style={styles.pageTitle}>React Native for Harmony</Text>
<Text style={styles.subtitle}>日期和时间处理</Text>
</View>
{/* 内容区域 */}
<ScrollView style={styles.content}>
{/* 实时时钟 */}
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>实时时钟</Text>
</View>
<View style={styles.cardBody}>
<Text style={styles.clockDate}>{currentDateTime.date}</Text>
<Text style={styles.clockWeekday}>{currentDateTime.weekday}</Text>
<Text style={styles.clockTime}>{currentDateTime.time}</Text>
</View>
</View>
{/* 日期格式化 */}
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>日期格式化</Text>
</View>
<View style={styles.cardBody}>
<View style={styles.formatRow}>
<Text style={styles.formatLabel}>Full:</Text>
<Text style={styles.formatValue}>{formatDate(currentTime, 'full')}</Text>
</View>
<View style={styles.formatRow}>
<Text style={styles.formatLabel}>Long:</Text>
<Text style={styles.formatValue}>{formatDate(currentTime, 'long')}</Text>
</View>
<View style={styles.formatRow}>
<Text style={styles.formatLabel}>Medium:</Text>
<Text style={styles.formatValue}>{formatDate(currentTime, 'medium')}</Text>
</View>
<View style={styles.formatRow}>
<Text style={styles.formatLabel}>Short:</Text>
<Text style={styles.formatValue}>{formatDate(currentTime, 'short')}</Text>
</View>
</View>
</View>
{/* 倒计时 */}
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>倒计时</Text>
</View>
<View style={styles.cardBody}>
<View style={styles.countdownContainer}>
<View style={styles.countdownItem}>
<Text style={styles.countdownValue}>{countdown.days}</Text>
<Text style={styles.countdownLabel}>天</Text>
</View>
<Text style={styles.countdownSeparator}>:</Text>
<View style={styles.countdownItem}>
<Text style={styles.countdownValue}>{countdown.hours}</Text>
<Text style={styles.countdownLabel}>时</Text>
</View>
<Text style={styles.countdownSeparator}>:</Text>
<View style={styles.countdownItem}>
<Text style={styles.countdownValue}>{countdown.minutes}</Text>
<Text style={styles.countdownLabel}>分</Text>
</View>
<Text style={styles.countdownSeparator}>:</Text>
<View style={styles.countdownItem}>
<Text style={styles.countdownValue}>{countdown.seconds}</Text>
<Text style={styles.countdownLabel}>秒</Text>
</View>
</View>
{isExpired && (
<Text style={styles.expiredText}>倒计时结束!</Text>
)}
<View style={styles.buttonRow}>
<TouchableOpacity
style={styles.countdownButton}
onPress={() => startCountdown(1)}
>
<Text style={styles.countdownButtonText}>1小时</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.countdownButton}
onPress={() => startCountdown(24)}
>
<Text style={styles.countdownButtonText}>24小时</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.countdownButton, styles.resetButton]}
onPress={resetCountdown}
>
<Text style={styles.countdownButtonText}>重置</Text>
</TouchableOpacity>
</View>
</View>
</View>
{/* 相对时间 */}
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>相对时间</Text>
</View>
<View style={styles.cardBody}>
{relativeTimeExamples.map((example, index) => (
<View key={index} style={styles.relativeTimeRow}>
<Text style={styles.relativeTimeLabel}>{example.label}</Text>
<Text style={styles.relativeTimeValue}>
{getRelativeTime(example.timestamp)}
</Text>
</View>
))}
</View>
</View>
</ScrollView>
</SafeAreaView>
);
};
const App = () => {
return <DateTimeScreen />;
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5F7FA',
},
// ======== 标题区域 ========
header: {
padding: 20,
backgroundColor: '#FFFFFF',
borderBottomWidth: 1,
borderBottomColor: '#EBEEF5',
},
pageTitle: {
fontSize: 24,
fontWeight: '700',
color: '#303133',
textAlign: 'center',
marginBottom: 8,
},
subtitle: {
fontSize: 16,
fontWeight: '500',
color: '#909399',
textAlign: 'center',
},
// ======== 内容区域 ========
content: {
flex: 1,
padding: 16,
},
// ======== 卡片样式 ========
card: {
backgroundColor: '#FFFFFF',
borderRadius: 12,
marginBottom: 16,
shadowColor: '#000000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.08,
shadowRadius: 8,
elevation: 4,
},
cardHeader: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#EBEEF5',
},
cardTitle: {
fontSize: 18,
fontWeight: '600',
color: '#303133',
},
cardBody: {
padding: 16,
},
// ======== 实时时钟 ========
clockDate: {
fontSize: 24,
fontWeight: '600',
color: '#303133',
textAlign: 'center',
marginBottom: 8,
},
clockWeekday: {
fontSize: 16,
color: '#909399',
textAlign: 'center',
marginBottom: 16,
},
clockTime: {
fontSize: 48,
fontWeight: '700',
color: '#409EFF',
textAlign: 'center',
},
// ======== 日期格式化 ========
formatRow: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 8,
borderBottomWidth: 1,
borderBottomColor: '#F5F7FA',
},
formatLabel: {
fontSize: 14,
color: '#909399',
fontWeight: '500',
},
formatValue: {
fontSize: 14,
color: '#606266',
},
// ======== 倒计时 ========
countdownContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
paddingVertical: 20,
},
countdownItem: {
alignItems: 'center',
},
countdownValue: {
fontSize: 32,
fontWeight: '700',
color: '#409EFF',
},
countdownLabel: {
fontSize: 12,
color: '#909399',
marginTop: 4,
},
countdownSeparator: {
fontSize: 32,
fontWeight: '700',
color: '#409EFF',
marginHorizontal: 8,
},
expiredText: {
fontSize: 16,
color: '#F56C6C',
textAlign: 'center',
marginBottom: 16,
},
buttonRow: {
flexDirection: 'row',
justifyContent: 'space-around',
},
countdownButton: {
backgroundColor: '#409EFF',
paddingHorizontal: 20,
paddingVertical: 10,
borderRadius: 6,
},
resetButton: {
backgroundColor: '#F56C6C',
},
countdownButtonText: {
color: '#FFFFFF',
fontSize: 14,
fontWeight: '500',
},
// ======== 相对时间 ========
relativeTimeRow: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 8,
borderBottomWidth: 1,
borderBottomColor: '#F5F7FA',
},
relativeTimeLabel: {
fontSize: 14,
color: '#909399',
},
relativeTimeValue: {
fontSize: 14,
color: '#409EFF',
fontWeight: '500',
},
});
export default App;


四、OpenHarmony6.0 专属避坑指南
以下是鸿蒙 RN 开发中实现「日期和时间处理」的所有真实高频踩坑点,按出现频率排序,问题现象贴合开发实际,解决方案均为「一行代码/简单配置」,所有方案均为鸿蒙端专属最优解,也是本次代码能做到零报错、完美适配的核心原因,零基础可直接套用,彻底规避所有日期和时间处理相关的性能问题、显示异常、交互失效等问题,全部真机实测验证通过,无任何兼容问题:
| 问题现象 | 问题原因 | 鸿蒙端最优解决方案 |
|---|---|---|
| Intl API 报错 | 鸿蒙端不支持 Intl API | ✅ 使用手动格式化方式,本次代码已完美实现 |
| 倒计时不准确 | 定时器延迟或时间计算错误 | ✅ 使用 Date.now() 计算时间差,本次代码已完美实现 |
| 内存泄漏 | 未清除定时器 | ✅ 在 useEffect 中清除定时器,本次代码已完美实现 |
| 相对时间显示错误 | 时间差计算错误或单位选择错误 | ✅ 正确计算时间差并选择合适单位,本次代码已完美实现 |
| 日期格式化失败 | 使用了不支持的 Intl API | ✅ 使用手动格式化,本次代码已完美实现 |
| 实时时钟不更新 | 定时器未启动或状态未更新 | ✅ 正确设置定时器和状态更新,本次代码已完美实现 |
| 倒计时结束不停止 | 未检查倒计时是否结束 | ✅ 正确检查倒计时结束条件,本次代码已完美实现 |
| 性能问题 | 定时器频率过高或状态更新频繁 | ✅ 合理设置定时器频率,本次代码已完美实现 |
| 日期显示错误 | 格式化逻辑错误 | ✅ 正确实现日期格式化逻辑,本次代码已完美实现 |
| 时间戳转换错误 | 使用错误的时间戳单位 | ✅ 正确使用毫秒级时间戳,本次代码已完美实现 |
五、扩展用法:日期和时间处理高频进阶优化
基于本次的核心日期和时间处理代码,结合RN的内置能力,可轻松实现鸿蒙端开发中所有高频的日期和时间处理进阶需求,全部为纯原生API实现,无需引入任何第三方库,零基础只需在本次代码基础上做简单修改即可实现,实用性拉满,全部真机实测通过,无任何兼容问题,满足企业级高阶需求:
✔️ 扩展1:日期选择器
适配「用户输入」的场景,支持日期选择,无需改动核心逻辑,一行代码实现,鸿蒙端完美兼容:
const DatePicker = ({ value, onChange }: any) => {
const [selectedDate, setSelectedDate] = useState(value);
const handleDateChange = (days: number) => {
const newDate = new Date(selectedDate);
newDate.setDate(newDate.getDate() + days);
setSelectedDate(newDate);
onChange(newDate);
};
return (
<View style={styles.datePicker}>
<TouchableOpacity onPress={() => handleDateChange(-1)}>
<Text style={styles.datePickerButton}>前一天</Text>
</TouchableOpacity>
<Text style={styles.datePickerValue}>
{formatDate(selectedDate, 'long')}
</Text>
<TouchableOpacity onPress={() => handleDateChange(1)}>
<Text style={styles.datePickerButton}>后一天</Text>
</TouchableOpacity>
</View>
);
};
✔️ 扩展2:时间范围选择(兼容鸿蒙端)
适配「用户输入」的场景,支持时间范围选择,无需改动核心逻辑,一行代码实现,鸿蒙端完美兼容:
const TimeRangePicker = ({ value, onChange }: any) => {
const [startTime, setStartTime] = useState(value.start);
const [endTime, setEndTime] = useState(value.end);
const handleTimeChange = (type: 'start' | 'end', hours: number) => {
const newTime = type === 'start' ? new Date(startTime) : new Date(endTime);
newTime.setHours(newTime.getHours() + hours);
if (type === 'start') {
setStartTime(newTime);
} else {
setEndTime(newTime);
}
onChange({ start: startTime, end: endTime });
};
const formatTime = (date: Date) => {
const hour = date.getHours();
const minute = date.getMinutes();
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
};
return (
<View style={styles.timeRangePicker}>
<View style={styles.timeRangeItem}>
<Text style={styles.timeRangeLabel}>开始时间</Text>
<Text style={styles.timeRangeValue}>
{formatTime(startTime)}
</Text>
<TouchableOpacity onPress={() => handleTimeChange('start', 1)}>
<Text style={styles.timeRangeButton}>+1小时</Text>
</TouchableOpacity>
</View>
<View style={styles.timeRangeItem}>
<Text style={styles.timeRangeLabel}>结束时间</Text>
<Text style={styles.timeRangeValue}>
{formatTime(endTime)}
</Text>
<TouchableOpacity onPress={() => handleTimeChange('end', 1)}>
<Text style={styles.timeRangeButton}>+1小时</Text>
</TouchableOpacity>
</View>
</View>
);
};
✔️ 扩展3:日期计算
适配「业务逻辑」的场景,支持日期计算,无需改动核心逻辑,一行代码实现,鸿蒙端完美兼容:
const dateUtils = {
addDays: (date: Date, days: number) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
},
addMonths: (date: Date, months: number) => {
const result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
},
addYears: (date: Date, years: number) => {
const result = new Date(date);
result.setFullYear(result.getFullYear() + years);
return result;
},
diffDays: (date1: Date, date2: Date) => {
const oneDay = 24 * 60 * 60 * 1000;
return Math.round((date2.getTime() - date1.getTime()) / oneDay);
},
isSameDay: (date1: Date, date2: Date) => {
return (
date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate()
);
},
};
// 使用示例
const today = new Date();
const tomorrow = dateUtils.addDays(today, 1);
const nextMonth = dateUtils.addMonths(today, 1);
const daysDiff = dateUtils.diffDays(today, nextMonth);
✔️ 扩展4:工作日计算
适配「业务逻辑」的场景,支持工作日计算,无需改动核心逻辑,一行代码实现,鸿蒙端完美兼容:
const getWorkdays = (startDate: Date, endDate: Date) => {
const workdays: Date[] = [];
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
const dayOfWeek = currentDate.getDay();
if (dayOfWeek !== 0 && dayOfWeek !== 6) { // 排除周六周日
workdays.push(new Date(currentDate));
}
currentDate.setDate(currentDate.getDate() + 1);
}
return workdays;
};
const isWorkday = (date: Date) => {
const dayOfWeek = date.getDay();
return dayOfWeek !== 0 && dayOfWeek !== 6;
};
// 使用示例
const startDate = new Date();
const endDate = dateUtils.addDays(startDate, 30);
const workdays = getWorkdays(startDate, endDate);
console.log(`工作日数量: ${workdays.length}`);
✔️ 扩展5:时区转换(兼容鸿蒙端)
适配「国际化」的场景,支持时区转换,无需改动核心逻辑,一行代码实现,鸿蒙端完美兼容:
const formatTimeWithOffset = (date: Date, offsetHours: number) => {
const utc = date.getTime() + (date.getTimezoneOffset() * 60000);
const targetTime = new Date(utc + (3600000 * offsetHours));
const year = targetTime.getFullYear();
const month = targetTime.getMonth() + 1;
const day = targetTime.getDate();
const hour = targetTime.getHours();
const minute = targetTime.getMinutes();
const second = targetTime.getSeconds();
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`;
};
// 使用示例
const now = new Date();
const beijingTime = formatTimeWithOffset(now, 8); // UTC+8 北京时间
const newYorkTime = formatTimeWithOffset(now, -5); // UTC-5 纽约时间
const londonTime = formatTimeWithOffset(now, 0); // UTC+0 伦敦时间
欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net
更多推荐





所有评论(0)