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

Electron-JavaScript中如何获取当前设备的日期格式?

实现获取设备当前日期格式的getDateFormat()函数

嘿,这个需求很实用!要实现能返回当前设备日期格式的getDateFormat()函数,咱们可以利用浏览器原生的国际化API轻松搞定,它会自动适配系统的区域设置和日期偏好。下面是具体的实现方案:

核心实现代码

function getDateFormat() {
  // 初始化适配当前设备区域的日期格式化器
  const dateFormatter = new Intl.DateTimeFormat();
  // 获取格式化器实际生效的配置项
  const resolvedOpts = dateFormatter.resolvedOptions();

  // 把API返回的部件类型映射成常用的格式占位符
  const partPlaceholderMap = {
    year: resolvedOpts.year === '2-digit' ? 'YY' : 'YYYY',
    month: resolvedOpts.month === '2-digit' ? 'MM' : 'M',
    day: resolvedOpts.day === '2-digit' ? 'dd' : 'd'
  };

  // 将日期拆分为部件数组(包含日期项和分隔符)
  const dateParts = dateFormatter.formatToParts(new Date());
  // 过滤并替换部件为占位符,拼接成最终格式字符串
  const formatString = dateParts
    .filter(part => part.type !== 'literal' || ['/', '-', '.'].includes(part.value))
    .map(part => partPlaceholderMap[part.type] || part.value)
    .join('');

  return formatString;
}

// 测试示例
const currentDateFormat = getDateFormat();
console.log(currentDateFormat); // 输出如 "MM/dd/YYYY"、"dd/MM/YYYY" 或 "YYYY/MM/dd" 等

代码说明

  • Intl.DateTimeFormat:这是浏览器/Node.js原生的国际化日期格式化工具,会自动读取设备的系统区域设置(比如语言、日期格式偏好),无需手动判断。
  • resolvedOptions():用来获取格式化器实际使用的配置,比如年份是显示2位还是4位、月份是数字还是文本(我们这里只关注数字格式的部件)。
  • formatToParts():把日期拆分成一个个独立部件(比如月份数字、分隔符、日期数字、年份数字),方便我们替换成统一的占位符格式。
  • 占位符映射:根据配置把year/month/day部件转换成大家熟悉的YYYY/MM/dd这类占位符,同时保留系统默认的分隔符(比如/、-)。

兼容性说明

  • 现代浏览器(Chrome 24+、Firefox 29+、Safari 10+)都原生支持Intl.DateTimeFormat,无需额外依赖。
  • Node.js 10.0及以上版本也完全支持该API,服务器端同样可以使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:06:16