如何将Date对象格式化为字符串?
当前回答
这是一个完全符合您要求的脚本
https://github.com/UziTech/js-date-format
var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
其他回答
这可能有助于解决问题:
var d=新日期();var选项={day:'数字',月份:'long',年份:'数字'};console.log(d.toLocaleDateString('en-ZA',选项));
函数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
*
************************************/
如果你想要一个简短的、人类可读的函数,这个函数很容易调整以适合你。
timeStamp参数是1970年的毫秒-它由new Date().getTime()和许多其他设备返回。。。
好吧,我改变主意了。我包含了一个额外的零填充函数。诅咒!
function zeroPad(aNumber) {
return ("0"+aNumber).slice(-2);
}
function humanTime(timeStamp) {
var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
}
两个纯JavaScript单行程序
在这个答案中,我发展了JD Smith的想法。我能够缩短JD-Smith正则表达式。
let format=d=>d.toString().replace(/\w+(\w+)(\d+)(\d+).*/,'$2-$1-$3');console.log(格式(Date()));
Dave的也是基于JD Smith的想法,但他避免了正则表达式,并给出了一个非常好的解决方案——我稍微缩短了他的解决方案(通过更改拆分参数),并在包装器中使其不透明。
let format=(d,a=d.toString().split``)=>a[2]+“-”+a[1]+“-“+a[3];console.log(格式(Date()));
推荐文章
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 我怎么能计算在打字稿2日期之间的时间
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?
- 避免浏览器弹出窗口拦截器