як визначити, чи є вихідними дата у javascript [закрито]


81

якщо у мене є дата, яка входить у функцію, як я можу визначити, чи це вихідний день?


Зверніть увагу, що в деяких країнах вихідними є п’ятниця та субота (про що я вже згадував у відповідях), тому у відповіді слід враховувати вихідні за країною en.wikipedia.org/wiki/Workweek_and_weekend
Гай

Відповіді:


164
var day = yourDateObject.getDay();
var isWeekend = (day === 6) || (day === 0);    // 6 = Saturday, 0 = Sunday

9
d! = day:) Я б волів це назвати dayOfWeek, це мало б більше сенсу для ОП.
BalusC

4
Це не справедливо для всіх часових поясів. Наприклад, у Франції першим днем ​​тижня буде понеділок, а не неділя. Сучасні бібліотеки, такі як Moment, це компенсують.
csvan

7
@csvan: getDayзавжди повинен повертати 0 для неділі та 6 для суботи тощо, відповідно до поточних налаштувань часового поясу. (І тоді ОП повинен вирішити, що таке "вихідні" відповідно до їхніх вимог.)
Лука

1
Для js, мабуть, краще, якщо ви це зробите ===замість ==порівняння абсолютних значень. Не важливо, а просто найкраща практика.
dylanh724

1
Див. Ecma-international.org/ecma-262/6.0/#sec-week-day . 0 завжди дорівнює неділі
TreeAndLeaf

49
var isWeekend = yourDateObject.getDay()%6==0;

Це каже, що це справді, якщо це субота
Джанфранко П.

13
0% 6 (неділя) та 6% 6 (субота) обидва мають модуль 0
kennebec

8
окрім добровільного заплутування, я не бачу сенсу в цій техніці. Я особисто віддаю перевагу відповіді Лука. Це лише випадково, що в цьому випадку ми можемо використовувати модуль 6 замість 7 для вирішення нашої проблеми.
Анрі Лап'єр,

У деяких країнах вихідними є п’ятниця та субота
Гай,

@Guy, тоді питання в тому, чи .getDay()призведе інше значення, або визначення визначення isWeekendбуде неправильним. Якщо справа до змінної, мені все одно. Думаю, 0 завжди буде неділею, тому для мене це нормально.
C4d,


5

Я спробував правильну відповідь, і це спрацювало для певних мов, але не для всіх:

У документах momentjs Docs: будній день Повернене число залежить від локалі InitialWeekDay, тому понеділок = 0 | Неділя = 6

Тому я змінюю логіку, щоб перевірити фактичний DayString ('неділя')

const weekday = momentObject.format('dddd'); // Monday ... Sunday
const isWeekend = weekday === 'Sunday' || weekday === 'Saturday';

This way you are Locale independent.


Some countries have Friday and Saturday as weekend
Guy

@Guy You need to adapt the code to meet country needs. As per the wiki you link above some other countries have a single day weekend. Some countries have adopted a one-day weekend, i.e. either Sunday only (in seven countries), Friday only (in Djibouti, Iran, Palestine and Somalia), or Saturday only (in Nepal).
T04435

1

Update 2020

There are now multiple ways to achieve this.

1) Using the day method to get the days from 0-6:

const day = yourDateObject.day();
// or const day = yourDateObject.get('day');
const isWeekend = (day === 6 || day === 0);    // 6 = Saturday, 0 = Sunday

2) Using the isoWeekday method to get the days from 1-7:

const day = yourDateObject.isoWeekday();
// or const day = yourDateObject.get('isoWeekday');
const isWeekend = (day === 6 || day === 7);    // 6 = Saturday, 7 = Sunday

.isoWeekday() is a moment.js method, but not specified.
NVRM

0
var d = new Date();
var n = d.getDay();
 if( n == 6 )
console.log("Its weekend!!");
else
console.log("Its not weekend");

0

I've tested most of the answers here and there's always some issue with the Timezone, Locale, or when start of the week is either Sunday or Monday.

Below is one which I find is more secure, since it relies on the name of the weekday and on the en locale.

let startDate = start.clone(),
    endDate = end.clone();

let days = 0;
do {
    const weekday = startDate.locale('en').format('dddd'); // Monday ... Sunday
    if (weekday !== 'Sunday' && weekday !== 'Saturday') days++;
} while (startDate.add(1, 'days').diff(endDate) <= 0);

return days;

0

In the current version, you should use

    var day = yourDateObject.day();
    var isWeekend = (day === 6) || (day === 0);    // 6 = Saturday, 0 = Sunday

0

Use .getDay() method on the Date object to get the day.

Check if it is 6 (Saturday) or 0 (Sunday)

var givenDate = new Date('2020-07-11');
var day = givenDate.getDay();
var isWeekend = (day === 6) || (day === 0) ? 'It's weekend': 'It's working day';
    
console.log(isWeekend);

Welcome to SO. Please take more care when formatting your answers. Normal text shouldn't go in code blocks.
Calculuswhiz

-1

The following outputs a boolean whether a date object is during «opening» hours, excluding weekend days, and excluding nightly hours between 23H00 and 9H00, while taking into account the client time zone offset.

Of course this does not handle special cases like holidays, but not far to ;)

let t = new Date(Date.now()) // Example Date object
let zoneshift = t.getTimezoneOffset() / 60
let isopen = ([0,6].indexOf(t.getUTCDay()) === -1) && (23 + zoneshift  < t.getUTCHours() === t.getUTCHours() < 9 + zoneshift)

// Are we open?
console.log(isopen)
<b>We are open all days between 9am and 11pm.<br>
Closing the weekend.</b><br><hr>

Are we open now?

Alternatively, to get the day of the week as a locale Human string, we can use:

let t = new Date(Date.now()) // Example Date object

console.log(
  new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(t) ,
  new Intl.DateTimeFormat('fr-FR', { weekday: 'long'}).format(t) ,
  new Intl.DateTimeFormat('ru-RU', { weekday: 'long'}).format(t)
)

Beware new Intl.DateTimeFormat is slow inside loops, a simple associative array runs way faster:

console.log(
  ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][new Date(Date.now()).getDay()]
)


Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.