繁体   English   中英

从给定日期获取工作日

[英]Get the week day from a given date

我正在编写自己的日历插件,但正在努力获取给定日期的星期几。

假设我有1905年,月-4天和23天。有什么办法可以使用此数据-将其以更好的格式粉碎在一起,例如YYYY / DD / MM并使用它来计算一周中的一天-我希望找到一些类似PHP的公历日历方法,但是我还没有找到。

抱歉,如果以前已经有人问过这个问题,但是我只能使用星期几中的新日期来查找问题。

构造一个日期对象并询问它是星期几:

// Note months are zero indexed so May is 4, not 5
var d = new Date(1905, 4, 23).getDay(); // 2

您可以将其变成一个函数:

function getDay(y, m, d) {
  var days = ['Sunday','Monday','Tuesday',
     'Wednesday','Thursday','Friday','Saturday'];
 var d = new Date(y, --m, d);
 return d && days[d.getDay()];
}

// What day was 23 May, 1905?
console.log(getDay(1905,5,23)); // Tuesday

编辑

请注意,这些类型的函数会将两位数字年份转换为20世纪的日期,例如

var d = new Date(5, 4, 23) // 23 May, 1905

并且他们不检查值是否是有效日期:

var d = new Date(5, 16, 23) // 23 May, 1906

如果您不希望这样做,则必须以其他方式构造日期并检查值:

// Create a generic date object
var d = new Date();

// Set the values for 23 May, 0005
// This way doesn't convert 5 to 1905
d.setFullYear(5, 4, 23);

// Check at least 2 values in the date are the same as the input
// The easiest to check are year and date
if (d.getFullYear() == 5 && d.getDate() == 23) {  
  console.log(d + 'is a valid date!');
}

您可以根据上述内容创建一个单独的函数来创建日期,如果这些值无效(并且使用两位数的年份),则该日期将返回日期对象或NaN。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM