如何将选定时隙数组格式化为格式化字符串

时间:2016-08-25 13:04:44

标签: javascript jquery momentjs

我正在使用一个调度系统,用户可以在一天中选择半小时的时间段,其中所选的时隙数组看起来像这样:

['12:30', '13:00', '16:00', '16:30', '18:00']

我想在格式良好的输出中向用户显示此内容,理想情况如下:

"12:30pm - 1:30pm, 4:00pm - 5:00pm, 6:00pm - 6:30pm"

我可以处理24小时到12小时的转换,但我无法解决如何格式化时间范围并将它们分组,如果他们连续半小时的时段。

我使用的是moment.js,但如果需要,我可以使用其他插件。

编辑: 如果选择单个非连续时隙,例如18:00,则基于半小时间隔的输出应为"下午6:00-下午6:30"。

1 个答案:

答案 0 :(得分:4)

您需要先parse日期,然后使用.format()方法将其转换为所需的格式。

var app=angular.module('xpCalc', []);
app.controller('Xp Calculator', function($scope){
$scope.currentLevel;
$scope.currentXp=function(){
    var output=0;
    for (var thisLVL =1; thisLVL >= $scope.currentLevel; thisLVL++) {
        return output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
    }}});
var arr = ['12:30', '13:00', '16:00', '16:30'];
var newArr = arr.map(function(dt) {
  return moment(dt, 'HH:mm').format('hh:mmA');
})

//Example, However it will not work if newArr is length of 3, 5
var nArr = [];
for (var i = 0; i < newArr.length; i += 2) {
  nArr.push(newArr[i] + ' ' + newArr[i + 1])
}

console.log(nArr)