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


当前回答

Javascript Intl.DateTimeFormat方法提供了一种格式化日期的方便方法。

以下是如何构建所需格式:

常量日期=新日期(“2010-08-10”);let d=新Intl.DateTimeFormat('en-GB',{年:“数字”,月:“短”,日:“2位数”}).format(日期).split(“”).join(“-”);console.log(d);

其他回答

如果你想要一个简短的、人类可读的函数,这个函数很容易调整以适合你。

timeStamp参数是1970年的毫秒-它由new Date().getTime()和许多其他设备返回。。。

好吧,我改变主意了。我包含了一个额外的零填充函数。诅咒!

 function zeroPad(aNumber) {
     return ("0"+aNumber).slice(-2);
 }
 function humanTime(timeStamp) {
    var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
    return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
 }

DateFormatter.formatDate(新日期(2010,7,10),'DD-MMM-YYYY')

=>2010年8月10日

DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss')

=>2017-11-22 19:52:37

DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a')

=>2002年2月2日星期三2005年2月5日,2003年3月3日,4月4日,5月5日上午

var日期格式设置工具={月份名称:[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”],dayName:[“星期日”、“星期一”、“周二”、“周三”、“周四”、“周五”、“周六”],formatDate:函数(日期,格式){var self=this;format=self.getProperDigits(format,/d+/gi,date.getDate());format=self.getProperDigits(格式,/M+/g,date.getMonth()+1);format=format.replace(/y+/gi,函数(y){var len=y.length;var year=date.getFullYear();如果(长度==2)return(年份+“”).sslice(-2);否则如果(len==4)回归年;返回y;})format=self.getProperDigits(格式,/H+/g,date.getHours());format=self.getProperDigits(格式,/h+/g,self.getHours12(date.getHours()));format=self.getProperDigits(format,/m+/g,date.getMinutes());format=self.getProperDigits(format,/s+/gi,date.getSeconds());format=format.replace(/a/ig,函数(a){var amPm=self.getAmPm(date.getHours())如果(a==“a”)返回amPm.toUpperCase();返回amPm;})format=self.getFullOr3Letters(format,/d+/gi,self.dayNames,date.getDay())format=self.getFullOr3Letters(format,/M+/g,self.monthNames,date.getMonth())返回格式;},getProperDigits:函数(格式、正则表达式、值){return format.replace(正则表达式,函数(m){var长度=m.length;如果(长度==1)返回值;否则如果(长度==2)return(“0”+值).sslice(-2);返回m;})},getHours12:函数(小时){// https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method返回(小时+24)%12||12;},getAmPm:函数(小时){// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format回程时间>=12?'下午':'上午';},getFullOr3Letters:函数(格式,正则表达式,名称数组,值){return format.replace(正则表达式,函数){var len=s.length;如果(长度==3)return nameArray[value].substr(0,3);否则如果(len==4)return nameArray[value];返回s;})}}console.log(DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss'));console.log(DateFormatter.formatDate(new Date(),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));console.log(DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));

格式描述取自Ionic Framework(它不支持Z、UTC时区偏移)

未彻底测试

在现代浏览器(*)中,您可以这样做:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');

如果今天(1月24日)执行输出ᵗʰ, 2016):

'24-Jan-2016'

(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间版本。

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