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


当前回答

Use:

thisDate = new Date(parseInt(jsonDateString.replace('/Date(', '')));
formattedDate = (thisDate.getMonth() + 1) + "/" + (thisDate.getDate()+1) + "/" + thisDate.getFullYear();

这采用JSON日期“/date(1429573751663)/”,并生成格式化字符串:

"4/21/2015"

其他回答

这是一个完全符合您要求的脚本

https://github.com/UziTech/js-date-format

var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));

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

你不需要任何图书馆。只需提取日期组件并构造字符串。以下是如何获取YYYY-MM-DD格式。还要注意月份指数“一月是0,二月是1,依此类推。”

// @flow

type Components = {
  day: number,
  month: number,
  year: number
}

export default class DateFormatter {
  // YYYY-MM-DD
  static YYYY_MM_DD = (date: Date): string => {
    const components = DateFormatter.format(DateFormatter.components(date))
    return `${components.year}-${components.month}-${components.day}`
  }

  static format = (components: Components) => {
    return {
      day: `${components.day}`.padStart(2, '0'),
      month: `${components.month}`.padStart(2, '0'),
      year: components.year
    }
  }

  static components = (date: Date) => {
    return {
      day: date.getDate(),
      month: date.getMonth() + 1,
      year: date.getFullYear()
    }
  }
}

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

对于任何想要复制、粘贴和采用真正简单的ES6解决方案的人来说:

const dateToString=d=>`${d.getFullYear()}-${('00'+(d.getMonth()+1)).slice(-2)}-${('0'+d.getDate()).spice(-2)}`//如何使用:const myDate=新日期(Date.parse('04 Dec 1995 00:12:00 GMT'))console.log(dateToString(myDate))//1995-12-04