本文介绍了将HH:mm am / pm的时间字符串更改为24小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 8:45 am 如果是,是pm,将其转换为24小时。所以我可以放弃am / pm并使用它与其他东西。 我可以很容易地像下面那样放下/ pm: function replaceEnds(string){ string = string.replace(am,); string = string.replace(pm,); 返回字符串; } 但当然如果我这样做,我不知道字符串是am或pm,所以我不知道添加12个小时的字符串,使它24小时。 任何人都知道我如何解决这个问题?我绝对不能改变我得到变量的输入,它总是小时(12小时),分钟,am或pm。解决方案使用 moment.js : 如果你想手动执行,这将是我的解决方案: 函数to24Hour(str){ var tokens = /([10]?\d):([0-5] \d )([ap] m)/i.exec(str); if(tokens == null){return null; } if(tokens [3] .toLowerCase()==='pm'&&&&& Tokk [1]!=='12'){ tokens [1] =''+ 12 +(+标记[1])); } else if(tokens [3] .toLowerCase()==='am'&&&& Tokk [1] ==='12'){ tokens [1] ='00' ; } return tokens [1] +':'+ tokens [2]; } 手动解决方案难以理解,灵活性较差,缺少一些错误检查并需要单元测试。一般来说,您通常应该喜欢受过良好考试的流行图书馆解决方案,而不是您自己的解决方案(如果经过良好测试的库可用)。 I get a variable string like so:8:45 amAnd want, if it is pm, to convert it to 24 hour time. So that I can then drop the am/pm and use it with something else.I can drop the am/pm quite easily like this:function replaceEnds(string) { string = string.replace("am", ""); string = string.replace("pm", ""); return string; }But of course if I do that, I don't know if the string is am or pm, so I don't know to add 12 hours on to the string to make it 24 hour.Anyone know how I could resolve this? I absolutely cannot change the input that I get of the variable, it'll always be the hour (in 12 hour time), minutes, and am or pm. 解决方案 Using moment.js:moment(string, 'h:mm a').format('H:mm');If you want to do it manually, this would be my solution:function to24Hour(str) { var tokens = /([10]?\d):([0-5]\d) ([ap]m)/i.exec(str); if (tokens == null) { return null; } if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') { tokens[1] = '' + (12 + (+tokens[1])); } else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') { tokens[1] = '00'; } return tokens[1] + ':' + tokens[2];}The manual solution is harder to understand, is less flexible, is missing some error checking and needs unit tests. In general, you should usually prefer a well-tested popular library's solution, rather than your own (if a well-tested library is available). 这篇关于将HH:mm am / pm的时间字符串更改为24小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-16 02:11