如何将Date对象格式化为字符串?
当前回答
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
其他回答
尽管new Date().toISOString().slice(0,10);对于我的正常用例来说,这是一个非常时髦的风格,我不喜欢前几个更为定制的字符串的答案,我给了自己几分钟的时间,让自己尽可能地时髦一点。
我没有看到我提出的解决方案,所以这里是。。。
((d,x)=>`${d.getFullYear()}-${x(d.getMonth()+1)}-${x(d.getDate())}`)
(new Date(), (x)=>x.toString().padStart(2,"0"))
// today that produces
// '2022-09-28'
// the same as new Date().toISOString().slice(0, 10)
// but provides a good framework for other orders or values
伪IIFE获胜。
这里解决的问题当然是。。。
您可能需要使用前导零将天数和月份设置为小于10。因此,传入一个将强制转换为string&padStarts的函数。您需要在那里获得相同的日期,而不需要反复使用新的date()。获取“now”(newDate())并作为参数传入以供重用。你必须为getMonth添加1。这样做。
即使你需要映射到月份缩写之类的东西,你也可以使用类似的技巧,这并不是很可爱。
((d,x,y)=>`${x(d.getDate())} ${y(d.getMonth())} ${d.getFullYear()}`)
(
new Date(),
(x)=>x.toString().padStart(2,"0"),
(m)=>"jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec".split(',')[m]
)
// As of this writing, that yields...
// '28 sep 2022'
(显然,为了增加清晰度,两者都去掉了空格;不希望代码块滚动)
…尽管我很难推荐这样做,但出于某种奇怪的原因,我只能从控制台创建测试值。真的很奇怪,没有toString('yyyy-mm-dd'),这是我所能做到的。
一个简单的函数,可以返回日期、日期+时间或仅返回时间:
var myDate = dateFormatter("2019-01-24 11:33:24", "date-time");
// >> RETURNS "January 24, 2019 11:33:24"
var myDate2 = dateFormatter("2019-01-24 11:33:24", "date");
// >> RETURNS "January 24, 2019"
var myDate3 = dateFormatter("2019-01-24 11:33:24", "time");
// >> RETURNS "11:33:24"
function dateFormatter(strDate, format){
var theDate = new Date(strDate);
if (format=="time")
return getTimeFromDate(theDate);
else{
var dateOptions = {year:'numeric', month:'long', day:'numeric'};
var formattedDate = theDate.toLocaleDateString("en-US", + dateOptions);
if (format=="date")
return formattedDate;
return formattedDate + " " + getTimeFromDate(theDate);
}
}
function getTimeFromDate(theDate){
var sec = theDate.getSeconds();
if (sec<10)
sec = "0" + sec;
var min = theDate.getMinutes();
if (min<10)
min = "0" + min;
return theDate.getHours() + ':'+ min + ':' + sec;
}
字体版本
可以轻松增强以支持所需的任何格式字符串。当这样的通用解决方案非常容易创建,并且应用程序中经常出现日期格式时,我不建议在应用程序中对日期格式代码进行硬编码。这很难读懂,也隐藏了你的意图。格式字符串清楚地显示您的意图。
原型函数
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()
你不需要任何图书馆。只需提取日期组件并构造字符串。以下是如何获取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()
}
}
}
大家好,我有一个代码,用于为日期添加日期和格式。
const FechaMaxima = new Date();
FechaMaxima.setDate(FechaMaxima.getDate() + 6);
FechaMaxima.toISOString().substring(0, 10);