【问题标题】:Get browser time format Angular获取浏览器时间格式Angular
【发布时间】:2021-05-22 05:43:31
【问题描述】:

有没有一种方法可以从 Angular 中的操作系统或浏览器获取时间格式,因为我需要以用户格式显示时间?!

我试图找到一些东西,但没有任何结果。

提前致谢!

【问题讨论】:

  • 格式是指DD.MM.YYYY?这样的字符串。还有你的最终目标是什么?
  • 是的,但是对于时间来说,例如 HH:MM:SS XM。我需要根据用户浏览器或操作系统格式在表格列中显示时间
  • 你不能可靠地做到这一点。以明确的格式显示日期要好得多。

标签: javascript angular typescript datetime datetime-format


【解决方案1】:

格式化时间的最佳方式是使用浏览器内置的Intl API

const now = new Date()

console.log(
  "American: %s \nLocal: %s \nWith Seconds: %s \nHour cycle: %s",
  new Intl.DateTimeFormat("en-US", {timeStyle: "short"}).format(now),
  new Intl.DateTimeFormat(undefined, {timeStyle: "short"}).format(now),
  new Intl.DateTimeFormat(undefined, {timeStyle: "medium"}).format(now),
  new Intl.DateTimeFormat(undefined, {timeStyle: "short"}).resolvedOptions().hourCycle
)

来自MDN

小时周期
要使用的小时周期。可能的值为“h11”、“h12”、“h23”或“h24”。

【讨论】:

  • Intl.DateTimeFormat 的输出依赖于实现,并非所有平台都完全支持。在 iPad 上,以上都没有显示时间,小时周期显示“未定义”。
  • 有一个polyfill添加对不支持的浏览器的支持
【解决方案2】:

通常时间格式取决于用户区域设置。您可以轻松获取 LOCALE_ID 然后format date

那么就可以使用js函数了:toLocaleTimeString()

最简单的方法就是用moment。

// From 2.8.1 onward
moment.locale(String);

【讨论】:

  • 这假定用户已将浏览器设置为他们的首选语言,并且浏览器完全允许此类设置。许多人不这样做,只是默认为 en-us。
猜你喜欢
  • 2012-02-14
  • 2011-09-04
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多