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


当前回答

要获得“2010年8月10日”,请尝试:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

有关浏览器支持,请参阅toLocaleDateString。

其他回答

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。

要获得“2010年8月10日”,请尝试:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

有关浏览器支持,请参阅toLocaleDateString。

对于自定义分隔日期格式,必须拉出日期(或时间)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).

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

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js2010年8月10日为:

var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log(clock.day + '-' + str + '-' + clock.year); //gets you 10-Aug-2010