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


当前回答

简短、广泛兼容的方法:

function formatDate(date) {
    date.toISOString()
    .replace(/^(\d+)-(\d+)-(\d+).*$/, // Only extract Y-M-D
        function (a,y,m,d) {
            return [
                d, // Day
                ['Jan','Feb','Mar','Apr','May','Jun',  // Month Names
                'Jul','Ago','Sep','Oct','Nov','Dec']
                [m-1], // Month
                y  // Year
            ].join('-') // Stitch together
        })
}

或者,作为单行:

date.toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).(\d+)Z$/, function (a,y,m,d) {return [d,['Jan','Feb','Mar','Apr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'][m-1],y].join('-')})

其他回答

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

字体版本

可以轻松增强以支持所需的任何格式字符串。当这样的通用解决方案非常容易创建,并且应用程序中经常出现日期格式时,我不建议在应用程序中对日期格式代码进行硬编码。这很难读懂,也隐藏了你的意图。格式字符串清楚地显示您的意图。

原型函数

interface Date {
    format(formatString: string): string;
}

Date.prototype.format = function (formatString: string): string {
  return Object.entries({
    YYYY: this.getFullYear(),
    YY: this.getFullYear().toString().substring(2),
    yyyy: this.getFullYear(),
    yy: this.getFullYear().toString().substring(2),
    MMMM: this.toLocaleString('default', { month: 'long' }),
    MMM: this.toLocaleString('default', { month: 'short' }),
    MM: (this.getMonth() + 1).toString().padStart(2, '0'),
    M: this.getMonth() + 1,
    DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
    DDD: this.toLocaleDateString('default', { weekday: 'short' }),
    DD: this.getDate().toString().padStart(2, '0'),
    D: this.getDate(),
    dddd: this.toLocaleDateString('default', { weekday: 'long' }),
    ddd: this.toLocaleDateString('default', { weekday: 'short' }),
    dd: this.getDate().toString().padStart(2, '0'),
    d: this.getDate(),
    HH: this.getHours().toString().padStart(2, '0'), // military
    H: this.getHours().toString(), // military
    hh: (this.getHours() % 12).toString().padStart(2, '0'),
    h: (this.getHours() % 12).toString(),
    mm: this.getMinutes().toString().padStart(2, '0'),
    m: this.getMinutes(),
    SS: this.getSeconds().toString().padStart(2, '0'),
    S: this.getSeconds(),
    ss: this.getSeconds().toString().padStart(2, '0'),
    s: this.getSeconds(),
    TTT: this.getMilliseconds().toString().padStart(3, '0'),
    ttt: this.getMilliseconds().toString().padStart(3, '0'),
    AMPM: this.getHours() < 13 ? 'AM' : 'PM',
    ampm: this.getHours() < 13 ? 'am' : 'pm',
  }).reduce((acc, entry) => {
    return acc.replace(entry[0], entry[1].toString())
  }, formatString)
}

Javascript版本

同样,只需删除接口,以及冒号及其关联冒号之后的类型名称。

demo

function unitTest() {
    var d: Date = new Date()
    console.log(d.format('MM/dd/yyyy hh:mm:ss')) // 12/14/2022 03:38:31
    console.log(d.format('yyyy-MM-dd HH:mm:ss')) // 2022-12-14 15:38:31
}

unitTest()

为了将日期格式化为例如2010年8月10日,您可能需要使用.toDateString()和ES6数组析构函数。

const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'

const [, month, day, year] = formattedDate.split(' ')

const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')

我知道有人可能会说这是一个愚蠢的解决方案,但它确实做到了从日期字符串中删除不必要的信息。

yourDateObject生成:

2017年12月13日星期三20:40:40 GMT+0200(欧洲东部时间)

yourDateObject.toString().sslice(0,15);生产:

2017年12月13日星期三