2

I am trying to find a way in jQuery/javascript to reliably convert strings like these: "10:30 am – 11:00 pm" or this "6:45 am – 9:50 pm" into two pieces each, 1030 and 2300 or 645 and 2150 respectively. The end goal is to see if the current time is in between the two, I think I have that part down, but the conversion to 24-hour time is throwing me off. Here is a (non)working example but it might help to better illustrate my idea: http://codepen.io/AlexBezuska/pen/LkxBb Thanks!

4

3 回答 3

1

在以下代码中,未验证输入字符串的格式是否正确,它假定字符串始终采用正确的格式

function time24h(parts){
    var elms = /^(\d+):(\d+)$/.exec(parts[0]);
    return +elms[1] + (/^am$/i.test(parts[1]) ? 0 : 12) + elms[2];
}

function converter(string){
    var array = [];
    var regex = /^(\d+:\d+)\s+(am|pm)\s+.\s+(\d+:\d+)\s+(am|pm)$/;
    var parts = regex.exec(string);
    array.push(time24h([parts[1], parts[2]]));
    array.push(time24h([parts[3], parts[4]]));
    return array;
}

演示:小提琴

于 2013-05-20T03:40:14.170 回答
1

用一些正则表达式魔法尝试这样的事情:

var str = '6:45 am – 9:50 pm';

var result = [],
    regex = /(\d{1,2}):(\d{1,2})\s?(am|pm)/gi;

str.replace(regex, function(_, hours, minutes, meridian) {
  hours =+ hours;
  if (meridian.toLowerCase() == 'pm') hours += 12;
  result.push( +(hours +''+ minutes));
});

console.log(result); //=> [645, 2150]
于 2013-05-20T03:41:48.923 回答
1

像这样:

  /**
   * Returns time numeric value
   * @param timeIn12hours
   * @return {*}
   */
  function get24hoursTime(timeIn12hours)
  {
    timeIn12hours = timeIn12hours.replace(/^\s+|\s+$/g,'');
    var timeParts = timeIn12hours.split(" ");
    var timePeriod = timeParts[1];
    var hourParts = timeParts[0].split(":");

    if(timePeriod == 'pm')
      return (12 + parseInt(hourParts[0])) + hourParts[1];

    return hourParts[0] + hourParts[1];
  }

  /**
   * Returns object with period numeric values
   * @param periodIn12hours
   * @return {Object}
   */
  function get24hoursPeriod(periodIn12hours)
  {
    var parts = periodIn12hours.split("-");

    return {
      'from': get24hoursTime(parts[0]),
      'to': get24hoursTime(parts[1])
    }
  }

  val = get24hoursPeriod("6:45 am - 9:50 pm");

  alert("From: " + val.from + ", to: "+ val.to);
于 2013-05-20T03:43:43.867 回答