如果日期是:
今天 - 输出为Today
明天 - 输出为Tomorrow
昨天 - 输出为Yesterday
否则 - 输出为“月 - 日”格式
但我不能让这个工作。有帮助吗? JsFiddle here。
//My Date variable
var mydate = "22-Nov-2012"
alert(MDFormat(mydate));
/*
If the date is:
Today - show as "Today";
Tomorrow - show as "Tomorrow"
Yesterday - show as "Yesterday"
Else - show in "Month - Day format"
*/
function MDFormat(MMDD) {
MMDD= new Date(MMDD);
var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var day = MMDD.getDate();
var month = months[MMDD.getMonth()];
var currentDay = new Date().getDay();
var today;
if (currentDay == MMDD.getDay()) {
today = MMDD.getDay();
}
var tmr = currentDay + 1;
var yest = currentDay - 1;
var strDate;
switch (MMDD) {
case today:
strDate = "Today";
break;
case tmr:
strDate = "Tomorrow";
break;
case yest:
strDate = "Yesterday";
break;
default:
strDate = month + "-" + day;
break;
}
return strDate;
}
注意:我更喜欢无插件方式。
答案 0 :(得分:10)
getDate
仅适用于有效的预定义日期格式。您使用的那个不是有效的预定义格式。如果你试试这个:
var mydate = "Nov 22, 2012";
alert(MDFormat(mydate));
它有效。
还冒昧地解决了你的逻辑问题:
//My Date variable
var mydate = "Nov 22, 2012"
alert(MDFormat(mydate));
/*
If the date is:
Today - show as "Today";
Tomorrow - show as "Tomorrow"
Yesterday - show as "Yesterday"
Else - show in "Month - Day format"
*/
function MDFormat(MMDD) {
MMDD = new Date(MMDD);
var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var strDate = "";
var today = new Date();
today.setHours(0, 0, 0, 0);
var yesterday = new Date();
yesterday.setHours(0, 0, 0, 0);
yesterday.setDate(yesterday.getDate() - 1);
var tomorrow = new Date();
tomorrow.setHours(0, 0, 0, 0);
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(MMDD.getTime(),today.getTime(),MMDD.getTime()==today.getTime());
if (today.getTime() == MMDD.getTime()) {
strDate = "Today";
} else if (yesterday.getTime() == MMDD.getTime()) {
strDate = "Yesterday";
} else if (tomorrow.getTime() == MMDD.getTime()) {
strDate = "Tomorrow";
} else {
strDate = months[MMDD.getMonth()] + "-" + MMDD.getDate();
}
return strDate;
}
答案 1 :(得分:0)
使用Datejs插件试用 - 它很容易使用。我为您准备了一个可能的解决方案,http://jsbin.com/otasiz/1/edit。还在下面:
var downTheRoad = "11/30/2012";
var yesterday = "11/20/2012";
var tomorrow = "11/22/2012";
var today = "11/21/2012";
test(downTheRoad);
test(yesterday);
test(tomorrow);
test(today);
function test(dateStr) {
var date = Date.parse(dateStr);
var today = Date.parse("today");
var todayStr = today.toString("MM/dd/yyyy");
var tomorrow = Date.parse("tomorrow");
var tomorrowStr = tomorrow.toString("MM/dd/yyyy");
var yesterday = Date.parse("yesterday");
var yesterdayStr = yesterday.toString("MM/dd/yyyy");
if (dateStr === todayStr) {
alert(dateStr + " as today");
} else if (dateStr === tomorrowStr) {
alert(dateStr + " as tomorrow");
} else if (dateStr === yesterdayStr) {
alert(dateStr + " as yesterday");
}
else {
alert(dateStr + " as " + Date.parse(dateStr).toString("MMM-dd"));
}
}