简体   繁体   English

moment.js 检查系统时间格式是 12 小时还是 24 小时?

[英]moment.js check if system time format is 12 hours or 24 hours?

How to get the current system setting time format if 12 hours or 24 hours?如果是12小时还是24小时,如何获取当前系统设置的时间格式?

date.toLocaleTimeString does not work always return time in 12 hours. date.toLocaleTimeString并不总是在 12 小时内返回时间。

I need to display time on the basis of the system's time format.我需要根据系统的时间格式来显示时间。

example:例子:

  let currentDateTime = new Date();
  console.log(currentDateTime.toLocaleTimeString())

result:结果:

7:50:00 PM

I'm expecting 19:50:00 because my current system settings is 24hours format in my computer.我期待19:50:00 ,因为我当前的系统设置在我的计算机中是 24 小时格式。 see image:看图片: 在此处输入图像描述

for 24 hours you can make 12 hours false like this:对于 24 小时,您可以像这样使 12 小时为假:

 let currentDateTime = new Date(); console.log(currentDateTime.toLocaleTimeString('en-US', { hour12: false }))

A Simple approach using moment.js使用 moment.js 的简单方法

function is12HourFormat(time: string): boolean {
    return moment(time, 'hh:mm', true).isValid();
}

For 24 hour format:对于 24 小时格式:

function is24HourFormat(time: string): boolean {
    return moment(time, 'HH:mm', true).isValid();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM