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

如何使用TypeScript将当前日期转换为指定格式(固定00:00:00时间)

TypeScript 实现日期格式化并固定时间为00:00:00

以下是两种实用实现方式,均可将当前日期转换为指定格式,同时强制时间部分为00:00:00:

方法一:原生Date API手动拼接

适合需要完全自定义格式细节的场景:

function formatDateWithFixedTime(): string {
  const now = new Date();
  // 将时分秒及毫秒重置为0
  now.setHours(0, 0, 0, 0);
  
  // 定义星期、月份的英文缩写/全称数组
  const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const months = ['january', 'february', 'march', 'april', 'may', 'june', 
                  'july', 'august', 'september', 'october', 'november', 'december'];
  
  const weekday = weekdays[now.getDay()];
  const date = now.getDate();
  const month = months[now.getMonth()];
  const year = now.getFullYear();
  // 获取时区缩写(如IST)
  const timeZoneAbbr = now.toLocaleTimeString('en-US', { timeZoneName: 'short' }).split(' ').pop() || '';
  
  return `${weekday} ${date} ${month} ${year} 00:00:00 ${timeZoneAbbr}`;
}

// 调用示例
console.log(formatDateWithFixedTime());
// 输出示例: Fri 22 july 2021 00:00:00 IST

方法二:使用Intl.DateTimeFormat(推荐)

利用浏览器原生国际化API,简洁且自动处理时区、本地化格式:

function formatDateWithFixedTime(): string {
  const now = new Date();
  now.setHours(0, 0, 0, 0);
  
  // 配置格式化参数
  const formatOptions: Intl.DateTimeFormatOptions = {
    weekday: 'short',
    day: 'numeric',
    month: 'long',
    year: 'numeric',
    timeZoneName: 'short',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  };
  
  // 生成带时间的完整格式,再替换为00:00:00
  const fullFormatted = now.toLocaleString('en-US', formatOptions);
  // 替换时间部分,同时去掉默认的逗号分隔符
  return fullFormatted.replace(/\d{2}:\d{2}:\d{2}/, '00:00:00').replace(/,/g, '');
}

// 调用示例
console.log(formatDateWithFixedTime());
// 输出示例: Fri July 22 2021 00:00:00 IST

额外说明

  • 时区控制:如果需要强制使用特定时区(比如固定为IST),可以在formatOptions中添加timeZone: 'Asia/Kolkata'
  • 月份大小写:如果需要月份全小写,可在格式化后调用toLowerCase()处理对应部分
  • 日期补零:若需要日期为两位数字(如05而非5),将day: 'numeric'改为day: '2-digit'即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:27:36