在JavaScript中将军事时间转换为标准时间的最佳方法

10
什么是将军时间转换为上午和下午时间的最佳方法。我有以下代码,它运行良好:
$scope.convertTimeAMPM = function(time){
//var time = "12:23:39";
var time = time.split(':');
var hours = time[0];
var minutes = time[1];
var seconds = time[2];
$scope.timeValue = "" + ((hours >12) ? hours -12 :hours);
    $scope.timeValue += (minutes < 10) ? ":0" : ":" + minutes;
    $scope.timeValue += (seconds < 10) ? ":0" : ":" + seconds;
    $scope.timeValue += (hours >= 12) ? " P.M." : " A.M.";
    //console.log( timeValue);
}

但是当我运行程序时,输出结果并没有让我满意。

样例输出:

20:00:00   8:0:0 P.M.
08:00:00   08:0:0 A.M
16:00:00   4:30:0 P.M.

我希望实现以下类似的输出:
```html

我想要达到以下输出结果:

```
20:00:00   8:00:00 P.M.
08:00:00   8:00:00 A.M
16:30:00   4:30:00 P.M.

那里是否有任何建议?谢谢


2
FYI:军用时间格式 - CSᵠ
8个回答

18

你错过了字符串连接操作,因为当minutes < 10seconds < 10时,你没有得到所需的结果。

使用Number()将字符串转换成数字,并像下面的工作代码片段中所示适当使用它:

编辑:更新代码,在声明hoursminutesseconds时使用Number()

var time = "16:30:00"; // your input

time = time.split(':'); // convert to array

// fetch
var hours = Number(time[0]);
var minutes = Number(time[1]);
var seconds = Number(time[2]);

// calculate
var timeValue;

if (hours > 0 && hours <= 12) {
  timeValue= "" + hours;
} else if (hours > 12) {
  timeValue= "" + (hours - 12);
} else if (hours == 0) {
  timeValue= "12";
}
 
timeValue += (minutes < 10) ? ":0" + minutes : ":" + minutes;  // get minutes
timeValue += (seconds < 10) ? ":0" + seconds : ":" + seconds;  // get seconds
timeValue += (hours >= 12) ? " P.M." : " A.M.";  // get AM/PM

// show
alert(timeValue);
console.log(timeValue);

阅读:Number() | MDN


1
如何从函数中返回时间?我尝试使用return timeValue;但它不起作用; - Web.11
@Web.11 请详细说明您的问题,如果您能提供代码片段的链接,我可以更好地帮助您。 - Rahul Desai

11
根据 Nit 的建议,Moment.js 提供了一个简单的解决方案来解决您的问题。
function convert(input) {
    return moment(input, 'HH:mm:ss').format('h:mm:ss A');
}

console.log(convert('20:00:00'));
console.log(convert('08:00:00'));
console.log(convert('16:30:00'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>


1
一个使用moment.js的观察结果是 - 如果格式化很多这样的内容(即> 75),您的性能会受到影响。我观察到大约需要500毫秒来进行大约75次转换。我实施了Rahul Desai的答案,以缩短我的时间0.5秒。 - aero

2

作为对Huy Hoang Pham答案的扩展,这是使用Luxon而不是moment.js的代码(请参见此处此处)。

import { DateTime }  from "luxon";

function convert(input) {
    return DateTime.fromFormat(input, 'HH:mm:ss').toFormat('h:mm:ss A');
}

console.log(convert('20:00:00'));
console.log(convert('08:00:00'));
console.log(convert('16:30:00'));

时间是复杂的,我建议在进行此类转换时使用库而不是自己编写代码。


1

不需要使用库

这是一个我编写的简单而实用的函数,应该完全符合您的需求

function toStandardTime(militaryTime) {
    militaryTime = militaryTime.split(':');
    return (militaryTime[0].charAt(0) == 1 && militaryTime[0].charAt(1) > 2) ? (militaryTime[0] - 12) + ':' + militaryTime[1] + ':' + militaryTime[2] + ' P.M.' : militaryTime.join(':') + ' A.M.'
}

console.log(toStandardTime('16:30:00'));

如果需要,这是更易读的版本

function toStandardTime(militaryTime) {
  militaryTime = militaryTime.split(':');
  if (militaryTime[0].charAt(0) == 1 && militaryTime[0].charAt(1) > 2) {
    return (militaryTime[0] - 12) + ':' + militaryTime[1] + ':' + militaryTime[2] + ' P.M.';
  } else {
    return militaryTime.join(':') + ' A.M.';
  }
}

console.log(toStandardTime('16:30:00'));


1
虽然这可能是一个“简单而甜美”的函数,但它提醒了我们为什么要使用日期计算库。你的函数只能在输入匹配格式"16:30:00"时才能工作。例如,如果你传入"16:30",它就不能工作。 - Tyler Kemme
2
这就是OP所要求的。 - Arlo

1
使用ES6的一种简洁方式如下所示:
toRegularTime = (militaryTime) => {
    const [hours, minutes, seconds] = militaryTime.split(':');
    return `${(hours > 12) ? hours - 12 : hours}:${minutes}${seconds ? `:${seconds}` : ''} ${(hours >= 12) ? 'PM' : 'AM'}`;
}

1
这对于“00:00”无效,它只会输出“00:00 AM”,而不是“12:00 AM”,因此您需要在其中添加另一个if来检查零小时。另外,我喜欢可选秒的功能。 - RcoderNY

0

0
这个作为辅助函数怎么样?

let convertMilitaryToStandard = function(time) {
  let timeParts = time.split(":");
  let standardTime = "";

  if (parseInt(timeParts[0]) > 12) {
    timeParts[0] = timeParts[0] - 12;
    standardTime = timeParts.join(":") + " PM";
  } else if (parseInt(timeParts[0]) === 12) {
    standardTime = timeParts.join(":") + " PM";
  } else {
    standardTime = timeParts.join(":") + " AM";
  }

  return standardTime;
}

console.log(convertMilitaryToStandard("12:15:12"));
console.log(convertMilitaryToStandard("01:15:12"));
console.log(convertMilitaryToStandard("18:15"));


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community
为了去掉时间的前导零const convertMilitaryToStandard = (time) => { let timeParts = time.split(":"); let standardTime = ""; if (parseInt(timeParts[0]) > 12) { timeParts[0] = timeParts[0] - 12; standardTime = timeParts.join(":") + " PM"; } else if (parseInt(timeParts[0]) === 12) { standardTime = timeParts.join(":") + " PM"; } else { if (timeParts[0].startsWith("0")) { timeParts[0] = timeParts[0].substring(1); } standardTime = timeParts.join(":") + " AM"; } return standardTime; }; - undefined

0
const parseMillitaryTime = (time: string) =>
    pipe(
      time,
      s => s.split(':'),
      time_ =>
        `${((Number(time_[0]) + 11) % 12) + 1}:${
          Number(time_[1]) < 10 ? `0${Number(time_[1])}` : `${Number(time_[1])}`
        } ${Number(time_[0]) > 11 ? 'pm' : 'am'}`
    )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接