Convert UTC time to hours, minutes, and AM/PM format in javascript

被刻印的时光 ゝ 提交于 2019-12-25 03:24:46

问题


Given a UTC time, what is a simple way of converting it to a format in hours, minutes, and AM/PM (e.g. '3:30 PM')?


回答1:


<script type="text/javascript">
<!--

var a_p = "";
var d = new Date();

var curr_hour = d.getHours();

if (curr_hour < 12)
   {
   a_p = "AM";
   }
else
   {
   a_p = "PM";
   }
if (curr_hour == 0)
   {
   curr_hour = 12;
   }
if (curr_hour > 12)
   {
   curr_hour = curr_hour - 12;
   }

var curr_min = d.getMinutes();

document.write(curr_hour + " : " + curr_min + " " + a_p);

//-->
</script>

http://www.webdevelopersnotes.com/tips/html/formatting_time_using_javascript.php




回答2:


Use the following function, you can change a utc time in any format:-

var  getDateString = function(date, format) {
            var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            getPaddedComp = function(comp) {
                return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
            },
            formattedDate = format,
            o = {
                "y+": date.getFullYear(), // year
                "M+": months[date.getMonth()], //month
                "d+": getPaddedComp(date.getDate()), //day
                "h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
                "m+": getPaddedComp(date.getMinutes()), //minute
                "s+": getPaddedComp(date.getSeconds()), //second
                "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
                "t+": (date.getHours() >= 12) ? 'PM' : 'AM'
            };

            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    formattedDate = formattedDate.replace(RegExp.$1, o[k]);
                }
            }
            return formattedDate;
        };

Now you can use it to format any date object like:-

 getDateString(new Date(), "h:m:s:t")

o/p: "01:34:22:AM"


 getDateString(new Date(), "y:M:d")
 o/p:- "2014:Jun:20"

 getDateString(new Date(), "y/M/d h:m:s:t")
 o/p:- "2014/Jun/20 01:34:22:AM"



回答3:


// d = new Date(utc);
var hour = d.getHours() == 0 ? 12 : (d.getHours() > 12 ? d.getHours() - 12 : d.getHours());
var min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
var ampm = d.getHours() < 12 ? 'AM' : 'PM';
var time = hour + ':' + min + ' ' + ampm;


来源:https://stackoverflow.com/questions/24315100/convert-utc-time-to-hours-minutes-and-am-pm-format-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!