如何将Date对象格式化为字符串?


当前回答

这是修改为3个字符月和2位数年的主要答案:

函数formatDate(日期){var monthNames=[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”,“十月”,“十一月”,“十二月”];var day=date.getDate(),monthIndex=date.getMonth(),year=date.getFullYear().toString().substr(-2);return day+''+monthNames[monthIndex]+''+年;}document.write(formatDate(newDate()));

其他回答

设置日期格式的其他方式:

function formatDate(dDate,sMode){
    var today = dDate;
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10) {
        dd = '0'+dd
    }
    if(mm<10) {
        mm = '0'+mm
    }
    if (sMode+""==""){
        sMode = "dd/mm/yyyy";
    }
    if (sMode == "yyyy-mm-dd"){
        return  yyyy + "-" + mm + "-" + dd + "";
    }
    if (sMode == "dd/mm/yyyy"){
        return  dd + "/" + mm + "/" + yyyy;
    }
}

这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿了PHP日期格式功能,以满足我的需要。请随意使用它,它只是扩展了现有的Date()对象。这可能不是最优雅的解决方案,但它符合我的需求。

var d = new Date(); 
d_string = d.format("m/d/Y h:i:s");

/**************************************
 * Date class extension
 * 
 */
    // Provide month names
    Date.prototype.getMonthName = function(){
        var month_names = [
                            'January',
                            'February',
                            'March',
                            'April',
                            'May',
                            'June',
                            'July',
                            'August',
                            'September',
                            'October',
                            'November',
                            'December'
                        ];

        return month_names[this.getMonth()];
    }

    // Provide month abbreviation
    Date.prototype.getMonthAbbr = function(){
        var month_abbrs = [
                            'Jan',
                            'Feb',
                            'Mar',
                            'Apr',
                            'May',
                            'Jun',
                            'Jul',
                            'Aug',
                            'Sep',
                            'Oct',
                            'Nov',
                            'Dec'
                        ];

        return month_abbrs[this.getMonth()];
    }

    // Provide full day of week name
    Date.prototype.getDayFull = function(){
        var days_full = [
                            'Sunday',
                            'Monday',
                            'Tuesday',
                            'Wednesday',
                            'Thursday',
                            'Friday',
                            'Saturday'
                        ];
        return days_full[this.getDay()];
    };

    // Provide full day of week name
    Date.prototype.getDayAbbr = function(){
        var days_abbr = [
                            'Sun',
                            'Mon',
                            'Tue',
                            'Wed',
                            'Thur',
                            'Fri',
                            'Sat'
                        ];
        return days_abbr[this.getDay()];
    };

    // Provide the day of year 1-365
    Date.prototype.getDayOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((this - onejan) / 86400000);
    };

    // Provide the day suffix (st,nd,rd,th)
    Date.prototype.getDaySuffix = function() {
        var d = this.getDate();
        var sfx = ["th","st","nd","rd"];
        var val = d%100;

        return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
    };

    // Provide Week of Year
    Date.prototype.getWeekOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
    } 

    // Provide if it is a leap year or not
    Date.prototype.isLeapYear = function(){
        var yr = this.getFullYear();

        if ((parseInt(yr)%4) == 0){
            if (parseInt(yr)%100 == 0){
                if (parseInt(yr)%400 != 0){
                    return false;
                }
                if (parseInt(yr)%400 == 0){
                    return true;
                }
            }
            if (parseInt(yr)%100 != 0){
                return true;
            }
        }
        if ((parseInt(yr)%4) != 0){
            return false;
        } 
    };

    // Provide Number of Days in a given month
    Date.prototype.getMonthDayCount = function() {
        var month_day_counts = [
                                    31,
                                    this.isLeapYear() ? 29 : 28,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31
                                ];

        return month_day_counts[this.getMonth()];
    } 

    // format provided date into this.format format
    Date.prototype.format = function(dateFormat){
        // break apart format string into array of characters
        dateFormat = dateFormat.split("");

        var date = this.getDate(),
            month = this.getMonth(),
            hours = this.getHours(),
            minutes = this.getMinutes(),
            seconds = this.getSeconds();
        // get all date properties ( based on PHP date object functionality )
        var date_props = {
            d: date < 10 ? '0'+date : date,
            D: this.getDayAbbr(),
            j: this.getDate(),
            l: this.getDayFull(),
            S: this.getDaySuffix(),
            w: this.getDay(),
            z: this.getDayOfYear(),
            W: this.getWeekOfYear(),
            F: this.getMonthName(),
            m: month < 10 ? '0'+(month+1) : month+1,
            M: this.getMonthAbbr(),
            n: month+1,
            t: this.getMonthDayCount(),
            L: this.isLeapYear() ? '1' : '0',
            Y: this.getFullYear(),
            y: this.getFullYear()+''.substring(2,4),
            a: hours > 12 ? 'pm' : 'am',
            A: hours > 12 ? 'PM' : 'AM',
            g: hours % 12 > 0 ? hours % 12 : 12,
            G: hours > 0 ? hours : "12",
            h: hours % 12 > 0 ? hours % 12 : 12,
            H: hours,
            i: minutes < 10 ? '0' + minutes : minutes,
            s: seconds < 10 ? '0' + seconds : seconds           
        };

        // loop through format array of characters and add matching data else add the format character (:,/, etc.)
        var date_string = "";
        for(var i=0;i<dateFormat.length;i++){
            var f = dateFormat[i];
            if(f.match(/[a-zA-Z]/g)){
                date_string += date_props[f] ? date_props[f] : '';
            } else {
                date_string += f;
            }
        }

        return date_string;
    };
/*
 *
 * END - Date class extension
 * 
 ************************************/

注意(2022-10):toLocaleFormat已被弃用一段时间,并从Firefox版本58中删除。请参见LocaleFormat

我想你可以使用非标准的Date方法来LocaleFormat(formatString)

formatString:与C中strftime()函数期望的格式相同的格式字符串。

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011

参考文献:

到区域设置格式斯特夫蒂姆

如果您已经在项目中使用jQuery UI,您可以这样做:

var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));

// formatted will be 'Jul 8, 2014'

这里提供了一些可以使用的日期选择器日期格式选项。

如果您对格式的控制比当前接受的答案稍少,则可以使用Date#toLocaleDateString创建标准的特定于区域设置的渲染。区域设置和选项参数允许应用程序指定应使用其格式约定的语言,并允许对渲染进行一些自定义。

选项关键示例:

日期:当天的表示。可能的值为“数字”、“2位数”。工作日:工作日的表示。可能的值有“窄”、“短”、“长”。年份:年度的表示。可能的值为“数字”、“2位数”。月份:月份的表示。可能的值有“数字”、“2位数”、“窄”、“短”、“长”。小时:小时的表示。可能的值为“数字”、“2位数”。分钟:会议记录的表示。可能的值为“数字”、“2位数”。第二:第二个的表示。可能的值为“数字”和“2位”。

所有这些键都是可选的。您可以根据需要更改选项值的数量,这也将反映每个日期时间项的存在。

注意:如果您只想配置内容选项,但仍然使用当前区域设置,则为第一个参数传递null将导致错误。改用undefined。

对于不同的语言:

“en-US”:用于美式英语“en-GB”:用于英国英语“hi IN”:印地语“ja JP”:日语

您可以使用更多语言选项。

例如

var options={weeday:'long',year:'numeric',month:'long',day:'numeric'};var today=新日期();console.log(toLocaleDateString(“en-US”));//9/17/2016console.log(toLocaleDateString(“en-US”,选项));//2016年9月17日,星期六console.log(toLocaleDateString(“hi IN”,选项));//शनिवार, 17सितंबर 2016

您也可以使用toLocaleString()方法来实现同样的目的。唯一的区别是该函数提供了不传递任何选项的时间。

// Example
9/17/2016, 1:21:34 PM

参考文献:

toLocaleString()到LocaleDateString()