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


当前回答

将日期格式化为不同格式

let objectDate=新日期();let day=objectDate.getDate();console.log(天);//12let currentmo=objectDate.getMonth();月=当前月+1;console.log(月+1);//1.let year=objectDate.getFullYear();console.log(年);//2023//现在您可以相应地进行设置//日/月/年console.log(日+‘/‘+月+‘/’+年);//年/月/日console.log(月+'/'+day+'/'+年);

尝试此代码-https://bbbootstrap.com/code/format-date-javascript-49065802

其他回答

这是修改为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()));

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

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夜间版本。

对于自定义分隔日期格式,必须拉出日期(或时间)DateTimeFormat对象(它是ECMAScript国际化API),然后手动创建字符串使用所需的分隔符。

为此,可以使用DateTimeFormat#formatToParts。你可以销毁数组,但这并不理想,因为数组输出取决于区域设置:

{//示例1设f=新Intl.DateTimeFormat('en');让a=f.formatToParts();控制台日志(a);}{//示例2设f=新Intl.DateTimeFormat('hi');让a=f.formatToParts();控制台日志(a);}

最好将格式数组映射到结果字符串:

函数连接(t,a,s){函数格式(m){设f=新Intl.DateTimeFormat('en',m);返回f.format(t);}返回.map(格式).join(s);}让a=〔{日:‘数字’},{月:‘短’}、{年:‘数字”}〕;let s=join(新日期,a,'-');console.log;

还可以使用DateTimeFormat#格式,但请注意,使用此方法时,截至3月2020年,当涉及到分钟和秒的前导零(该方法避免了此错误以上)。

设d=新日期(2010,7,5);let ye=新Intl.DateTimeFormat('en',{year:'numeric'}).format(d);let mo=新Intl.DateTimeFormat('en',{month:'short'}).format(d);let da=新Intl.DateTimeFormat('en',{day:'2-位'}).format(d);console.log(`${da}--${mo}-${ye}');

在处理日期和时间时,通常值得使用库(例如,luxon、date fns、moment.js不建议用于新项目),因为该领域有许多隐藏的复杂性。

注意,上述解决方案中使用的ECMAScript国际化APIIE10不支持(2月全球浏览器市场份额为0.03%)2020).

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

yy=2位年份;yyyy=全年

M=数字月;MM=2位月;MMM=短月份名称;MMMM=完整月份名称

EEEE=工作日全名;EEE=短工作日名称

d=数字日;dd=2位数字日

h=小时;hh=2位数小时

m=分钟;mm=2位数分钟

s=秒;ss=2位数秒

S=毫秒

使用与ClassSimpleDateFormat(Java)类似的格式

var month名称=[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”、“九月”、“十月”、“十一月”、“十二月”];var dayOfWeekNames=[“星期日”、“星期一”、“周二”,“周三”、“周四”、“周五”、“周六”];函数formatDate(日期,formatStr){if(!formatStr){formatStr='dd/mm/yyyy';}var day=date.getDate(),month=date.getMonth(),year=date.getFullYear(),hour=date.getHours(),minute=date.getMinutes(),second=date.getSeconds(),毫秒=date.getMilliseconds(),hh=twoDigitPad(小时),mm=两个DigitPad(分钟),ss=twoDigitPad(秒),EEEE=dayOfWeekNames[date.getDay()],EEE=EEEE.substr(0,3),dd=twoDigitPad(天),M=月+1,MM=两个DigitPad(M),MMMM=monthNames[月],MMM=MMMM.substr(0,3),yyyy=年+“”,yy=yyyy.substr(2,2);返回格式Str.replace('h',hh).replace('h',hour).替换('m',mm).替换(m',分钟).替换('s',ss).替换(s'',second).replace('S',毫秒)替换('dd',dd)替换('d',day).替换('MMMM',MMMM).替换('MMM',MMM)替换('MM',MM).更换('M',M)替换('EEE',EEEE)替换('EE',EEE)替换('yyyy',yyyy).替换('yy',yy);}函数twoDigitPad(num){返回num<10?“0”+num:num;}console.log(formatDate(newDate()));console.log(formatDate(new Date(),'EEEE,MMMM d,yyyy hh:mm:ss:S'));console.log(formatDate(new Date(),'EEE,MMM d,yyyy hh:mm'));console.log(formatDate(new Date(),'yyyy-MM-dd hh:MM:ss:S'));console.log(formatDate(new Date(),'yy MM dd hh:MM'));