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


当前回答

你不需要任何图书馆。只需提取日期组件并构造字符串。以下是如何获取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()
    }
  }
}

其他回答

var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();

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

yourDateObject生成:

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

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

2017年12月13日星期三

截至2019年,您似乎可以使用LocaleDateString仅返回某些部分,然后您可以根据需要加入它们:

var date = new Date();

console.log(date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + "-"+ date.toLocaleDateString("en-US", { month: 'short' })
            + "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> 16-Nov-2019

console.log(date.toLocaleDateString("en-US", { month: 'long' }) 
            + " " + date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> November 16, 2019

Date构造函数(和Date.parse())在构造日期时只接受一种格式作为参数,即ISO 8601:

// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')

但由于浏览器的差异和不一致性,强烈不建议从字符串中解析(MDN建议不要使用日期字符串创建日期)。

建议的替代方法是直接从数字数据构建Date实例,如下所示:

new Date(2017, 7, 15) // Month is zero-indexed

这就是解析。现在,要将日期格式化为所需的字符串,您有几个date对象的本地选项(尽管我认为没有一个符合您所需的格式):

date.toString()       // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString()   // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString()    // '2019-01-23T09:23:42.079Z'

对于其他格式选项,恐怕您必须使用Moment.js、day.js等库。

这篇文章中的日期格式提示归功于Zell Liew。

两个纯JavaScript单行程序

在这个答案中,我发展了JD Smith的想法。我能够缩短JD-Smith正则表达式。

let format=d=>d.toString().replace(/\w+(\w+)(\d+)(\d+).*/,'$2-$1-$3');console.log(格式(Date()));

Dave的也是基于JD Smith的想法,但他避免了正则表达式,并给出了一个非常好的解决方案——我稍微缩短了他的解决方案(通过更改拆分参数),并在包装器中使其不透明。

let format=(d,a=d.toString().split``)=>a[2]+“-”+a[1]+“-“+a[3];console.log(格式(Date()));