如何将Date对象格式化为字符串?
当前回答
只需执行以下操作:-
let date = new Date().toLocaleDateString('en-us',{day: 'numeric'})
let month = new Date().toLocaleDateString('en-us',{month: 'long'})
let year = new Date().toLocaleDateString('en-us',{year: 'numeric'})
const FormattedDate = `${date}-${month}-${year}`
console.log(FormattedDate) // 26-March-2022
其他回答
字体版本
可以轻松增强以支持所需的任何格式字符串。当这样的通用解决方案非常容易创建,并且应用程序中经常出现日期格式时,我不建议在应用程序中对日期格式代码进行硬编码。这很难读懂,也隐藏了你的意图。格式字符串清楚地显示您的意图。
原型函数
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()
对于自定义分隔日期格式,必须拉出日期(或时间)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).
一行中请求的格式-没有库和Date方法,只有正则表达式:
var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')
在我的测试中,这在主要浏览器(Chrome、Safari、Firefox和IE)中可靠地工作。正如@RobG所指出的,Date.protype.toString()的输出依赖于实现,因此对于国际或非浏览器实现,只需测试输出,以确保它在JavaScript引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在执行正则表达式替换之前确保其与预期匹配。
你应该看看DayJs。它是momentJs的翻版,但模块化架构更轻。
快速2kB替代Moment.js,具有相同的现代API
Day.js是一个极简的JavaScript库,它使用Moment.js兼容的API为现代浏览器解析、验证、操作和显示日期和时间。如果您使用Moment.js,您已经知道如何使用Day.js。
var date=date.now();const formatedDate=dayjs(日期).format(“YYYY-MM-DD”)console.log(formatedDate);<script src=“https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js“crossoorigin=”匿名“></script>
在现代浏览器(*)中,您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
如果今天(1月24日)执行输出ᵗʰ, 2016):
'24-Jan-2016'
(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间版本。
推荐文章
- 一元加/数字(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?
- 如何检查动态附加的事件监听器是否存在?