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


当前回答

一个简单的函数,可以返回日期、日期+时间或仅返回时间:

var myDate = dateFormatter("2019-01-24 11:33:24", "date-time");
// >> RETURNS "January 24, 2019 11:33:24"

var myDate2 = dateFormatter("2019-01-24 11:33:24", "date");
// >> RETURNS "January 24, 2019"

var myDate3 = dateFormatter("2019-01-24 11:33:24", "time");
// >> RETURNS "11:33:24"


function dateFormatter(strDate, format){
    var theDate = new Date(strDate);
    if (format=="time")
       return getTimeFromDate(theDate);
    else{
       var dateOptions = {year:'numeric', month:'long', day:'numeric'};
       var formattedDate = theDate.toLocaleDateString("en-US", + dateOptions);
       if (format=="date")
           return formattedDate;
       return formattedDate + " " + getTimeFromDate(theDate);
    }
}

function getTimeFromDate(theDate){
    var sec = theDate.getSeconds();
    if (sec<10)
        sec = "0" + sec;
    var min = theDate.getMinutes();
    if (min<10)
        min = "0" + min;
    return theDate.getHours() + ':'+ min + ':' + sec;
}

其他回答

我使用以下方法。它很简单,工作正常。

 var dtFormat = require('dtformat');
   var today = new Date();
   dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");

或者这个:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate()  + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)

如果您对格式的控制比当前接受的答案稍少,则可以使用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()

这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿了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
 * 
 ************************************/

一行中请求的格式-没有库和Date方法,只有正则表达式:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

在我的测试中,这在主要浏览器(Chrome、Safari、Firefox和IE)中可靠地工作。正如@RobG所指出的,Date.protype.toString()的输出依赖于实现,因此对于国际或非浏览器实现,只需测试输出,以确保它在JavaScript引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在执行正则表达式替换之前确保其与预期匹配。

如果您已经在项目中使用ExtJS,则可以使用Ext.Date:

var date = new Date();
Ext.Date.format(date, "d-M-Y");

返回:

"11-Nov-2015"