簡體   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