使用 AM 和 AM 将 24 小时时间转换为 12 小时时间使用 JavaScript 进行私信

发布于 2024-10-15 18:57:52 字数 198 浏览 5 评论 0原文

使用 AM & 将以下 JSON 返回值从 24 小时格式转换为 12 小时格式的最佳方法是什么?下午?日期应保持不变 - 时间是唯一需要格式化的内容。

February 04, 2011 19:00:00

PS 如果使用 jQuery 更容易的话!也更喜欢简单的函数/代码,而不是使用 Date.js。

What is the best way to convert the following JSON returned value from a 24-hour format to 12-hour format w/ AM & PM? The date should stay the same - the time is the only thing that needs formatting.

February 04, 2011 19:00:00

P.S. Using jQuery if that makes it any easier! Would also prefer a simple function/code and not use Date.js.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

蓝海似她心 2024-10-22 18:57:52

这是无需 if 语句即可更改时间的方法:

hours = ((hours + 11) % 12 + 1);

This is how you can change hours without if statement:

hours = ((hours + 11) % 12 + 1);
多像笑话 2024-10-22 18:57:52

更新2:没有秒选项

更新:中午后上午修正,测试:http://jsfiddle.net/aorcsik/xbtjE/

我创建了这个函数来执行此操作:

function formatDate(date) {
  var d = new Date(date);
  var hh = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  var dd = "AM";
  var h = hh;
  if (h >= 12) {
    h = hh - 12;
    dd = "PM";
  }
  if (h == 0) {
    h = 12;
  }
  m = m < 10 ? "0" + m : m;

  s = s < 10 ? "0" + s : s;

  /* if you want 2 digit hours:
  h = h<10?"0"+h:h; */

  var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);

  var replacement = h + ":" + m;
  /* if you want to add seconds
  replacement += ":"+s;  */
  replacement += " " + dd;

  return date.replace(pattern, replacement);
}

alert(formatDate("February 04, 2011 12:00:00"));

UPDATE 2: without seconds option

UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/

I created this function to do this:

function formatDate(date) {
  var d = new Date(date);
  var hh = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  var dd = "AM";
  var h = hh;
  if (h >= 12) {
    h = hh - 12;
    dd = "PM";
  }
  if (h == 0) {
    h = 12;
  }
  m = m < 10 ? "0" + m : m;

  s = s < 10 ? "0" + s : s;

  /* if you want 2 digit hours:
  h = h<10?"0"+h:h; */

  var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);

  var replacement = h + ":" + m;
  /* if you want to add seconds
  replacement += ":"+s;  */
  replacement += " " + dd;

  return date.replace(pattern, replacement);
}

alert(formatDate("February 04, 2011 12:00:00"));

韬韬不绝 2024-10-22 18:57:52
    //it is pm if hours from 12 onwards
    suffix = (hours >= 12)? 'pm' : 'am';

    //only -12 from hours if it is greater than 12 (if not back at mid night)
    hours = (hours > 12)? hours -12 : hours;

    //if 00 then it is 12 am
    hours = (hours == '00')? 12 : hours;
    //it is pm if hours from 12 onwards
    suffix = (hours >= 12)? 'pm' : 'am';

    //only -12 from hours if it is greater than 12 (if not back at mid night)
    hours = (hours > 12)? hours -12 : hours;

    //if 00 then it is 12 am
    hours = (hours == '00')? 12 : hours;
回首观望 2024-10-22 18:57:52

对于那些只需要输出中的时间的读者,您可以将选项传递给 JavaScript 的 Date::toLocaleString() 方法。例子:

var date = new Date("February 04, 2011 19:00:00");
var options = {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);

timeString 将设置为:

8:00 AM

如果您也需要秒,请将“秒:'数字'”添加到您的选项中。对于所有选项,请参阅

For anyone reading who wants ONLY the time in the output, you can pass options to JavaScript's Date::toLocaleString() method. Example:

var date = new Date("February 04, 2011 19:00:00");
var options = {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);

timeString will be set to:

8:00 AM

Add "second: 'numeric'" to your options if you want seconds too. For all option see this.

余罪 2024-10-22 18:57:52

这是使用原型的一种相当简洁的方法:

Date.prototype.getFormattedTime = function () {
    var hours = this.getHours() == 0 ? "12" : this.getHours() > 12 ? this.getHours() - 12 : this.getHours();
    var minutes = (this.getMinutes() < 10 ? "0" : "") + this.getMinutes();
    var ampm = this.getHours() < 12 ? "AM" : "PM";
    var formattedTime = hours + ":" + minutes + " " + ampm;
    return formattedTime;
}

然后您所要做的就是将字符串值转换为日期并使用新方法:

var stringValue = "February 04, 2011 19:00:00;
var dateValue = new Date(stringValue);
var formattedTime = dateValue.getFormattedTime();

或者在一行中:

var formattedTime = new Date("February 04, 2011 19:00:00").getFormattedTime();

Here's a reasonably terse way to do it using a Prototype:

Date.prototype.getFormattedTime = function () {
    var hours = this.getHours() == 0 ? "12" : this.getHours() > 12 ? this.getHours() - 12 : this.getHours();
    var minutes = (this.getMinutes() < 10 ? "0" : "") + this.getMinutes();
    var ampm = this.getHours() < 12 ? "AM" : "PM";
    var formattedTime = hours + ":" + minutes + " " + ampm;
    return formattedTime;
}

Then all you have to do is convert your string value to a date and use the new method:

var stringValue = "February 04, 2011 19:00:00;
var dateValue = new Date(stringValue);
var formattedTime = dateValue.getFormattedTime();

Or in a single line:

var formattedTime = new Date("February 04, 2011 19:00:00").getFormattedTime();
神也荒唐 2024-10-22 18:57:52

保持简单干净

var d = new Date();
var n = d.toLocaleString();

https://jsfiddle.net/rinu6200/3dkdxaad/#base

Keep it simple and clean

var d = new Date();
var n = d.toLocaleString();

https://jsfiddle.net/rinu6200/3dkdxaad/#base

倾城花音 2024-10-22 18:57:52
function pad(num) {return ("0" + num).slice(-2);}
function time1() {
  var today = new Date(),
    h = today.getHours(),
    m = today.getMinutes(),
    s = today.getSeconds();
    
  h = h % 12;
  h = h ? h : 12; // the hour '0' should be '12'
  clk.innerHTML = h + ':' + 
    pad(m) + ':' + 
    pad(s) + ' ' + 
    (h >= 12 ? 'PM' : 'AM');
}
window.onload = function() {
  var clk = document.getElementById('clk');
  t = setInterval(time1, 500);
}
<span id="clk"></span>

function pad(num) {return ("0" + num).slice(-2);}
function time1() {
  var today = new Date(),
    h = today.getHours(),
    m = today.getMinutes(),
    s = today.getSeconds();
    
  h = h % 12;
  h = h ? h : 12; // the hour '0' should be '12'
  clk.innerHTML = h + ':' + 
    pad(m) + ':' + 
    pad(s) + ' ' + 
    (h >= 12 ? 'PM' : 'AM');
}
window.onload = function() {
  var clk = document.getElementById('clk');
  t = setInterval(time1, 500);
}
<span id="clk"></span>

晚风撩人 2024-10-22 18:57:52

jQuery 根本没有任何日期实用程序。如果您不使用任何其他库,通常的方法是创建一个 JavaScript Date 对象,然后从中提取数据并自行格式化。

要创建 Date 对象,您可以确保 JSON 中的日期字符串采用 Date 可以理解的形式,这是 IETF 标准(基本上是 RFC 822 第 5 节)。因此,如果您有机会更改 JSON,那将是最简单的。 (编辑:您的格式实际上可能按原样工作。)

如果您无法更改 JSON,那么您需要自己解析字符串并获取日、口、年、小时、分钟和秒作为整数并创建Date 对象。

获得 Date 对象后,您需要提取所需的数据并对其进行格式化:

   var myDate = new Date("4 Feb 2011, 19:00:00");
   var hours = myDate.getHours();
   var am = true;
   if (hours > 12) {
      am = false;
      hours -= 12;
   } else (hours == 12) {
      am = false;
   } else (hours == 0) {
      hours = 12;
   }
   
   var minutes = myDate.getMinutes();
   alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);

jQuery doesn't have any Date utilities at all. If you don't use any additional libraries, the usual way is to create a JavaScript Date object and then extract the data from it and format it yourself.

For creating the Date object you can either make sure that your date string in the JSON is in a form that Date understands, which is IETF standard (which is basically RFC 822 section 5). So if you have the chance to change your JSON, that would be easiest. (EDIT: Your format may actually work the way it is.)

If you can't change your JSON, then you'll need to parse the string yourself and get day, mouth, year, hours, minutes and seconds as integers and create the Date object with that.

Once you have your Date object you'll need to extract the data you need and format it:

   var myDate = new Date("4 Feb 2011, 19:00:00");
   var hours = myDate.getHours();
   var am = true;
   if (hours > 12) {
      am = false;
      hours -= 12;
   } else (hours == 12) {
      am = false;
   } else (hours == 0) {
      hours = 12;
   }
   
   var minutes = myDate.getMinutes();
   alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);
澜川若宁 2024-10-22 18:57:52

1) 用于使 24 小时变成 12 小时的“平方”指令:

var hours24 = new Date().getHours(); // retrieve current hours (in 24 mode)
var dayMode = hours24 < 12 ? "am" : "pm"; // if it's less than 12 then "am"
var hours12 = hours24 <= 12 ? (hours24 == 0 ? 12 : hours24) : hours24 - 12;
// "0" in 24-mode now becames "12 am" in 12-mode – thanks to user @Cristian
document.write(hours12 + " " + dayMode); // printing out the result of code

2) 在一行中(相同的结果,但算法略有不同):

var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");

两个选项都返回字符串,例如 "5 pm" 或 <代码>“上午10点”等。

1) "Squared" instructions for making 24-hours became 12-hours:

var hours24 = new Date().getHours(); // retrieve current hours (in 24 mode)
var dayMode = hours24 < 12 ? "am" : "pm"; // if it's less than 12 then "am"
var hours12 = hours24 <= 12 ? (hours24 == 0 ? 12 : hours24) : hours24 - 12;
// "0" in 24-mode now becames "12 am" in 12-mode – thanks to user @Cristian
document.write(hours12 + " " + dayMode); // printing out the result of code

2) In a single line (same result with slightly different algorythm):

var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");

Both options return string, like "5 pm" or "10 am" etc.

留一抹残留的笑 2024-10-22 18:57:52

您可以查看这个。其中一个例子说:

var d = new Date(dateString);

一旦你有了 Date 对象,你就可以相当容易地使用它。您可以调用 toLocaleDateString、toLocaleTimeString,也可以测试 getHours 是否大于 12,然后计算 AM/PM 时间。

You can take a look at this. One of the examples says:

var d = new Date(dateString);

Once you have Date object you can fairly easy play with it. You can either call toLocaleDateString, toLocaleTimeString or you can test if getHours is bigger than 12 and then just calculate AM/PM time.

箹锭⒈辈孓 2024-10-22 18:57:52
date = date.replace(/[0-9]{1,2}(:[0-9]{2}){2}/, function (time) {
    var hms = time.split(':'),
        h = +hms[0],
        suffix = (h < 12) ? 'am' : 'pm';
    hms[0] = h % 12 || 12;        
    return hms.join(':') + suffix
});

编辑:我忘记处理上午/下午 12 点。固定的。

date = date.replace(/[0-9]{1,2}(:[0-9]{2}){2}/, function (time) {
    var hms = time.split(':'),
        h = +hms[0],
        suffix = (h < 12) ? 'am' : 'pm';
    hms[0] = h % 12 || 12;        
    return hms.join(':') + suffix
});

edit: I forgot to deal with 12 o'clock am/pm. Fixed.

歌枕肩 2024-10-22 18:57:52
var dt = new Date();
    var h =  dt.getHours(), m = dt.getMinutes();
    var thistime = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
console.log(thistime);

这是演示

var dt = new Date();
    var h =  dt.getHours(), m = dt.getMinutes();
    var thistime = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
console.log(thistime);

Here is the Demo

云淡风轻 2024-10-22 18:57:52
 function GetTime(date) {
        var currentTime = (new Date(date))
        var hours = currentTime.getHours()
        //Note: before converting into 12 hour format
        var suffix = '';
        if (hours > 11) {
            suffix += "PM";
        } else {
            suffix += "AM";
        }
        var minutes = currentTime.getMinutes()
        if (minutes < 10) {
            minutes = "0" + minutes
        }
        if (hours > 12) {
            hours -= 12;
        } else if (hours === 0) {
            hours = 12;
        }
        var time = hours + ":" + minutes + " " + suffix;
        return time;
    }
 function GetTime(date) {
        var currentTime = (new Date(date))
        var hours = currentTime.getHours()
        //Note: before converting into 12 hour format
        var suffix = '';
        if (hours > 11) {
            suffix += "PM";
        } else {
            suffix += "AM";
        }
        var minutes = currentTime.getMinutes()
        if (minutes < 10) {
            minutes = "0" + minutes
        }
        if (hours > 12) {
            hours -= 12;
        } else if (hours === 0) {
            hours = 12;
        }
        var time = hours + ":" + minutes + " " + suffix;
        return time;
    }
猫九 2024-10-22 18:57:52

请尝试使用下面的代码

var s = "15 Feb 2015 11.30 a.m";
        var times = s.match("((([0-9])|([0-2][0-9])).([0-9][0-9])[\t ]?((a.m|p.m)|(A.M|P.M)))");            
        var time = "";

        if(times != null){                          
            var hour = times[2];
            if((times[6] == "p.m" || times[6] == "P.M")){
                if(hour < 12){
                    hour = parseInt(hour) + parseInt(12);
                }else if(hour == 12){
                    hour = "00";
                }
            }
            time = [hour, times[5], "00"].join(":");

        }

谢谢

Please try with below code

var s = "15 Feb 2015 11.30 a.m";
        var times = s.match("((([0-9])|([0-2][0-9])).([0-9][0-9])[\t ]?((a.m|p.m)|(A.M|P.M)))");            
        var time = "";

        if(times != null){                          
            var hour = times[2];
            if((times[6] == "p.m" || times[6] == "P.M")){
                if(hour < 12){
                    hour = parseInt(hour) + parseInt(12);
                }else if(hour == 12){
                    hour = "00";
                }
            }
            time = [hour, times[5], "00"].join(":");

        }

Thanks

栖竹 2024-10-22 18:57:52

这对我有用!

function main() {
  var time = readLine();
  var formattedTime = time.replace('AM', ' AM').replace('PM', ' PM');
  var separators = [':', ' M'];
  var hms = formattedTime.split(new RegExp('[' + separators.join('') + ']'));
  if (parseInt(hms[0]) < 12 && hms[3] == 'P')
      hms[0] = parseInt(hms[0]) + 12;
  else if (parseInt(hms[0]) == 12 && hms[3] == 'A')
      hms[0] = '00';
  console.log(hms[0] + ':' + hms[1] + ':' + hms[2]);

}

This worked for me!

function main() {
  var time = readLine();
  var formattedTime = time.replace('AM', ' AM').replace('PM', ' PM');
  var separators = [':', ' M'];
  var hms = formattedTime.split(new RegExp('[' + separators.join('') + ']'));
  if (parseInt(hms[0]) < 12 && hms[3] == 'P')
      hms[0] = parseInt(hms[0]) + 12;
  else if (parseInt(hms[0]) == 12 && hms[3] == 'A')
      hms[0] = '00';
  console.log(hms[0] + ':' + hms[1] + ':' + hms[2]);

}
清风无影 2024-10-22 18:57:52

您可以尝试这个更通用的函数:

function to12HourFormat(date = (new Date)) {
  return {
    hours: ((date.getHours() + 11) % 12 + 1),
    minutes: date.getMinutes(),
    meridian: (date.getHours() >= 12) ? 'PM' : 'AM',
  };
}

返回灵活的对象格式。

https://jsbin.com/vexejanovo/edit

You could try this more generic function:

function to12HourFormat(date = (new Date)) {
  return {
    hours: ((date.getHours() + 11) % 12 + 1),
    minutes: date.getMinutes(),
    meridian: (date.getHours() >= 12) ? 'PM' : 'AM',
  };
}

Returns a flexible object format.

https://jsbin.com/vexejanovo/edit

玩世 2024-10-22 18:57:52

我是一个相对新手,但这是我为自己的一个项目想到的,而且它似乎有效。可能有更简单的方法可以做到这一点。

function getTime() {
    var nowTimeDate = new Date();
    var nowHour = nowTimeDate.getHours();
    var nowMinutes = nowTimeDate.getMinutes();
    var suffix = nowHour >= 12 ? "pm" : "am";
    nowHour = (suffix == "pm" & (nowHour > 12 & nowHour < 24)) ? (nowHour - 12) : nowHour;
    nowHour = nowHour == 0 ? 12 : nowHour;
    nowMinutes = nowMinutes < 10 ? "0" + nowMinutes : nowMinutes;
    var currentTime = nowHour + ":" + nowMinutes + suffix;
    document.getElementById("currentTime").innerHTML = currentTime;
}

I'm a relative newbie, but here's what I came up with for one of my own projects, and it seems to work. There may be simpler ways to do it.

function getTime() {
    var nowTimeDate = new Date();
    var nowHour = nowTimeDate.getHours();
    var nowMinutes = nowTimeDate.getMinutes();
    var suffix = nowHour >= 12 ? "pm" : "am";
    nowHour = (suffix == "pm" & (nowHour > 12 & nowHour < 24)) ? (nowHour - 12) : nowHour;
    nowHour = nowHour == 0 ? 12 : nowHour;
    nowMinutes = nowMinutes < 10 ? "0" + nowMinutes : nowMinutes;
    var currentTime = nowHour + ":" + nowMinutes + suffix;
    document.getElementById("currentTime").innerHTML = currentTime;
}
盛夏已如深秋| 2024-10-22 18:57:52

这是您的 html 代码,您在其中调用函数将 24 小时时间格式转换为 12 小时(上午/下午)

<pre id="tests" onClick="tConvert('18:00:00')">
  test on click 18:00:00
</pre>
<span id="rzlt"></span>

现在在js代码中按原样编写这个tConvert函数

 function tConvert (time)
  {
     
   // 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' : 'PM'; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    //return time; // return adjusted time or original string
      var tel = document.getElementById ('rzlt');
      
      tel.innerHTML= time.join ('');
  }

将 18:00:00 转换为 6:00:00PM 为我工作

this is your html code where you are calling function to convert 24 hour time format to 12 hour with am/pm

<pre id="tests" onClick="tConvert('18:00:00')">
  test on click 18:00:00
</pre>
<span id="rzlt"></span>

now in js code write this tConvert function as it is

 function tConvert (time)
  {
     
   // 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' : 'PM'; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    //return time; // return adjusted time or original string
      var tel = document.getElementById ('rzlt');
      
      tel.innerHTML= time.join ('');
  }

converting 18:00:00 to 6:00:00PM working for me

霞映澄塘 2024-10-22 18:57:52

该函数将在两个方向上进行转换:
12 到 24 小时24 到 12 小时

function toggle24hr(time, onoff){
    if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
    var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
    time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
    time[0] = Number(time[0])
    if(onoff){//convert to 24 hour:
        if((pm && time[0]!=12)) time[0] += 12
        else if(!pm && time[0]==12) time[0] = '00'  //handle midnight
        if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
    }else{ //convert to 12 hour:
        pm = time[0]>=12
        if(!time[0]) time[0]=12 //handle midnight
        else if(pm && time[0]!=12) time[0] -= 12
    }
    return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}

以下是一些示例:

//convert to 24 hour:
toggle24hr('12:00am')   //returns 00:00
toggle24hr('2:00pm')    //returns 14:00
toggle24hr('8:00am')    //returns 08:00
toggle24hr('12:00pm')   //returns 12:00

//convert to 12 hour:
toggle24hr('14:00')    //returns 2:00pm
toggle24hr('08:00')    //returns 8:00am
toggle24hr('12:00')    //returns 12:00pm
toggle24hr('00:00')    //returns 12:00am

//you can also force a specific format like this:
toggle24hr('14:00',1)    //returns 14:00
toggle24hr('14:00',0)    //returns 2:00pm

This function will convert in both directions:
12 to 24 hour or 24 to 12 hour

function toggle24hr(time, onoff){
    if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
    var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
    time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
    time[0] = Number(time[0])
    if(onoff){//convert to 24 hour:
        if((pm && time[0]!=12)) time[0] += 12
        else if(!pm && time[0]==12) time[0] = '00'  //handle midnight
        if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
    }else{ //convert to 12 hour:
        pm = time[0]>=12
        if(!time[0]) time[0]=12 //handle midnight
        else if(pm && time[0]!=12) time[0] -= 12
    }
    return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}

Here's some examples:

//convert to 24 hour:
toggle24hr('12:00am')   //returns 00:00
toggle24hr('2:00pm')    //returns 14:00
toggle24hr('8:00am')    //returns 08:00
toggle24hr('12:00pm')   //returns 12:00

//convert to 12 hour:
toggle24hr('14:00')    //returns 2:00pm
toggle24hr('08:00')    //returns 8:00am
toggle24hr('12:00')    //returns 12:00pm
toggle24hr('00:00')    //returns 12:00am

//you can also force a specific format like this:
toggle24hr('14:00',1)    //returns 14:00
toggle24hr('14:00',0)    //returns 2:00pm
﹂绝世的画 2024-10-22 18:57:52

给你

var myDate = new Date("February 04, 2011 19:00:00");
var hr = myDate.getHours(); 
var convHrs = "";
var ampmSwitch = "";
ampmSwitch = (hr > 12)? "PM":"AM"; 
convHrs = (hr >12)? hr-12:hr;
// Build back the Date / time using getMonth/ getFullYear and getDate and other functions on the myDate object. Enclose it inside a func and there you got the working 12 hrs converter ;)

,这是你的转换器函数;)祝你编码愉快!

function convertTo12Hrs(yourDateTime){
    var myDate = new Date(yourDateTime);
    var dtObject = new Object();
    var monthsCollection = {0:"January", 1:"February",2:"March",3:"April",4:"May",5:"June",6:"July",7:"August",8:"September",9:"October",10:"November",11:"December"};
    dtObject.year = myDate.getFullYear();
    dtObject.month = monthsCollection[myDate.getMonth()];
    dtObject.day = (myDate.getDate()<10)?"0"+myDate.getDate():myDate.getDate();
    dtObject.minutes = (myDate.getMinutes() < 10)? "0"+myDate.getMinutes():myDate.getMinutes();
    dtObject.seconds = (myDate.getSeconds() < 10)? "0"+myDate.getSeconds():myDate.getSeconds();
    // Check if hours are greater than 12? Its PM
    dtObject.ampmSwitch = (myDate.getHours() > 12)? "PM":"AM";
    // Convert the hours
    dtObject.hour = (myDate.getHours() > 12)?myDate.getHours()-12:myDate.getHours();
    // Add the 0 as prefix if its less than 10
    dtObject.hour = (dtObject.hour < 10)? "0"+dtObject.hour:dtObject.hour;

    // Format back the string as it was or return the dtObject object or however you like. I am returning the object here
    return dtObject;
}

像这样调用它
ConvertTo12Hrs("2011 年 2 月 4 日 19:00:00");它将返回您的对象,您可以使用该对象按照您的喜好格式化回日期时间字符串...

Here you go

var myDate = new Date("February 04, 2011 19:00:00");
var hr = myDate.getHours(); 
var convHrs = "";
var ampmSwitch = "";
ampmSwitch = (hr > 12)? "PM":"AM"; 
convHrs = (hr >12)? hr-12:hr;
// Build back the Date / time using getMonth/ getFullYear and getDate and other functions on the myDate object. Enclose it inside a func and there you got the working 12 hrs converter ;)

And here's the converter func for yas ;) Happy coding!!

function convertTo12Hrs(yourDateTime){
    var myDate = new Date(yourDateTime);
    var dtObject = new Object();
    var monthsCollection = {0:"January", 1:"February",2:"March",3:"April",4:"May",5:"June",6:"July",7:"August",8:"September",9:"October",10:"November",11:"December"};
    dtObject.year = myDate.getFullYear();
    dtObject.month = monthsCollection[myDate.getMonth()];
    dtObject.day = (myDate.getDate()<10)?"0"+myDate.getDate():myDate.getDate();
    dtObject.minutes = (myDate.getMinutes() < 10)? "0"+myDate.getMinutes():myDate.getMinutes();
    dtObject.seconds = (myDate.getSeconds() < 10)? "0"+myDate.getSeconds():myDate.getSeconds();
    // Check if hours are greater than 12? Its PM
    dtObject.ampmSwitch = (myDate.getHours() > 12)? "PM":"AM";
    // Convert the hours
    dtObject.hour = (myDate.getHours() > 12)?myDate.getHours()-12:myDate.getHours();
    // Add the 0 as prefix if its less than 10
    dtObject.hour = (dtObject.hour < 10)? "0"+dtObject.hour:dtObject.hour;

    // Format back the string as it was or return the dtObject object or however you like. I am returning the object here
    return dtObject;
}

invoke it like
convertTo12Hrs("February 04, 2011 19:00:00"); it will return you the object, which in turn you can use to format back your datetime string as you fancy...

掐死时间 2024-10-22 18:57:52

无论如何,你最终都会进行大量的字符串操作,
那么为什么不直接操作日期字符串本身呢?

浏览器对日期字符串的格式不同。

Netscape ::: 2012 年 5 月 11 日星期五 20:15:49 GMT-0600(山地夏令时间)

IE ::: 2012 年 MDT 5 月 11 日星期五 20:17:33

所以你必须检查一下。

var D = new Date().toString().split(' ')[(document.all)?3:4];

这会将 D 设置为 24 小时 HH:MM:SS 字符串。将其拆分为
冒号,第一个元素是小时。

var H = new Date().toString().split(' ')[(document.all)?3:4].split(':')[0];

可以将 24 小时制转换为 12 小时制,但这并没有
这里其实已经提到了。可能是因为它相当疯狂
当你转换小时数时,你实际上在数学上做什么
从时钟。事实上,你所做的就是添加 23,然后对其进行修改
乘以 12,然后加 1

twelveHour = ((twentyfourHour+23)%12)+1;

因此,例如,您可以从日期字符串 mod 中获取整个时间
小时,并用新的小时显示所有内容。

var T = new Date().toString().split(' ')[(document.all)?3:4].split(':');
T[0] = (((T[0])+23)%12)+1;
alert(T.join(':'));

使用一些智能正则表达式,您可能可以从 HH:MM:SS 中提取时间
日期字符串的一部分,并将它们全部放在同一行中。这将是
荒谬的一行,因为反向引用 $1 不能用于
无需在替换中放置函数即可进行计算。

看起来是这样的:

var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/,function(){return ((parseInt(RegExp.$1)+23)%12)+1} );

正如我所说,这很荒谬。如果您使用的库可以执行
如果您对反向引用进行计算,则该行将变为:

var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/, (($1+23)%12)+1);

如果您很好地记录了它,那么这实际上并不是不可能作为可用代码。
该行说:

创建一个日期字符串,用空格将其分解,获取 browser-apropos 部分,
并将第一个两位数字替换为经过修改的数字。

故事的重点是,如何将 24 小时制时间转换为 12 小时制时间
是一种非显而易见的数学计算:

将 23 加起来,再除以 12,然后再加一个。

You're going to end up doing alot of string manipulation anyway,
so why not just manipulate the date string itself?

Browsers format the date string differently.

Netscape ::: Fri May 11 2012 20:15:49 GMT-0600 (Mountain Daylight Time)

IE ::: Fri May 11 20:17:33 MDT 2012

so you'll have to check for that.

var D = new Date().toString().split(' ')[(document.all)?3:4];

That will set D equal to the 24-hour HH:MM:SS string. Split that on the
colons, and the first element will be the hours.

var H = new Date().toString().split(' ')[(document.all)?3:4].split(':')[0];

You can convert 24-hour hours into 12-hour hours, but that hasn't
actually been mentioned here. Probably because it's fairly CRAZY
what you're actually doing mathematically when you convert hours
from clocks. In fact, what you're doing is adding 23, mod'ing that
by 12, and adding 1

twelveHour = ((twentyfourHour+23)%12)+1;

So, for example, you could grab the whole time from the date string, mod
the hours, and display all that with the new hours.

var T = new Date().toString().split(' ')[(document.all)?3:4].split(':');
T[0] = (((T[0])+23)%12)+1;
alert(T.join(':'));

With some smart regex, you can probably pull the hours off the HH:MM:SS
part of the date string, and mod them all in the same line. It would be
a ridiculous line because the backreference $1 couldn't be used in
calculations without putting a function in the replace.

Here's how that would look:

var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/,function(){return ((parseInt(RegExp.$1)+23)%12)+1} );

Which, as I say, is ridiculous. If you're using a library that CAN perform
calculations on backreferences, the line becomes:

var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/, (($1+23)%12)+1);

And that's not actually out of the question as useable code, if you document it well.
That line says:

Make a Date string, break it up on the spaces, get the browser-apropos part,
and replace the first two-digit-number with that number mod'ed.

Point of the story is, the way to convert 24-hour-clock hours to 12-hour-clock hours
is a non-obvious mathematical calculation:

You add 23, mod by 12, then add one more.

落叶缤纷 2024-10-22 18:57:52

这是一个对我有用的不错的小功能。

function getDisplayDatetime() {
    var d = new Date(); var hh = d.getHours(); var mm = d.getMinutes(); var dd = "AM"; var h = hh;

    if (mm.toString().length == 1) {
        mm = "0" + mm;
    }

    if (h >= 12) {
        h = hh - 12;
        dd = "PM";
    }

    if (h == 0) {
        h = 12;
    }
    var Datetime = "Datetime: " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getUTCDate() + " " + h + ":" + mm;
    return Datetime + " " + dd;
}

Here is a nice little function that worked for me.

function getDisplayDatetime() {
    var d = new Date(); var hh = d.getHours(); var mm = d.getMinutes(); var dd = "AM"; var h = hh;

    if (mm.toString().length == 1) {
        mm = "0" + mm;
    }

    if (h >= 12) {
        h = hh - 12;
        dd = "PM";
    }

    if (h == 0) {
        h = 12;
    }
    var Datetime = "Datetime: " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getUTCDate() + " " + h + ":" + mm;
    return Datetime + " " + dd;
}
丑丑阿 2024-10-22 18:57:52

我注意到已经有一个答案,但我想分享我自己的解决方案,使用纯 JavaScript:

function curTime(pm) {
  var dt = new Date();
  var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
  var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
  return time;
}

您可以在 https://jsfiddle.net/j2xk312m/3/ 使用以下代码块:

(function() {

  function curTime(pm) {
    var dt = new Date();
    var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
    var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
    return time;
  }

  alert("12-hour Format:    "+curTime(true)+"\n24-hour Format:    "+curTime(false));

})();

I noticed there is already an answer, but I wanted to share my own solution, using pure JavaScript:

function curTime(pm) {
  var dt = new Date();
  var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
  var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
  return time;
}

You can see it in action at https://jsfiddle.net/j2xk312m/3/ using the following code block:

(function() {

  function curTime(pm) {
    var dt = new Date();
    var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
    var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
    return time;
  }

  alert("12-hour Format:    "+curTime(true)+"\n24-hour Format:    "+curTime(false));

})();
牵你的手,一向走下去 2024-10-22 18:57:52

这样您就可以更好地控制输出 - 即 - 如果您希望时间格式为 '4:30 pm' 而不是 '04:30 PM' - 您可以转换为您想要的任何格式 - 也可以稍后更改。而不是受限于一些不允许任何灵活性的旧方法。

您只需转换前 2 位数字,因为 24 小时制或 12 小时制的分和秒数字相同。

var my_time_conversion_arr = {'01':"01", '02':"02", '03':"03", '04':"04", '05':"05", '06':"06", '07':"07", '08':"08", '09':"09", '10':"10", '11':"11", '12': "12", '13': "1", '14': "2", '15': "3", '16': "4", '17': "5", '18': "6", '19': "7", '20': "8", '21': "9", '22': "10", '23': "11", '00':"12"};

                var AM_or_PM = "";
                var twenty_four_hour_time = "16:30";
                var twenty_four_hour_time_arr = twenty_four_hour_time.split(":");
                var twenty_four_hour_time_first_two_digits = twenty_four_hour_time_arr[0];

                var first_two_twelve_hour_digits_converted = my_time_conversion_arr[twenty_four_hour_time_first_two_digits];

                var time_strng_to_nmbr = parseInt(twenty_four_hour_time_first_two_digits);
                if(time_strng_to_nmbr >12){
                    //alert("GREATER THAN 12");
                    AM_or_PM = "pm";
                }else{
                    AM_or_PM = "am";
                }

                var twelve_hour_time_conversion = first_two_twelve_hour_digits_converted+":"+twenty_four_hour_time_arr[1]+" "+AM_or_PM;

This way you have more control over the output - i.e - if you wanted the time format to be '4:30 pm' instead of '04:30 P.M.' - you can convert to whatever format you decide you want - and change it later too. Instead of being constrained to some old method that does not allow any flexibility.

and you only need to convert the first 2 digits as the minute and seconds digits are the same in 24 hour time or 12 hour time.

var my_time_conversion_arr = {'01':"01", '02':"02", '03':"03", '04':"04", '05':"05", '06':"06", '07':"07", '08':"08", '09':"09", '10':"10", '11':"11", '12': "12", '13': "1", '14': "2", '15': "3", '16': "4", '17': "5", '18': "6", '19': "7", '20': "8", '21': "9", '22': "10", '23': "11", '00':"12"};

                var AM_or_PM = "";
                var twenty_four_hour_time = "16:30";
                var twenty_four_hour_time_arr = twenty_four_hour_time.split(":");
                var twenty_four_hour_time_first_two_digits = twenty_four_hour_time_arr[0];

                var first_two_twelve_hour_digits_converted = my_time_conversion_arr[twenty_four_hour_time_first_two_digits];

                var time_strng_to_nmbr = parseInt(twenty_four_hour_time_first_two_digits);
                if(time_strng_to_nmbr >12){
                    //alert("GREATER THAN 12");
                    AM_or_PM = "pm";
                }else{
                    AM_or_PM = "am";
                }

                var twelve_hour_time_conversion = first_two_twelve_hour_digits_converted+":"+twenty_four_hour_time_arr[1]+" "+AM_or_PM;
肤浅与狂妄 2024-10-22 18:57:52

JavaScript 中理想的简单答案,不包括秒。

   var h = 23   // Hour (Enter This)
   var min = 55  // Minutes (Enter This)
   var meridian = "AM"  // AM or PM

  if (h >= 12) {
    h = h - 12;
    meridian = "PM";
  }
  if (h == 0) {
    h = 12;
  }

  document.write(h + ":" + min + " " + meridian)
  // Returns 12:55 PM

Ideal simplistic answer in JavaScript, excluding seconds.

   var h = 23   // Hour (Enter This)
   var min = 55  // Minutes (Enter This)
   var meridian = "AM"  // AM or PM

  if (h >= 12) {
    h = h - 12;
    meridian = "PM";
  }
  if (h == 0) {
    h = 12;
  }

  document.write(h + ":" + min + " " + meridian)
  // Returns 12:55 PM
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文