如何将24h时间格式转换为12h格式以及其他方法?

时间:2019-01-30 22:26:40

标签: javascript jquery

我有一个具有24h格式(小时:分钟天)的不同时间的表,并且可以成功地将其转换为12h格式(小时:分钟AM / PM天)。但是,我无法将其从12h格式转换回24h格式。

这是我的代码:

<table>
    <tr>
      <th>ID</th>
      <th>Time</th>
    </tr>
    <tr>
      <td>1</td>
      <td class="timeclass">00:15 Monday</td>
    </tr>
    <tr>
      <td>1</td>
      <td class="timeclass">01:00 Tuesday</td>
    </tr>
    <tr>
      <td>1</td>
      <td class="timeclass">03:15 Wednesday</td>
    </tr>
    <tr>
      <td>1</td>
      <td class="timeclass">04:00 Thursday</td>
    </tr>
</table>
<input type="checkbox" value="" id="AMPM" onclick="AMPMCheck()"> AM/PM format

function AMPMCheck() {
  var checkBox = document.getElementById("AMPM");
  if (checkBox.checked == true){
    convertTime24To12();
  } else {
     convertTime12To24();
  }
}


function convertTime24To12 () {
  $(".timeclass").each(function() {
    var $e = $(this);
    var time3 = $e.html();
    var time2 = time3.split(' ');
    var time = time2[0];
    var day = time2[1];
    // Check correct time format and split into components
    time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

    if (time.length > 1) { // If time format correct
      time = time.slice (1);  // Remove full string match value
      time[5] = +time[0] < 12 ? ' AM ' + day : ' PM ' + day; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    $e.html(time.join (''));
  });
}

function convertTime12To24 () {
  $(".timeclass").each(function() {
    var $e = $(this);
    var time3 = $e.html();
    var time2 = time3.split(' ');
    var time = time2[0].split(':');
    var hours = time[0];
    var minutes = time[1];
    console.log("hours: " + hours + " minutes: " + minutes);
    var AMPM = time2[1];
    if(AMPM == "PM" && hours<12) hours = hours+12;
    if(AMPM == "AM" && hours==12) hours = hours-12;
    var sHours = hours.toString();
    var sMinutes = minutes.toString();
    if(hours<10) sHours = "0" + sHours;
    if(minutes<10) sMinutes = "0" + sMinutes;
    $e.html(sHours + ":" + sMinutes + " " + time2[2]);
  });
}

这里也是JSFiddle的链接:https://jsfiddle.net/samg1wfv/

有人知道从12h格式转换回24h格式时我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您正在将hoursminutes解释为字符串,然后将它们视为数字。

通过将它们转换为数字:

var hours = Number(time[0]);
var minutes = Number(time[1]);

您的代码将按预期工作。