I'd go with expl3
all along.
\documentclass{article}\ExplSyntaxOn\NewDocumentCommand{\primarySection}{O{primary}mmmmm} { \__sky_year_extract:n { #5 } \int_compare:nTF { \c_sys_year_int - 5 > \l__sky_year_recent_int } % replace the two following branches { not~recent~year~(\int_use:N \l__sky_year_recent_int) } { recent~year~(\int_use:N \l__sky_year_recent_int) } }\int_new:N \l__sky_year_recent_int\seq_new:N \l__sky_year_all_seq\cs_new_protected:Nn \__sky_year_extract:n { \regex_extract_all:nnN { [0-9]{4} } { #1 } \l__sky_year_all_seq \seq_sort:Nn \l__sky_year_all_seq { \int_compare:nNnTF { ##1 } > { ##2 } { \sort_return_same: } { \sort_return_swapped: } } \int_set:Nn \l__sky_year_recent_int { \seq_item:Nn \l__sky_year_all_seq { 1 } } }\ExplSyntaxOff\begin{document}\primarySection {Data 1} {Data 2} {Data 3} {Jan. 1930 - June 2023} % Dates {Data 4}\primarySection {Data 1} {Data 2} {Data 3} {Jan. 1930 - June 2001} % Dates {Data 4}\end{document}
Since I can't make a sense out of your \secondarySection
macro (you end up with exactly the same tokens in both cases), I replaced it with code that shows what branch is taken.