gpt4 book ai didi

javascript - jQuery 日期格式 [今天/明天/昨天/月-日] - 无法正常工作

转载 作者:搜寻专家 更新时间:2023-11-01 05:01:45 27 4
gpt4 key购买 nike

我想要实现的是,当我在这个函数中输入一个日期时,它应该给我这个:

如果日期是:

今天 - 输出为 今天
明天 - 输出为 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;
}​

注意:我更喜欢无插件的方式。

最佳答案

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;
}

演示:http://jsfiddle.net/xqnc8/4/

关于javascript - jQuery 日期格式 [今天/明天/昨天/月-日] - 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13496860/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com