经过几次搜索,我找不到我想要的东西.我正在使用jquery datepicker返回一个看起来像的日期字符串,Day, Month Date, YYYY我正在寻找一个库或一些方法,将其转换为
the second Tuesday of the month,或the fourth Thursday of the month.到目前为止它似乎是jquery的,prettyDate并EasyDate没有我正在寻找的功能,我希望避免手动这样做!
谢谢,亚历克斯
您不需要日期库 - 只需取日期,除以7并向上舍入.
//format: Day, Month Date, YYYY
var ordinals = ["", "first", "second", "third", "fourth", "fifth"];
var date = "Friday, May 10, 2013";
var tokens = date.split(/[ ,]/);
// tokens = ["Friday", "", "May", "10", "", "2013"];
console.log( "The " + ordinals[Math.ceil(tokens[3]/7)] + " " + tokens[0] + " of the month");
Run Code Online (Sandbox Code Playgroud)
如果 momentjs 不适合您,这是我当天使用的脚本(尽管我确实认为 momentjs 是更好的解决方案)。
/*
Parameters:
index: n'th occurrence of the specified day
day: daynumber - javascript way where sunday is 0 and is saturday is 6
month: javascript way which is 0-11 [optional - defaults to current]
year: Full year - four digits [optional - defaults to current]
*/
function getNthDayOfMonth(index,day,month,year){
// Create date object
var date = new Date();
// Set to first day of month
date.setDate(1);
// If supplied - set the month
if(month!==''&&month!==undefined){
// Set month
date.setMonth(month);
}else{
month = date.getMonth();
}
// If supplied - set the year
if(year!==''&&year!==undefined){
// Set year
date.setFullYear(year);
}else{
year = date.getFullYear();
}
// Find daynumber
firstDay = date.getDay();
// Find first friday.
while(date.getDay()!=day){
date.setDate(date.getDate()+1) ;
}
switch(index){
case 2:
date.setDate(date.getDate()+7);
break;
case 3:
date.setDate(date.getDate()+14);
break;
case 4:
date.setDate(date.getDate()+21);
break;
case 5:
date.setDate(date.getDate()+28);
if(date.getMonth()!==month){
date = null;
}
break;
}
return date;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4029 次 |
| 最近记录: |