Javascript无效日期到字符串格式

时间:2016-10-17 02:40:38

标签: javascript date

我正在尝试解析通过jSon从MySql检索的时间

类似的东西:

new Date('12:15:24').toString('h:mmtt');

但我在控制台

中一直收到无效日期

我需要做的是将24小时格式转换为12小时上午/下午,反之亦然

3 个答案:

答案 0 :(得分:2)

Date()构造函数只喜欢一组非常有限的日期格式。如果您的输入格式固定为'hh:mm:ss',则使用简单的字符串替换格式化它可能更容易:

function formatTime(time) {
  return time.replace(/(\d?\d)(:\d\d):(\d\d)/, function(_, h, m) {
    return (h > 12 ? h-12 : +h === 0 ? "12" : +h) + m + (h >= 12 ? "pm" : "am");
  });
}

console.log( formatTime('00:15:24') );
console.log( formatTime('09:15:24') );
console.log( formatTime('10:15:24') );
console.log( formatTime('11:15:24') );
console.log( formatTime('12:15:24') );
console.log( formatTime('13:15:24') );
console.log( formatTime('14:15:24') );

进一步阅读:

答案 1 :(得分:0)

我会考虑使用日期/时间操作库,例如http://momentjs.com/

您还可以通过拆分时间字符串并创建Date()对象来实现所需。示例:

var docIndex = 0;
db.url_list.find({},{"_id":1}).forEach(function(doc){
  docIndex++;
  if("5801ed58a8242ba30e8b46fa"==doc["_id"]){
    print('document position is...' + docIndex);
    return false;
  }
});

但这并不是一种操纵日期/时间的安全方法。

答案 2 :(得分:0)

最好使用moment.js像这样处理日期时间



services.AddTransient(obj => new InterceptServiceProvider().GetService(typeof(CustomerClass)) as ICustomer);

// get hours:minutes:seconds of the date 31-Jan_2016 9.31.21
console.log(moment('2016-01-31 09:30:21').format('HH:mm:ss'))

// get current hours:minutes:seconds
console.log(moment().format('HH:mm:ss')) 

// get current date-month-year hours:minutes:seconds
console.log(moment('2016-01-31 09:30:21').format('DD-MM-YYYY HH:mm:ss')) 




相关问题