How to Get the Day of Week Given a Date

How do I get the day of week given a date?

Use weekday():

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4

From the documentation:

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

How to get which day of week is a specific date?

If you are using a datetime.date object you can use the weekday() function. Converting to a date object inside your module should be trivial if you are passing in the day, month and year.

https://docs.python.org/3.7/library/datetime.html#datetime.date.weekday

Numeric representation

Example function:

import datetime

def weekday_from_date(day, month, year):
return datetime.date(day=day, month=month, year=year).weekday()

Example usage:

>>> weekday_from_date(day=1, month=1, year=1995)
6

String representation

Combined with the calendar module and the day_name array you can also get it displayed as a string easily.

https://docs.python.org/3.7/library/calendar.html#calendar.day_name

Example function:

import datetime
import calendar

def weekday_from_date(day, month, year):
return calendar.day_name[
datetime.date(day=day, month=month, year=year).weekday()
]

Example usage:

>>> weekday_from_date(day=1, month=1, year=1995)
'Sunday'

Unit Tests

Using pytest writing a series of super fast unit tests should be straightforward to prove it's correctness. You can add to this suite as you please.

import pytest

@pytest.mark.parametrize(
['day', 'month', 'year', 'expected_weekday'],
[
(1, 1, 1995, 6),
(2, 1, 1995, 0),
(3, 1, 1995, 1),
(6, 6, 1999, 6)
]
)
def test_weekday_from_date(day, month, year, expected_weekday):
assert weekday_from_date(day, month, year) == expected_weekday

How to get first and last day of the current week in JavaScript

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6

var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"

This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.

Making it work with first and last days in different months is left as an exercise for the user

Get Date of days of a week given year, month and week number (relative to month) in Javascript / Typescript

If you want Monday as the first day of the week, and the first week of a month is the one with the first Thursday, then you can use a similar algorithm to the year week number function.

So get the start of the required week, then just loop 7 times to get each day. E.g.

/* Return first day of specified week of month of year
**
** @param {number|string} year - year for required week
** @param {number|string} month - month for required week
** Month is calendar month number, 1 = Jan, 2 = Feb, etc.
** @param {number|string} week - week of month
** First week of month is the one with the first Thursday
** @returns {Date} date for Monday at start of required week
*/
function getMonthWeek(year, month, week) {
// Set date to 4th of month
let d = new Date(year, month - 1, 4);
// Get day number, set Sunday to 7
let day = d.getDay() || 7;
// Set to prior Monday
d.setDate(d.getDate() - day + 1);
// Set to required week
d.setDate(d.getDate() + 7 * (week - 1));
return d;
}

// Return array of dates for specified week of month of year
function getWeekDates(year, month, week) {
let d = getMonthWeek(year, month, week);
for (var i=0, arr=[]; i<7; i++) {

// Array of date strings
arr.push(d.toDateString());

// For array of Date objects, replace above with
// arr.push(new Date(d));

// Increment date
d.setDate(d.getDate() + 1);
}
return arr;
}

// Week dates for week 1 of Jan 2020 - week starts in prior year
console.log(getWeekDates(2020, 1, 1));
// Week dates for week 5 of Jan 2020 - 5 week month
console.log(getWeekDates(2020, 1, 5));
// Week dates for week 1 of Oct 2020 - 1st is a Thursday
console.log(getWeekDates(2020, 10, 1));
// Week dates for week 1 of Nov 2020 - 1st is a Sunday
console.log(getWeekDates(2020, 11, 1));

C Program to find day of week given date

A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm argument can be queried for its tm_wday member on systems that modify those fields automatically (e.g. some glibc implementations).

int get_weekday(char * str) {
struct tm tm;
memset((void *) &tm, 0, sizeof(tm));
if (strptime(str, "%d-%m-%Y", &tm) != NULL) {
time_t t = mktime(&tm);
if (t >= 0) {
return localtime(&t)->tm_wday; // Sunday=0, Monday=1, etc.
}
}
return -1;
}

Or you could encode these rules to do some arithmetic in a really long single line:

  • 1 Jan 1900 was a Monday.
  • Thirty days has September, April, June and November; all the rest have thirty-one, saving February alone, which has twenty-eight, rain or shine, and on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z).

What's the best way in JavaScript to get the day of the week of a date string in any time zone?

Use

new Date('2022-01-29').getUTCDay()

new Date('2022-01-29') will create a Date object with the UTC (Greenwhich) date "2022-01-29" and time "00:00h". When getting a weekday with .getDay() your browser would calculate it for your local timezone. By using .getUTCDay() instead you get the weekday for the UTC timezone.

Interesting point made by @RayHatfield

console.log("UTC-time:", new Date("2022-01-29").getUTCHours()) // 0
console.log("UTC-time:", new Date("2022-01-29Z00:00:00").getUTCHours()) // 0 ("Z" is for "ZULU" -> UTC)
console.log("UTC-time:", new Date("2022-01-29T00:00:00Z").getUTCHours()) // 0 (ISO 8601 date string -> UTC)
console.log("UTC-time:", new Date("2022-01-29T00:00:00").getUTCHours()) // UTC time (h) for your local midnight


Related Topics



Leave a reply



Submit