如何将Date对象格式化为字符串?
当前回答
函数convert_month(i=0,option=“num”){//i=索引变量对象月=[{num:01,短:“Jan”,长:“Janer”},{num:02,短:“Feb”,长:“Februari”},{num:03,短:“Mar”,长:“March”},{num:04,短:“Apr”,长:“April”},{num:05,短:“May”,长:“May”},{num:06,短:“Jun”,长:“Juni”},{num:07,短:“Jul”,长:“July”},{num:08,短:“Aug”,长:“August”},{num:09,短:“Sep”,长:“Sept”},{num:10,短:“Oct”,长:“Octo”},{num:11,短:“Nov”,长:“十一月”},{num:12,短:“Dec”,长:“十二月”}];返回object_months[i][option];}var d=新日期();// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascriptvar num=`${d.getDate()}-${convert_month(d.getMonth())}--${d.getFullYear()}';var short=`${d.getDate()}-${convert_month(d.getMonth(),“short”)}-${d.getFullYear()}`;var long=`${d.getDate()}-${convert_month(d.getMonth(),“long”)}-${d.getFullYear()}`;document.querySelector(“#num”).innerHTML=num;document.querySelector(“#short”).innerHTML=短;document.querySelector(“#long”).innerHTML=long;<p>数字:<span id=“num”></span>(默认值)</p><p>短:<span id=“Short”></span></p><p>长:<span id=“Long”></span></p>
其他回答
这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿了PHP日期格式功能,以满足我的需要。请随意使用它,它只是扩展了现有的Date()对象。这可能不是最优雅的解决方案,但它符合我的需求。
var d = new Date();
d_string = d.format("m/d/Y h:i:s");
/**************************************
* Date class extension
*
*/
// Provide month names
Date.prototype.getMonthName = function(){
var month_names = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
return month_names[this.getMonth()];
}
// Provide month abbreviation
Date.prototype.getMonthAbbr = function(){
var month_abbrs = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
return month_abbrs[this.getMonth()];
}
// Provide full day of week name
Date.prototype.getDayFull = function(){
var days_full = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
return days_full[this.getDay()];
};
// Provide full day of week name
Date.prototype.getDayAbbr = function(){
var days_abbr = [
'Sun',
'Mon',
'Tue',
'Wed',
'Thur',
'Fri',
'Sat'
];
return days_abbr[this.getDay()];
};
// Provide the day of year 1-365
Date.prototype.getDayOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
};
// Provide the day suffix (st,nd,rd,th)
Date.prototype.getDaySuffix = function() {
var d = this.getDate();
var sfx = ["th","st","nd","rd"];
var val = d%100;
return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
};
// Provide Week of Year
Date.prototype.getWeekOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
// Provide if it is a leap year or not
Date.prototype.isLeapYear = function(){
var yr = this.getFullYear();
if ((parseInt(yr)%4) == 0){
if (parseInt(yr)%100 == 0){
if (parseInt(yr)%400 != 0){
return false;
}
if (parseInt(yr)%400 == 0){
return true;
}
}
if (parseInt(yr)%100 != 0){
return true;
}
}
if ((parseInt(yr)%4) != 0){
return false;
}
};
// Provide Number of Days in a given month
Date.prototype.getMonthDayCount = function() {
var month_day_counts = [
31,
this.isLeapYear() ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
return month_day_counts[this.getMonth()];
}
// format provided date into this.format format
Date.prototype.format = function(dateFormat){
// break apart format string into array of characters
dateFormat = dateFormat.split("");
var date = this.getDate(),
month = this.getMonth(),
hours = this.getHours(),
minutes = this.getMinutes(),
seconds = this.getSeconds();
// get all date properties ( based on PHP date object functionality )
var date_props = {
d: date < 10 ? '0'+date : date,
D: this.getDayAbbr(),
j: this.getDate(),
l: this.getDayFull(),
S: this.getDaySuffix(),
w: this.getDay(),
z: this.getDayOfYear(),
W: this.getWeekOfYear(),
F: this.getMonthName(),
m: month < 10 ? '0'+(month+1) : month+1,
M: this.getMonthAbbr(),
n: month+1,
t: this.getMonthDayCount(),
L: this.isLeapYear() ? '1' : '0',
Y: this.getFullYear(),
y: this.getFullYear()+''.substring(2,4),
a: hours > 12 ? 'pm' : 'am',
A: hours > 12 ? 'PM' : 'AM',
g: hours % 12 > 0 ? hours % 12 : 12,
G: hours > 0 ? hours : "12",
h: hours % 12 > 0 ? hours % 12 : 12,
H: hours,
i: minutes < 10 ? '0' + minutes : minutes,
s: seconds < 10 ? '0' + seconds : seconds
};
// loop through format array of characters and add matching data else add the format character (:,/, etc.)
var date_string = "";
for(var i=0;i<dateFormat.length;i++){
var f = dateFormat[i];
if(f.match(/[a-zA-Z]/g)){
date_string += date_props[f] ? date_props[f] : '';
} else {
date_string += f;
}
}
return date_string;
};
/*
*
* END - Date class extension
*
************************************/
嗯,我想要的是将今天的日期转换为MySQL友好的日期字符串,如2012-06-23,并在我的一个查询中使用该字符串作为参数。我找到的简单解决方案是:
var today = new Date().toISOString().slice(0, 10);
请记住,上述解决方案没有考虑您的时区偏移。
您可以考虑改用此函数:
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
这将为您提供正确的日期,以防您在一天的开始/结束时执行此代码。
var date=新日期();函数到本地(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON();}函数到JSONLocal(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON().slice(0,10);}//查看您的devtools控制台console.log(date.toJSON());console.log(date.toISOString());console.log(toLocal(日期));console.log(toJSONLocal(日期));
日期.toISOString日期.toJSON字符串切片外部示例
在JavaScript中格式化DateTime的一种有用且灵活的方法是Intl.DateTimeFormat:
var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));
结果是:“2017年10月12日”
可以使用options参数自定义日期和时间格式。
Intl.DateTimeFormat对象是启用语言敏感日期和时间格式的对象的构造函数。
语法
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
参数
区域设置
可选择的带有BCP 47语言标记的字符串或此类字符串的数组。有关locales参数的一般形式和解释,请参阅Intl页。允许使用以下Unicode扩展密钥:
nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".
选项
可选择的具有以下部分或全部财产的对象:
本地匹配器
要使用的区域设置匹配算法。可能的值是“查找”和“最佳匹配”;默认值为“最佳拟合”。有关此选项的信息,请参阅Intl页面。
时区
要使用的时区。实现必须识别的唯一值是“UTC”;默认值是运行时的默认时区。实施还可以识别IANA时区数据库的时区名称,例如“亚洲/上海”、“亚洲/加尔各答”、“美国/纽约”。
小时12
是否使用12小时(而不是24小时)。可能的值为true和false;默认值取决于区域设置。
格式匹配器
要使用的格式匹配算法。可能的值是“基本”和“最适合”;默认值为“最佳拟合”。有关使用此属性的信息,请参见以下段落。
以下财产描述了格式化输出中使用的日期时间组件及其所需的表示。需要实现至少支持以下子集:
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
实现可能支持其他子集,并且将针对所有可用的子集表示组合来协商请求,以找到最佳匹配。有两种算法可用于此协商,并由formatMatcher属性选择:完全指定的“基本”算法和依赖于实现的“最佳匹配”算法。
周工作日
工作日的表示。可能的值有“窄”、“短”、“长”。
era
时代的代表。可能的值有“窄”、“短”、“长”。
year
年度的表示。可能的值为“数字”、“2位数”。
月
月份的表示。可能的值有“数字”、“2位数”、“窄”、“短”、“长”。
day
当天的表示。可能的值为“数字”、“2位数”。
hour
小时的表示。可能的值为“数字”、“2位数”。
分钟
会议记录的表示。可能的值为“数字”、“2位数”。
第二
第二个的表示。可能的值为“数字”、“2位数”。
时区名称
时区名称的表示形式。可能的值为“短”、“长”。每个日期时间组件属性的默认值未定义,但如果所有组件财产均未定义,则假定年、月和日为“数字”。
联机检查
更多详细信息
使用此步骤
const MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','9','Oct','Nov','Dec']const date=新日期()const dateString=`${date.getDate()}-${MONTHS[date.getMonth()]}--${date.getFullYear()}`console.log(dateString)
字体版本
可以轻松增强以支持所需的任何格式字符串。当这样的通用解决方案非常容易创建,并且应用程序中经常出现日期格式时,我不建议在应用程序中对日期格式代码进行硬编码。这很难读懂,也隐藏了你的意图。格式字符串清楚地显示您的意图。
原型函数
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()
推荐文章
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 我怎么能计算在打字稿2日期之间的时间
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?
- 避免浏览器弹出窗口拦截器