鸿蒙(HarmonyOS)中日期时间处理

本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

以下是鸿蒙(HarmonyOS)中日期时间处理(基于Date对象和@ohos.i18n),涵盖基础操作、格式化、时区转换及高级场景,附带代码示例:

一、基础日期操作

1. 创建Date对象
// 当前时间
const now = new Date();
console.log(`当前时间: ${now}`); // 输出: Mon Jul 08 2024 14:30:00 GMT+0800

// 指定日期时间
const specificDate = new Date(2024, 6, 8, 9, 30, 0); // 月份从0开始(6表示7月)
console.log(`指定时间: ${specificDate}`);

// 通过时间戳创建
const timestamp = 1720425600000; // 2024-07-08 00:00:00 UTC
const dateFromTimestamp = new Date(timestamp);

2. 获取日期组件

const date = new Date();
console.log(`年: ${date.getFullYear()}`);    // 2024
console.log(`月: ${date.getMonth() + 1}`);   // 7(需+1修正)
console.log(`日: ${date.getDate()}`);        // 8
console.log(`时: ${date.getHours()}`);       // 14
console.log(`分: ${date.getMinutes()}`);     // 30
console.log(`秒: ${date.getSeconds()}`);     // 0
console.log(`毫秒: ${date.getMilliseconds()}`);
console.log(`星期: ${date.getDay()}`);       // 1(周一)

二、日期格式化(i18n模块)

1. 基本格式化
import i18n from '@ohos.i18n';

// 获取系统Locale
const systemLocale = i18n.getSystemLanguage() + '-' + i18n.getSystemRegion();

// 创建DateTimeFormat对象
const options: Intl.DateTimeFormatOptions = {
  dateStyle: 'full',       // 完整日期(如"2024年7月8日星期一")
  timeStyle: 'medium',     // 中等时间(如"14:30:00")
  calendar: 'gregory'      // 公历
};
const formatter = new Intl.DateTimeFormat(systemLocale, options);

// 格式化输出
console.log(formatter.format(new Date())); // 示例: "2024年7月8日星期一 14:30:00"

 2. 自定义格式

const customOptions: Intl.DateTimeFormatOptions = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  hour12: false // 24小时制
};
const customFormatter = new Intl.DateTimeFormat('zh-CN', customOptions);
console.log(customFormatter.format(new Date())); // "2024/07/08 14:30"

3. 手动拼接格式化 

const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 补零
const day = date.getDate().toString().padStart(2, '0');

// 输出:2024-07-08
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate);

4. toLocaleString系列方法

const date = new Date();

// 本地化日期时间(简写)
console.log(date.toLocaleDateString()); // "2024/7/8"(中文环境)
console.log(date.toLocaleTimeString()); // "14:30:00"

// 指定语言和选项
const options = { 
  year: 'numeric', 
  month: 'long', 
  day: 'numeric' 
};
console.log(date.toLocaleString('zh-CN', options)); // "2024年7月8日"
console.log(date.toLocaleString('en-US', options)); // "July 8, 2024"

三、时区与国际化

选项键可选值示例效果
year'numeric''2-digit'"2024" 或 "24"
month'numeric''2-digit''long''short'"7"、"07"、"七月"、"7月"
day'numeric''2-digit'"8" 或 "08"
weekday'long''short''narrow'"星期一"、"周一"、"一"
hour'numeric''2-digit'"14" 或 "2 PM"
minute'numeric''2-digit'"30" 或 "05"
hour12true/false是否使用12小时制
1. 时区转换
const utcDate = new Date().toISOString(); // UTC时间
console.log(`UTC时间: ${utcDate}`); // "2024-07-08T06:30:00.000Z"

// 转换为纽约时间
const nyOptions: Intl.DateTimeFormatOptions = {
  timeZone: 'America/New_York',
  timeStyle: 'long'
};
const nyFormatter = new Intl.DateTimeFormat('en-US', nyOptions);
console.log(`纽约时间: ${nyFormatter.format(new Date())}`); // "2:30:00 AM EDT"
2. 多语言日期显示
// 英文格式
const enFormatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'full' });
console.log(enFormatter.format(new Date())); // "Monday, July 8, 2024"

// 日语格式
const jaFormatter = new Intl.DateTimeFormat('ja-JP', { 
  era: 'long', 
  year: 'numeric', 
  month: 'long', 
  day: 'numeric' 
});
console.log(jaFormatter.format(new Date())); // "令和6年7月8日"

四、日期计算与操作

1. 日期加减
// 加3天
const addDays = (date: Date, days: number): Date => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
};
console.log(addDays(new Date(), 3)); // 2024-07-11

// 减1个月
const subMonths = (date: Date, months: number): Date => {
  const result = new Date(date);
  result.setMonth(result.getMonth() - months);
  return result;
};
2. 日期比较
const date1 = new Date(2024, 6, 1);
const date2 = new Date(2024, 6, 8);

// 比较时间戳
console.log(date1 > date2); // false
console.log(date1.getTime() === date2.getTime()); // false

// 计算日期差(天)
const diffDays = Math.floor((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24));
console.log(`相差天数: ${diffDays}`); // 7

五、高级场景示例

1. 倒计时组件
@Entry
@Component
struct CountdownTimer {
  @State remainingTime: string = '00:00:00';
  private targetDate: Date = new Date(2024, 7, 1); // 8月1日

  onPageShow() {
    setInterval(() => {
      const now = new Date();
      const diffMs = this.targetDate.getTime() - now.getTime();
      
      const hours = Math.floor(diffMs / (1000 * 60 * 60));
      const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((diffMs % (1000 * 60)) / 1000);
      
      this.remainingTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }, 1000);
  }

  build() {
    Column() {
      Text('距离8月1日还剩:')
      Text(this.remainingTime)
        .fontSize(30)
    }
  }
}
2. 工作日计算
function isWeekend(date: Date): boolean {
  return date.getDay() === 0 || date.getDay() === 6;
}

function getWorkdaysBetween(start: Date, end: Date): number {
  let count = 0;
  const current = new Date(start);
  
  while (current <= end) {
    if (!isWeekend(current)) count++;
    current.setDate(current.getDate() + 1);
  }
  
  return count;
}

六、注意事项

  1. 时区陷阱getMonth()返回0-11,getDay()返回0-6(0是周日)。
  2. 性能优化:频繁操作日期时建议使用时间戳计算。
  3. 国际化:格式化前检查i18n.is24HourClock()判断系统时钟制式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值