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 に答える