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

Angular中UTC时间转本地时间:保持原格式的实现方法

日期转本地对象并保留格式的解决办法

你拿到的日期格式是:

Sat Nov 18 2023 22:30:00 GMT+0530 (India Standard Time)
通过this.selectedDate = info.date;获取该时间后,需要转成本地日期时间对象,同时保持原有格式不变。

具体实现步骤:

  • 首先,info.date本身就是Date对象,直接基于它创建本地时间实例就行:
    // 获取原始日期对象
    const originalDate = info.date;
    // 自动转换为本地时区的日期对象
    this.selectedDate = new Date(originalDate);
    
  • 如果要输出和原始格式完全一致的字符串,得自己写个格式化函数来拼接:
    function formatToOriginalStyle(date) {
      const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      
      // 提取各个时间部分
      const weekday = weekdays[date.getDay()];
      const month = months[date.getMonth()];
      const day = String(date.getDate()).padStart(2, '0');
      const year = date.getFullYear();
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      // 处理时区偏移和名称
      const offset = date.getTimezoneOffset();
      const sign = offset > 0 ? '-' : '+';
      const offsetHrs = String(Math.floor(Math.abs(offset)/60)).padStart(2, '0');
      const offsetMins = String(Math.abs(offset)%60).padStart(2, '0');
      const tzName = Intl.DateTimeFormat().resolvedOptions().timeZone;
      
      return `${weekday} ${month} ${day} ${year} ${hours}:${minutes}:${seconds} GMT${sign}${offsetHrs}${offsetMins} (${tzName})`;
    }
    
    // 使用示例
    this.selectedDate = new Date(info.date);
    // 得到和原始格式一致的字符串
    const formattedStr = formatToOriginalStyle(this.selectedDate);
    
  • 划重点:如果只需要本地日期对象,直接new Date(originalDate)就搞定;如果要输出指定格式的字符串,就用上面的格式化函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:57:25