函数formatDate用于将日期对象转换成指定格式的字符串,语法如下:
var str = formatDate(date, pattern);
其中pattern的全格式为"yyyy-MM-dd HH:mm:ss"
使用范例如下:
var date = new Date(2001, 8, 11, 8, 26, 8);
formatDate(date, "yyyy"); 返回值: "2001"
formatDate(date, "yyyy-MM-dd"); 返回值: "2001-09-11"
formatDate(date, "yyyy-MM-dd HH"); 返回值: "2001-09-11 08"
formatDate(date, "yyyy-MM-dd HH:mm:ss"); 返回值: "2001-09-11 08:26:08"
请写出函数formatDate的实现代码。
JavaScript 一道作业题,帮忙做一下
答案:2 悬赏:60
解决时间 2021-02-16 18:10
- 提问者网友:烟刺痛了眼
- 2021-02-16 02:54
最佳答案
- 二级知识专家网友:疯山鬼
- 2021-02-16 03:27
var date = new Date(2001, 8, 11, 8, 26, 8);
function formatDate(date,pattern) {
var d = {
year:date.getFullYear(),
month:date.getMonth() < 10 ? '0'+date.getMonth() :date.getMonth() ,
day:date.getDate() < 10 ? '0'+date.getDate() : date.getDate(),
hours:date.getHours() < 10 ? '0'+date.getHours() : date.getHours(),
minutes:date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes(),
seconds:date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds()
},ret;
switch(pattern) {
case "yyyy":
ret = d.year;
break;
case "yyyy-MM-dd":
ret = d.year+'-'+d.month+'-'+d.day;
break;
case "yyyy-MM-dd HH":
ret = d.year+'-'+d.month+'-'+d.day+' '+d.hours;
break;
case "yyyy-MM-dd HH:mm:ss":
ret = d.year+'-'+d.month+'-'+d.day+' '+d.hours+':'+d.minutes+':'+d.seconds;
break;
default:
break;
}
return ret;
}
formatDate(date, "yyyy");
formatDate(date, "yyyy-MM-dd");
formatDate(date, "yyyy-MM-dd HH");
formatDate(date, "yyyy-MM-dd HH:mm:ss");
function formatDate(date,pattern) {
var d = {
year:date.getFullYear(),
month:date.getMonth() < 10 ? '0'+date.getMonth() :date.getMonth() ,
day:date.getDate() < 10 ? '0'+date.getDate() : date.getDate(),
hours:date.getHours() < 10 ? '0'+date.getHours() : date.getHours(),
minutes:date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes(),
seconds:date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds()
},ret;
switch(pattern) {
case "yyyy":
ret = d.year;
break;
case "yyyy-MM-dd":
ret = d.year+'-'+d.month+'-'+d.day;
break;
case "yyyy-MM-dd HH":
ret = d.year+'-'+d.month+'-'+d.day+' '+d.hours;
break;
case "yyyy-MM-dd HH:mm:ss":
ret = d.year+'-'+d.month+'-'+d.day+' '+d.hours+':'+d.minutes+':'+d.seconds;
break;
default:
break;
}
return ret;
}
formatDate(date, "yyyy");
formatDate(date, "yyyy-MM-dd");
formatDate(date, "yyyy-MM-dd HH");
formatDate(date, "yyyy-MM-dd HH:mm:ss");
全部回答
- 1楼网友:风格单纯
- 2021-02-16 04:59
function multiply(){
var args=arguments;
var result=0;
for(var i=0;i
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯