Programming Tips - C/C++: Get the Julian date | Get the week of the year

Date: 2021dec30 Date: 2026jun4 Language: C/C++ Q. C/C++: Get the Julian date | Get the week of the year A. The Julian date (Nth day of the year) is in the `tm struct':
#include <time.h> int JulianDate() { // The Nth day of the year const time_t now = time(NULL); struct tm here; localtime_r(&now, &here); return here.tm_yday; }
The week of the year is not in there but you can use strftime():
#include <time.h> int WeekOfYear() { const time_t now = time(NULL); struct tm here; char buf[100]; localtime_r(&now, &here); strftime(buf, sizeof(buf), "%U", &here); // Or you may prefer %V - see `man strftime` return atoi(buf); // Obviously getting it into a string and then turning the string // into an integer isn't so pretty but it works. }
Example Use:
#include <stdio.h> void exampleUse() { printf("julianDate=%d\n", julianDate()); printf("weekOfYear=%d\n", weekOfYear()); }
Modern C++ has std::chrono https://www.davekb.com/search.php?target=chrono