Javascript 根据当前日期获取日期的名称
我需要能够获得以下信息:Javascript 根据当前日期获取日期的名称,javascript,date,Javascript,Date,我需要能够获得以下信息: function changeDate(date) { var d = new Date(); if(d) // check if in the current week { return date.format(EEE); }else if() //check if out of the week { return date.format(d MMM); } } 检查我的当前日期是否为本周的周一-周日,如
function changeDate(date)
{
var d = new Date();
if(d) // check if in the current week
{
return date.format(EEE);
}else if() //check if out of the week
{
return date.format(d MMM);
}
}
检查我的当前日期是否为本周的周一-周日,如果我在本周,我应该能够返回一个日期名称,格式为三个字母MON-for Monday EEE格式
如果我不在本周,我需要用三个字母的month d MMM格式返回日期,例如3月11日
我尝试了以下方法:
function changeDate(date)
{
var d = new Date();
if(d) // check if in the current week
{
return date.format(EEE);
}else if() //check if out of the week
{
return date.format(d MMM);
}
}
日期的格式为MM/dd/yyyy HH:MM假设当前日期是指给定日期
试试这个:
function getWeek(d) {
var target = new Date(d.valueOf());
var dayNr = (d.getDay() + 6) % 7;
target.setDate(target.getDate() - dayNr + 3);
var jan4 = new Date(target.getFullYear(), 0, 4);
var dayDiff = (target - jan4) / 86400000;
var weekNr = 1 + Math.ceil(dayDiff / 7);
return weekNr;
}
function changeDate(date) {
var d = new Date();
return getWeek(d) == getWeek(date)?
date.toString().substring(0,3).toUpperCase():
b.getDate() + " " + b.toString().substring(3,7).toUpperCase();
}
getWeek是从哪里来的
示例用法:
var a = new Date("Feb 14 2014"),
b = new Date("Mar 15 2014");
changeDate(a); // "FRI"
changeDate(b); // "15 MAR"
此方法getCalWeek将为您提供一个对象,其中包含给定日期的周和年
function thursday(mydate) {
var Th=new Date();
Th.setTime(mydate.getTime() + (3-((mydate.getDay()+6) % 7)) * 86400000);
return Th;
}
function getCalWeek(thedate) {
ThursDate=thursday(thedate);
weekYear=ThursDate.getFullYear();
ThursWeek1=thursday(new Date(weekYear,0,4));
theweek=Math.floor(1.5+(ThursDate.getTime()-ThursWeek1.getTime())/86400000/7);
return {"week": theweek, "year" : weekYear};
}
然后您可以比较两个日期的周和年
var weekdays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
function changeDate(date) {
d = new Date(); // today
weekAndYearToday = getCalWeek(d);
weekAndYearDate = getCalWeek(date);
if(weekAndYearToday.week = weekAndYearDate.week && weekAndYearToday.year = weekAndYearDate.year) {
// here it is clear that "date" is in the current week
return weekdays[date.getDay()];
} else {
return date.getDate() + " " + months[date.getMonth()];
}
}
当您提供验证日期和测试周时,下面的代码应该为您提供所需的日期 它已经过单元测试
您当前的日期一定是当前的一周吗?你可能没有解释清楚-你能举个例子说明你认为这是错误的吗?听起来像是算法问题。。