如何将Date对象格式化为字符串?
当前回答
我们有很多解决方案,但我认为最好的是Moment.js。所以我个人建议将Moment.jss用于日期和时间操作。
console.log(moment().format('DD-MMM-YYYY'));<script src=“//cdnjs.cloudflare.com/ajax/libs/ment.js/2.14.1/moment.min.js”></script>
其他回答
该模块可以轻松处理几乎所有的情况。它是一个更大的npm包的一部分,由Locutus提供,该包包含多种功能,但它可以完全独立于包本身使用,如果不使用npm(从模块更改为仅功能),只需复制粘贴/调整一点即可。
作为第二个参数,它接受时间戳,它可以来自任何地方,例如Date.getTime()。
此外,Locutus还在locatus包中维护了一个更大的datetime模块,这将提供一种更面向对象的使用方法。
在这里,您可以看到其他日期时间函数(作为模块),这些函数也非常有用。
您可以在这里找到关于参数和格式字符串的文档(注意,文档站点是一个PHP站点,但locatus实现遵循完全相同的规范)。
日期模块示例
date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'
date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'
date('Y W o', 1062462400)//'2003 36 2003'
var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09 10
date('W', 1104534000) //'52'
date('B t', 1104534000) //'999 31'
date('W U', 1293750000.82); // 2010-12-31 '52 1293750000'
date('W', 1293836400); // 2011-01-01 '52'
date('W Y-m-d', 1293974054); // 2011-01-02 '52 2011-01-02'
这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式。它模仿了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
*
************************************/
将日期格式化为不同格式
let objectDate=新日期();let day=objectDate.getDate();console.log(天);//12let currentmo=objectDate.getMonth();月=当前月+1;console.log(月+1);//1.let year=objectDate.getFullYear();console.log(年);//2023//现在您可以相应地进行设置//日/月/年console.log(日+‘/‘+月+‘/’+年);//年/月/日console.log(月+'/'+day+'/'+年);
尝试此代码-https://bbbootstrap.com/code/format-date-javascript-49065802
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
在现代浏览器(*)中,您可以这样做:
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夜间版本。
推荐文章
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 我怎么能计算在打字稿2日期之间的时间
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?
- 避免浏览器弹出窗口拦截器