在 Javascript 中将用户输入的时间解析为 Date 对象的最佳方法是什么?
-
02-07-2019 - |
题
我正在开发一个表单小部件,供用户在文本输入中输入一天中的时间(对于日历应用程序)。使用 JavaScript(我们使用 jQuery FWIW),我想找到解析用户输入 JavaScript 的文本的最佳方法 Date()
对象,这样我就可以轻松地对其进行比较和其他操作。
我尝试过 parse()
方法,对于我的需求来说有点太挑剔了。我希望它能够成功解析以下示例输入时间(除了其他逻辑上相似的时间格式之外)。 Date()
目的:
- 1:00 PM
- 1:00 PM。
- 下午 1:00
- 1:00 PM
- 1:00 PM。
- 1:00p
- 下午 1 点
- 下午 1 点
- 1 p
- 下午 1 点
- 下午 1 点
- 1p
- 13:00
- 13
我想我可以使用正则表达式来分割输入并提取我想要用来创建我的信息 Date()
目的。做这个的最好方式是什么?
解决方案
适用于您指定的输入的快速解决方案:
function parseTime( t ) {
var d = new Date();
var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ );
d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) );
d.setMinutes( parseInt( time[2]) || 0 );
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
它应该也适用于其他一些品种(即使是上午)。使用后,它仍然可以工作 - 例如)。显然,这是相当粗糙的,但它也非常轻量级(例如,使用它比使用完整的库便宜得多)。
警告:该代码不适用于 12:00 AM 等。
其他提示
提供的所有示例在上午 12:00 到 12:59 之间都无法工作。如果正则表达式与时间不匹配,它们也会抛出错误。以下处理这个:
function parseTime(timeString) {
if (timeString == '') return null;
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i);
if (time == null) return null;
var hours = parseInt(time[1],10);
if (hours == 12 && !time[4]) {
hours = 0;
}
else {
hours += (hours < 12 && time[4])? 12 : 0;
}
var d = new Date();
d.setHours(hours);
d.setMinutes(parseInt(time[3],10) || 0);
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
这适用于其中包含时间的字符串。因此“abcde12:00pmdef”将被解析并返回中午 12 点。如果所需的结果是它仅返回字符串中仅包含时间的时间,则可以使用以下正则表达式,前提是将“time[4]”替换为“time[6]”。
/^(\d+)(:(\d\d))?\s*((a|(p))m?)?$/i
不用费心自己做,直接使用 日期js.
当无法解析字符串时,这里的大多数正则表达式解决方案都会抛出错误,并且其中没有多少解决方案可以解释像这样的字符串 1330
或者 130pm
. 。尽管OP没有指定这些格式,但我发现它们对于解析人类输入的日期至关重要。
所有这些让我想到使用正则表达式可能不是最好的方法。
我的解决方案是一个函数,它不仅可以解析时间,还允许您指定输出格式和舍入分钟的步骤(间隔)。它大约有 70 行,仍然是轻量级的,可以解析所有上述格式以及不带冒号的格式。
function parseTime(time, format, step) {
var hour, minute, stepMinute,
defaultFormat = 'g:ia',
pm = time.match(/p/i) !== null,
num = time.replace(/[^0-9]/g, '');
// Parse for hour and minute
switch(num.length) {
case 4:
hour = parseInt(num[0] + num[1], 10);
minute = parseInt(num[2] + num[3], 10);
break;
case 3:
hour = parseInt(num[0], 10);
minute = parseInt(num[1] + num[2], 10);
break;
case 2:
case 1:
hour = parseInt(num[0] + (num[1] || ''), 10);
minute = 0;
break;
default:
return '';
}
// Make sure hour is in 24 hour format
if( pm === true && hour > 0 && hour < 12 ) hour += 12;
// Force pm for hours between 13:00 and 23:00
if( hour >= 13 && hour <= 23 ) pm = true;
// Handle step
if( step ) {
// Step to the nearest hour requires 60, not 0
if( step === 0 ) step = 60;
// Round to nearest step
stepMinute = (Math.round(minute / step) * step) % 60;
// Do we need to round the hour up?
if( stepMinute === 0 && minute >= 30 ) {
hour++;
// Do we need to switch am/pm?
if( hour === 12 || hour === 24 ) pm = !pm;
}
minute = stepMinute;
}
// Keep within range
if( hour <= 0 || hour >= 24 ) hour = 0;
if( minute < 0 || minute > 59 ) minute = 0;
// Format output
return (format || defaultFormat)
// 12 hour without leading 0
.replace(/g/g, hour === 0 ? '12' : 'g')
.replace(/g/g, hour > 12 ? hour - 12 : hour)
// 24 hour without leading 0
.replace(/G/g, hour)
// 12 hour with leading 0
.replace(/h/g, hour.toString().length > 1 ? (hour > 12 ? hour - 12 : hour) : '0' + (hour > 12 ? hour - 12 : hour))
// 24 hour with leading 0
.replace(/H/g, hour.toString().length > 1 ? hour : '0' + hour)
// minutes with leading zero
.replace(/i/g, minute.toString().length > 1 ? minute : '0' + minute)
// simulate seconds
.replace(/s/g, '00')
// lowercase am/pm
.replace(/a/g, pm ? 'pm' : 'am')
// lowercase am/pm
.replace(/A/g, pm ? 'PM' : 'AM');
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
这里有一个改进 乔的版本. 。请随意进一步编辑。
function parseTime(timeString)
{
if (timeString == '') return null;
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i);
d.setHours( parseInt(time[1],10) + ( ( parseInt(time[1],10) < 12 && time[4] ) ? 12 : 0) );
d.setMinutes( parseInt(time[3],10) || 0 );
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
变化:
- 向 parseInt() 调用添加了 radix 参数(因此 jslint 不会抱怨)。
- 使正则表达式不区分大小写,因此“2:23 PM”的工作方式类似于“2:23 pm”
我在实施 John Resig 的解决方案时遇到了一些问题。这是我根据他的回答使用的修改后的函数:
function parseTime(timeString)
{
if (timeString == '') return null;
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/);
d.setHours( parseInt(time[1]) + ( ( parseInt(time[1]) < 12 && time[4] ) ? 12 : 0) );
d.setMinutes( parseInt(time[3]) || 0 );
d.setSeconds(0, 0);
return d;
} // parseTime()
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
AnyTime.Converter 可以解析多种不同格式的日期/时间:
这 时间 包大小为 0.9kbs。可与 NPM 和 Bower 包管理器一起使用。
这是直接来自的示例 README.md
:
var t = Time('2p');
t.hours(); // 2
t.minutes(); // 0
t.period(); // 'pm'
t.toString(); // '2:00 pm'
t.nextDate(); // Sep 10 2:00 (assuming it is 1 o'clock Sep 10)
t.format('hh:mm AM') // '02:00 PM'
t.isValid(); // true
Time.isValid('99:12'); // false
这是一种更坚固的方法,考虑了用户打算如何使用此类输入。例如,如果用户输入“12”,他们会期望这是中午 12 点(中午),而不是上午 12 点。下面的函数处理所有这些。也可以在这里找到: http://blog.de-zwart.net/2010-02/javascript-parse-time/
/**
* Parse a string that looks like time and return a date object.
* @return Date object on success, false on error.
*/
String.prototype.parseTime = function() {
// trim it and reverse it so that the minutes will always be greedy first:
var value = this.trim().reverse();
// We need to reverse the string to match the minutes in greedy first, then hours
var timeParts = value.match(/(a|p)?\s*((\d{2})?:?)(\d{1,2})/i);
// This didnt match something we know
if (!timeParts) {
return false;
}
// reverse it:
timeParts = timeParts.reverse();
// Reverse the internal parts:
for( var i = 0; i < timeParts.length; i++ ) {
timeParts[i] = timeParts[i] === undefined ? '' : timeParts[i].reverse();
}
// Parse out the sections:
var minutes = parseInt(timeParts[1], 10) || 0;
var hours = parseInt(timeParts[0], 10);
var afternoon = timeParts[3].toLowerCase() == 'p' ? true : false;
// If meridian not set, and hours is 12, then assume afternoon.
afternoon = !timeParts[3] && hours == 12 ? true : afternoon;
// Anytime the hours are greater than 12, they mean afternoon
afternoon = hours > 12 ? true : afternoon;
// Make hours be between 0 and 12:
hours -= hours > 12 ? 12 : 0;
// Add 12 if its PM but not noon
hours += afternoon && hours != 12 ? 12 : 0;
// Remove 12 for midnight:
hours -= !afternoon && hours == 12 ? 12 : 0;
// Check number sanity:
if( minutes >= 60 || hours >= 24 ) {
return false;
}
// Return a date object with these values set.
var d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + tests[i].parseTime() );
}
这是一个字符串原型,因此您可以像这样使用它:
var str = '12am';
var date = str.parseTime();
对于所有使用 24 小时时钟的人来说,这里有一个解决方案,支持:
- 0820 -> 08:20
- 32 -> 03:02
- 124 -> 12:04
function parseTime(text) {
var time = text.match(/(\d?\d):?(\d?\d?)/);
var h = parseInt(time[1], 10);
var m = parseInt(time[2], 10) || 0;
if (h > 24) {
// try a different format
time = text.match(/(\d)(\d?\d?)/);
h = parseInt(time[1], 10);
m = parseInt(time[2], 10) || 0;
}
var d = new Date();
d.setHours(h);
d.setMinutes(m);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
我对上面的函数做了一些修改以支持更多格式。
- 1400 -> 下午 2:00
- 1.30 -> 下午 1:30
- 上午 1:30 -> 凌晨 1:30
- 100 -> 凌晨 1:00
还没有清理干净,但适用于我能想到的一切。
function parseTime(timeString) {
if (timeString == '') return null;
var time = timeString.match(/^(\d+)([:\.](\d\d))?\s*((a|(p))m?)?$/i);
if (time == null) return null;
var m = parseInt(time[3], 10) || 0;
var hours = parseInt(time[1], 10);
if (time[4]) time[4] = time[4].toLowerCase();
// 12 hour time
if (hours == 12 && !time[4]) {
hours = 12;
}
else if (hours == 12 && (time[4] == "am" || time[4] == "a")) {
hours += 12;
}
else if (hours < 12 && (time[4] != "am" && time[4] != "a")) {
hours += 12;
}
// 24 hour time
else if(hours > 24 && hours.toString().length >= 3) {
if(hours.toString().length == 3) {
m = parseInt(hours.toString().substring(1,3), 10);
hours = parseInt(hours.toString().charAt(0), 10);
}
else if(hours.toString().length == 4) {
m = parseInt(hours.toString().substring(2,4), 10);
hours = parseInt(hours.toString().substring(0,2), 10);
}
}
var d = new Date();
d.setHours(hours);
d.setMinutes(m);
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
这是另一种方法,涵盖原始答案、任何合理的数字数量、猫的数据输入以及逻辑谬误。算法如下:
- 判断经线是否 午后.
- 将输入数字转换为整数值。
- 0 点到 24 点之间的时间:小时是点钟,没有分钟(12 点是下午)。
- 100 到 2359 之间的时间:小时 div 100 是点钟,分钟 mod 100 余数。
- 2400点开始的时间:小时为午夜,剩余分钟。
- 当小时超过 12 时,减去 12 并强制 post meridiem true。
- 当分钟超过 59 时,强制为 59。
将小时、分钟和子午线转换为 Date 对象是读者的一项练习(许多其他答案显示了如何执行此操作)。
"use strict";
String.prototype.toTime = function () {
var time = this;
var post_meridiem = false;
var ante_meridiem = false;
var hours = 0;
var minutes = 0;
if( time != null ) {
post_meridiem = time.match( /p/i ) !== null;
ante_meridiem = time.match( /a/i ) !== null;
// Preserve 2400h time by changing leading zeros to 24.
time = time.replace( /^00/, '24' );
// Strip the string down to digits and convert to a number.
time = parseInt( time.replace( /\D/g, '' ) );
}
else {
time = 0;
}
if( time > 0 && time < 24 ) {
// 1 through 23 become hours, no minutes.
hours = time;
}
else if( time >= 100 && time <= 2359 ) {
// 100 through 2359 become hours and two-digit minutes.
hours = ~~(time / 100);
minutes = time % 100;
}
else if( time >= 2400 ) {
// After 2400, it's midnight again.
minutes = (time % 100);
post_meridiem = false;
}
if( hours == 12 && ante_meridiem === false ) {
post_meridiem = true;
}
if( hours > 12 ) {
post_meridiem = true;
hours -= 12;
}
if( minutes > 59 ) {
minutes = 59;
}
var result =
(""+hours).padStart( 2, "0" ) + ":" + (""+minutes).padStart( 2, "0" ) +
(post_meridiem ? "PM" : "AM");
return result;
};
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + tests[i].toTime() );
}
在 jQuery 中,新定义的 String 原型的使用方式如下:
<input type="text" class="time" />
$(".time").change( function() {
var $this = $(this);
$(this).val( time.toTime() );
});
为什么不使用验证来缩小用户可以输入的内容并简化列表以仅包含可以解析(或经过一些调整后解析)的格式。
我认为要求用户以支持的格式输入时间并不过分。
dd:dd A(米)/P(米)
dd A(米)/P(米)
DD
/(\d+)(?::(\d\d))(?::(\d\d))?\s*([pP]?)/
// added test for p or P
// added seconds
d.setHours( parseInt(time[1]) + (time[4] ? 12 : 0) ); // care with new indexes
d.setMinutes( parseInt(time[2]) || 0 );
d.setSeconds( parseInt(time[3]) || 0 );
谢谢
答案太多了,再多一个也不会有什么坏处。
/**
* Parse a time in nearly any format
* @param {string} time - Anything like 1 p, 13, 1:05 p.m., etc.
* @returns {Date} - Date object for the current date and time set to parsed time
*/
function parseTime(time) {
var b = time.match(/\d+/g);
// return undefined if no matches
if (!b) return;
var d = new Date();
d.setHours(b[0]>12? b[0] : b[0]%12 + (/p/i.test(time)? 12 : 0), // hours
/\d/.test(b[1])? b[1] : 0, // minutes
/\d/.test(b[2])? b[2] : 0); // seconds
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
为了足够稳健,它应该检查每个值是否在允许值的范围内,例如,上午/下午时间是否必须为 1 到 12(含),否则为 0 到 24(含)等。
对 Patrick McElhaney 解决方案的改进(他的解决方案不能正确处理凌晨 12 点)
function parseTime( timeString ) {
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*([pP]?)/i);
var h = parseInt(time[1], 10);
if (time[4])
{
if (h < 12)
h += 12;
}
else if (h == 12)
h = 0;
d.setHours(h);
d.setMinutes(parseInt(time[3], 10) || 0);
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
我对其他答案不满意,所以我又做了一个。这个版本:
- 识别秒和毫秒
- 退货
undefined
无效输入,例如“13:00pm”或“11:65” - 如果您提供,则返回当地时间
localDate
参数,否则返回 Unix 纪元(1970 年 1 月 1 日)的 UTC 时间。 - 支持军事时间,如
1330
(要禁用,请在正则表达式中添加第一个“:”) - 允许一个小时,24 小时时间(即“7”表示上午 7 点)。
- 允许 24 小时作为 0 小时的同义词,但不允许 25 小时。
- 要求时间位于字符串的开头(要禁用、删除
^\s*
在正则表达式中) - 具有实际检测输出何时不正确的测试代码。
编辑:现在是一个 包裹 包括一个 timeToString
格式化程序: npm i simplertime
/**
* Parses a string into a Date. Supports several formats: "12", "1234",
* "12:34", "12:34pm", "12:34 PM", "12:34:56 pm", and "12:34:56.789".
* The time must be at the beginning of the string but can have leading spaces.
* Anything is allowed after the time as long as the time itself appears to
* be valid, e.g. "12:34*Z" is OK but "12345" is not.
* @param {string} t Time string, e.g. "1435" or "2:35 PM" or "14:35:00.0"
* @param {Date|undefined} localDate If this parameter is provided, setHours
* is called on it. Otherwise, setUTCHours is called on 1970/1/1.
* @returns {Date|undefined} The parsed date, if parsing succeeded.
*/
function parseTime(t, localDate) {
// ?: means non-capturing group and ?! is zero-width negative lookahead
var time = t.match(/^\s*(\d\d?)(?::?(\d\d))?(?::(\d\d))?(?!\d)(\.\d+)?\s*(pm?|am?)?/i);
if (time) {
var hour = parseInt(time[1]), pm = (time[5] || ' ')[0].toUpperCase();
var min = time[2] ? parseInt(time[2]) : 0;
var sec = time[3] ? parseInt(time[3]) : 0;
var ms = (time[4] ? parseFloat(time[4]) * 1000 : 0);
if (pm !== ' ' && (hour == 0 || hour > 12) || hour > 24 || min >= 60 || sec >= 60)
return undefined;
if (pm === 'A' && hour === 12) hour = 0;
if (pm === 'P' && hour !== 12) hour += 12;
if (hour === 24) hour = 0;
var date = new Date(localDate!==undefined ? localDate.valueOf() : 0);
var set = (localDate!==undefined ? date.setHours : date.setUTCHours);
set.call(date, hour, min, sec, ms);
return date;
}
return undefined;
}
var testSuite = {
'1300': ['1:00 pm','1:00 P.M.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1:00:00PM', '1300', '13'],
'1100': ['11:00am', '11:00 AM', '11:00', '11:00:00', '1100'],
'1359': ['1:59 PM', '13:59', '13:59:00', '1359', '1359:00', '0159pm'],
'100': ['1:00am', '1:00 am', '0100', '1', '1a', '1 am'],
'0': ['00:00', '24:00', '12:00am', '12am', '12:00:00 AM', '0000', '1200 AM'],
'30': ['0:30', '00:30', '24:30', '00:30:00', '12:30:00 am', '0030', '1230am'],
'1435': ["2:35 PM", "14:35:00.0", "1435"],
'715.5': ["7:15:30", "7:15:30am"],
'109': ['109'], // Three-digit numbers work (I wasn't sure if they would)
'': ['12:60', '11:59:99', '-12:00', 'foo', '0660', '12345', '25:00'],
};
var passed = 0;
for (var key in testSuite) {
let num = parseFloat(key), h = num / 100 | 0;
let m = num % 100 | 0, s = (num % 1) * 60;
let expected = Date.UTC(1970, 0, 1, h, m, s); // Month is zero-based
let strings = testSuite[key];
for (let i = 0; i < strings.length; i++) {
var result = parseTime(strings[i]);
if (result === undefined ? key !== '' : key === '' || expected !== result.valueOf()) {
console.log(`Test failed at ${key}:"${strings[i]}" with result ${result ? result.toUTCString() : 'undefined'}`);
} else {
passed++;
}
}
}
console.log(passed + ' tests passed.');
如果你只想要几秒钟,这里有一个衬垫
const toSeconds = s => s.split(':').map(v => parseInt(v)).reverse().reduce((acc,e,i) => acc + e * Math.pow(60,i))
其他答案整理表
首先,我 不敢相信 没有内置功能,甚至没有强大的第三方库可以处理这个问题。实际上,这是网络开发,所以我可以相信它。
尝试用所有这些不同的算法测试所有边缘情况让我头晕,所以我冒昧地将这个线程中的所有答案和测试编译到一个方便的表格中。
代码(和结果表)太大,无法包含内联内容,所以我制作了一个 JSFiddle:
http://jsfiddle.net/jLv16ydb/4/show
// heres some filler code of the functions I included in the test,
// because StackOverfleaux wont let me have a jsfiddle link without code
Functions = [
JohnResig,
Qwertie,
PatrickMcElhaney,
Brad,
NathanVillaescusa,
DaveJarvis,
AndrewCetinic,
StefanHaberl,
PieterDeZwart,
JoeLencioni,
Claviska,
RobG,
DateJS,
MomentJS
];
// I didn't include `date-fns`, because it seems to have even more
// limited parsing than MomentJS or DateJS
请随意分叉我的小提琴并添加更多算法和测试用例
我没有在结果和“预期”输出之间添加任何比较,因为在某些情况下,“预期”输出可能会引起争议(例如,应该 12
被解释为 12:00am
或者 12:00pm
?)。您必须仔细查看该表,看看哪种算法对您最有意义。
笔记: 颜色不一定表示输出的质量或“预期”,它们仅表示输出的类型:
red
= 抛出js错误yellow
=“假”值(undefined
,null
,NaN
,""
,"invalid date"
)green
= jsDate()
目的light green
= 其他一切
其中一个 Date()
对象是输出,我将其转换为 24 小时 HH:mm
格式以便于比较。
经过彻底的测试和调查后 我的另一个编译答案, ,我得出的结论是,@Dave Jarvis 的解决方案最接近我认为的合理输出和边缘情况处理。作为参考,我查看了退出文本框后 Google 日历的时间输入将时间重新格式化为什么。
即便如此,我发现它并没有像谷歌日历那样处理一些(尽管很奇怪)的边缘情况。所以我从头开始重新设计,这就是我想出的结果。我也将其添加到 我的编译答案.
// attempt to parse string as time. return js date object
static parseTime(string) {
string = String(string);
var am = null;
// check if "apm" or "pm" explicitly specified, otherwise null
if (string.toLowerCase().includes("p")) am = false;
else if (string.toLowerCase().includes("a")) am = true;
string = string.replace(/\D/g, ""); // remove non-digit characters
string = string.substring(0, 4); // take only first 4 digits
if (string.length === 3) string = "0" + string; // consider eg "030" as "0030"
string = string.replace(/^00/, "24"); // add 24 hours to preserve eg "0012" as "00:12" instead of "12:00", since will be converted to integer
var time = parseInt(string); // convert to integer
// default time if all else fails
var hours = 12,
minutes = 0;
// if able to parse as int
if (Number.isInteger(time)) {
// treat eg "4" as "4:00pm" (or "4:00am" if "am" explicitly specified)
if (time >= 0 && time <= 12) {
hours = time;
minutes = 0;
// if "am" or "pm" not specified, establish from number
if (am === null) {
if (hours >= 1 && hours <= 12) am = false;
else am = true;
}
}
// treat eg "20" as "8:00pm"
else if (time >= 13 && time <= 99) {
hours = time % 24;
minutes = 0;
// if "am" or "pm" not specified, force "am"
if (am === null) am = true;
}
// treat eg "52:95" as 52 hours 95 minutes
else if (time >= 100) {
hours = Math.floor(time / 100); // take first two digits as hour
minutes = time % 100; // take last two digits as minute
// if "am" or "pm" not specified, establish from number
if (am === null) {
if (hours >= 1 && hours <= 12) am = false;
else am = true;
}
}
// add 12 hours if "pm"
if (am === false && hours !== 12) hours += 12;
// sub 12 hours if "12:00am" (midnight), making "00:00"
if (am === true && hours === 12) hours = 0;
// keep hours within 24 and minutes within 60
// eg 52 hours 95 minutes becomes 4 hours 35 minutes
hours = hours % 24;
minutes = minutes % 60;
}
// convert to js date object
var date = new Date();
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
return date;
}
我觉得这是我能得到的最接近我的需求的,但欢迎提出建议。 笔记: 这是以美国为中心的,因为某些模式默认为 am/pm:
1
=>13:00
(1:00pm
)1100
=>23:00
(11:00pm
)456
=>16:56
(4:56pm
)