Is there a way to find out day of the week given date in just one line of C code?
For example
Given 19-05-2011(dd-mm-yyyy) gives me Thursday
s = s + (date + year + (year / 4) - 2) ; and then s = s % 7. After the above process, s will contain an index to the week array which can be accessed as - week[s] and this value shows the day on the given date. Note: “%s” in printf() is used to print the string value of week[s].
Step1 :Take the first two digit of the given year. Step2 :Calculate the next highest multiple of 4 for the first two digit number. Step3 :Subtract 1 from the number. Step4 :Then, subtract the first two digit from the number.
The Excel DAY function returns the day of the month as a number between 1 to 31 from a given date. You can use the DAY function to extract a day number from a date into a cell.
As reported also by Wikipedia, in 1990 Michael Keith and Tom Craver published an expression to minimise the number of keystrokes needed to enter a self-contained function for converting a Gregorian date into a numerical day of the week.
The expression does preserve neither y
nor d
, and returns a zero-based index representing the day, starting with Sunday, i.e. if the day is Monday the expression returns 1
.
A code example which uses the expression follows:
int d = 15 ; //Day 1-31
int m = 5 ; //Month 1-12`
int y = 2013 ; //Year 2013`
int weekday = (d += m < 3 ? y-- : y - 2, 23*m/9 + d + 4 + y/4- y/100 + y/400)%7;
The expression uses the comma operator, as discussed in this answer.
Enjoy! ;-)
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:
EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With