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

Date: 2021dec30 Update: 2026oct5 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 + 1; // Add one since yday is zero-based }
The week of the year is not in there but you can use strftime():
#include <time.h> #include <stdlib.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. }
Full Example Use:
#include <stdlib.h> #include <stdio.h> #include <time.h> // (Place the two above functions here) int main() { printf("julianDate=%d\n", julianDate()); printf("weekOfYear=%d\n", weekOfYear()); putchar('\n'); printf("From date command...\n"); fflush(stdout); system("date '+julian=%j week=%U'"); }
Output:
julianDate=278 weekOfYear=40 From date command... julian=278 week=40
Modern C++ has std::chrono https://www.davekb.com/search.php?target=chrono