如何将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()
}
}
}
其他回答
在我的情况下,我已将日期表“2022年7月1日”格式化为“2022-07-01”
常量格式日期=日期=>{const d=新日期(日期)let month=(d.getMonth()+1).toString()let day=d.getDate().toString()const year=d.getFullYear()如果(月长度<2){月=“0”+月}如果(日长度<2){天=“0”+天}return[年,月,日]。join('-')}console.log(格式日期('01/07/2022'))
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解决方案:
var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
@Sébastien——可选的所有浏览器支持
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
基于Date.toLocaleDateString的高阶标记模板文本示例:
const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')
console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"
这可能有助于解决问题:
var d=新日期();var选项={day:'数字',月份:'long',年份:'数字'};console.log(d.toLocaleDateString('en-ZA',选项));
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?