Format date time in jQuery

前端 未结 5 1942
var date = \"2014-07-12 10:54:11\";

How can I show this in format 12 Jul, 2014 at 10:51 am ? Is there any function like

var          


        
5条回答
  •  鱼传尺愫
    2020-12-17 02:37

    I've made a custom date string format function, you can use that.

    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
                 "H+": getPaddedComp(date.getHours()), //hour
                "m+": getPaddedComp(date.getMinutes()), //minute
                "s+": getPaddedComp(date.getSeconds()), //second
                "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
                "b+": (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;
        };
    

    And now suppose you've :-

        var date = "2014-07-12 10:54:11",
        objDate = Date.parse(date.replace(/-/g, "/"));;
    

    So to format this date you write:-

    var formattedDate = getDateString(new Date(objDate ), "d M, y at h:m b")
    

提交回复
热议问题