本文介紹了將 24 小時制時間轉換為 12 小時制時間,帶 AM &使用 Javascript 進行 PM的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
將以下 JSON 返回值從 24 小時格式轉換為 12 小時格式的最佳方法是什么?下午?日期應該保持不變 - 時間是唯一需要格式化的東西.
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
附:如果這樣做更容易,請使用 jQuery!也更喜歡簡單的函數/代碼,而不是使用 Date.js.
P.S. Using jQuery if that makes it any easier! Would also prefer a simple function/code and not use Date.js.
推薦答案
更新 2: 沒有秒選項
更新: 中午后修正,測試: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"));
這篇關于將 24 小時制時間轉換為 12 小時制時間,帶 AM &使用 Javascript 進行 PM的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!