# What year will it be in n seconds?

You are given an integer n as input, and, regardless of the current date, must return the calendar year (Gregorian calendar, other calendars not allowed) taking place n seconds from now.

## Rules

• You may not assume that the current year is 2021. In other words, imagine a user testing your solution in five years.
• Standard loopholes forbidden.
• Shortest answer in bytes wins.
• Built-in date functions are allowed.
• You must also support negative numbers.
• On the topic of the year zero: Your answer must follow the ISO specifications, meaning there is a year zero.
• You may assume that the input is always an integer within bounds of your language number system.
• If your language's date functions take leap seconds into account, then follow your language, otherwise do not take leap seconds into account.

## Examples (in this case, measured at the time of writing, which is February 15, 2021)

100000000000 -> 5190
1000 -> 2021
54398643 -> 2022
54398643234 -> 3744
-100000000000 -> -1148

• Is it "local date at 00:00:00" + n seconds or "local date at local time" + n seconds? – Arnauld Feb 15 at 13:46
• In my case, putting new Date() gives the date at my local time, but that might not be true in other languages. It depends on the language – Recursive Co. Feb 15 at 13:47
• Was the negative-number requirement to avoid solutions like sleep $n;date being a valid bash answer? I notice there's no performance requirement :P – Peter Cordes Feb 16 at 2:14 • It's generally accepted that CodeGolf answers that provably work for large test cases are fine, even if nobody has time to wait for them to finish, so for example O(e^n) or n! time and/or space complexity is fine for a problem that would normally take much shorter, like log(n) time. But when the "run-time" couldn't be sped up with a faster computer, so it can never produce an answer before the specified time, yeah that's stretching it in my opinion, too. And a different sort of reason for being slow than the usual excuse. – Peter Cordes Feb 16 at 8:25 • @LuisMendo Edited the question albeit a bit late – Recursive Co. Feb 17 at 15:33 ## 35 Answers # Ohm v2, 5 bytes υ!+υy  Try it online! Explanation: υ!+υy υ! get the current timestamp in seconds + sum with the implicit input υy get the year from the resulting timestamp  • υ is a two byte unicode charicter, so this is 7 bytes. "echo 'υ!+υy' | wc -c" returns 8 including the newline character. – timthelion Feb 16 at 17:07 • @timthelion Ohm use a custom code-page as many other languages do, you can read more about it here codegolf.meta.stackexchange.com/a/10187/72733 – Cinaski Feb 16 at 17:29 • Wow, haven't seen this language used in a long time! This kind of challenge is exactly what I added the time builtins for, very nice solution! – Nick Clifford Feb 17 at 15:39 # Bash, 16 bytes date -d$1sec +%Y


Try it online!

### Credits

• Saved 12 bytes thanks to @manatwork
• Why not date -d$1sec +%Y? Try it online! – manatwork Feb 15 at 15:55 • Sorry, disregard my comment, forgot it's n seconds and not 1 second. – nyuszika7h Feb 17 at 14:41 # PHP, 27 bytes <?=date(Y,time()+$argv[1]);


Try it online!

• Oh my, of course! (deletes his own answer in shame) – Kaddath Feb 15 at 14:36
• 25 bytes as a function – 640KB Feb 15 at 17:23
• @640KB Nice! It's been a while since I did PHP. Back when I stopped, the Arrow Function RFC was still open. Glad to see it being part of the language now. – oktupol Feb 15 at 18:37
• @oktupol yeah but they have strange limitations, such as you cannot do loops in them, or use recursion (without lengthy tricks) – Kaddath Feb 16 at 8:25
• <?=date(Y,time()+$argn); for 24? What's the current consent for$argn? +2 for the flag? – Christoph Feb 16 at 9:05

# 05AB1E, 116 bytes

"т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}"Vžežfžg)IŽª+·÷ÄF©IdiY.V‹i®¬>0ë®1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝëć©ić©i<D_-12š31šë®<šDY.Všë®<š]θ


Here we go again..

Try it online or try it only with custom specified starting date. (Pretty slow for large inputs, so won't be able to output the larger test cases with the current date.)

Explanation:

Since 05AB1E doesn't have any date builtins (except for the current day/time), I've calculated things manually before. I've used the code of going to the next day from this answer of mine, which in turns also uses the leap year calculation of this answer of mine.
Since this challenge also asks to go back in time, I've modified the program accordingly to support that as well.

Step 1: Create a function to calculate the amount of days in a month for a given year/month:

"т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}"  # Push this string
V # Pop and store it in variable Y

                             # Pop the list and push all values separated to the stack
# (the year will be at the top; month below it)
т‰                           # Take the divmod-100 of the year
0K                         # Remove the 0s
θ                        # Pop and push its last item
4Ö                      # Check if it's divisible by 4
U                     # Pop and store this in variable X
# (X=1 for leap years; X=0 for non-leap years)
D                    # Duplicate the current month
2Qi                 # If it's equal to 2 (thus February):
\                #  Discard the duplicated month
28X+            #  Push 28 + isLeapYear from variable X
ë                 # Else:
<                #  Decrease the month by 1
7%              #  Modulo-7
É             #  Modulo-2
31α          #  Absolute difference with 31
}                 # Close the if-else statement


Step 2: Now we determine the current date, and loop an amount of times depending on the input:

že                             # Push the current day
žf                           # Push the current month
žg                         # Push the current year
)                        # Wrap all three into a list
I                       # Push the input-integer
Žª+                    # Push compressed integer 42300
·                   # Double it to 84600 (60*60*24)
÷                  # Integer-divide the input by 84600
Ä                 # Take its absolute value
F                # And loop that many times:


Step 3: If the input was positive, calculate the next date:

©                              #  Store the current date in variable ® (without popping)
Idi                           #  If the input is non-negative:
Y.V                        #   Execute string Y as 05AB1E code to get the amount
#   of days for the current month/year
‹i                      #   If this is smaller than the current days:
®                     #    Push the current date again
¬                    #    Get its first item (the days)
>                   #    Increase the day by 1
0                  #    Push index 0
ë                      #   Else:
®                     #    Push the current date again
1                    #    Push day=1
¾                   #    Push index 0
ǝ                  #    Insert days=1 at index 0 into the date
D                 #    Duplicate it
Ås               #    Pop and push its middle item (the month)
D              #    Duplicate that month
12‹i          #    If it's smaller than 12:
>         #     Increase the month by 1
1        #     Push index 1
ë          #    Else:
\         #     Discard the duplicated month
1        #     Push month=1
D       #     Push index 1
ǝ      #     Insert month=1 at index 1 into the date
¤     #     Push its last item (the year)
>    #     Increase the year by 1
2   #     Push index 2
}          #    Close the if-else statement
}                      #   Close the if-else statement
ǝ                     #   Insert the value at the given index into the date


Step 4: If the input was negative instead, calculate the previous date:

ë                              #  Else (the input is negative):
ć                             #   Extract head; push [month,year] and day separated
©                            #   Store the day in variable ® (without popping)
i                           #   If day == 1:
ć                          #    Extract head; push [year] and month separated
©                         #    Store the month in variable ® (without popping)
i                        #    If month == 1:
<                       #     Decrease the [year] by 1
D                      #     Duplicate it
_                     #     Check if it's equal to 0 (1 if 0; 0 otherwise)
-                    #     Subtract that (so we go from year 1 to -1)
12š31š              #     Prepend 12 and 31: [31,12,year-1-(year-1==0)]
ë                        #    Else:
®<š                     #     Prepend month-1 to the [year] list
D                    #     Duplicate it
Y.V                 #     Execute string Y as 05AB1E code to get the amount
#     of days for this month/year
š                #     Prepend this to the [month-1,year] list
ë                           #   Else:
®<š                        #    Prepend day-1 to the [month,year] list


Step 5: After the loop, extract the year to output:

]                              # Close both the if-else and loop
θ                             # Pop the date, and only leave its last item (the year)
# (after which it is output implicitly as result)


See this 05AB1E tips of mine (section How to compress large integers?) to understand why Žª+ is 42300.

• Oh my. Debugging this must have been fun :-) – Luis Mendo Feb 15 at 16:08
• @LuisMendo Haha, most of it has been done before in other challenges. But I indeed debugged going to the previous date, since that is new. :) – Kevin Cruijssen Feb 15 at 16:09
• Nice, extremely creative. This must have taken a while to write – Recursive Co. Feb 15 at 16:09
• @expressjs123 Probably longer than most of the answers indeed. 05AB1E is a code-golf language, so in most challenges one of the shortest. With date-related challenges on the other hand, it's usually one of the longest, since it has to do almost everything manually. But I kinda like doing those kind of challenges in 05AB1E regardless. ;) – Kevin Cruijssen Feb 15 at 16:16
• Looks like the tables have turned :P. +1 for doing something like this in a golfing language – user Feb 15 at 16:26

# Ruby, 21 bytes

->n{[*Time.now+n][5]}


Try it online!

Shorter by a byte than the more obvious ->n{(Time.now+n).year}.

• The shortest answer I can actually understand! (the APL one is shorter but it's harder to make something of it) – Recursive Co. Feb 15 at 14:46
• @expressjs123 I've added an explanation. Let me know if I need to expand on anything. – Adám Feb 15 at 16:23
• Nice. Never even thought about decomposing a Time object. – engineersmnky Feb 17 at 3:00

# Octave / MATLAB, 27 bytes

@(x)datestr(x/86400+now,10)


Try it online!

### How it works

@(x)                          % Define anonymous function with input x
x/86400           % Divide input by 86400, to convert to days
now       % Current time in days since "January 0, 0000"
datestr(           ,10)   % Convert to string with format 10, which is year

• Would the downvoter be so kind to explain how I can improve my answer (other than posting an explanation, which I haven't had the time for yet)? – Luis Mendo Feb 15 at 16:13
• Many answers here are getting downvoted without explanation :/ – Razetime Feb 15 at 16:22
• @Razetime I've seen that happen, sometimes, to answers in golfing languages. Some people don't like those languages and decide that's enough reason to downvote. But Octave? – Luis Mendo Feb 15 at 17:03
• not a downvote but it's easy to find a failing input since not all days are 86400 seconds long – Agos Feb 17 at 10:06
• @Agos Good point. I have asked the OP if leap seconds need to be taken into account. Doing it would complicate answers a lot – Luis Mendo Feb 17 at 11:00

# JavaScript (ES6), 42 bytes

n=>new Date(+new Date+n*1e3).getFullYear()


Try it online!

• Nice answer, but not accepting it yet (waiting a week to accept any answer) – Recursive Co. Feb 15 at 14:00
• @expressjs123 For code-golf challenges, we usually do not accept any answer. If you really want to accept one, you should indeed wait at least one week before doing so and pick the shortest one (which is not going to be this one). – Arnauld Feb 15 at 14:05

# jq, 20 15 characters

now+.|gmtime[0]


Sample run:

bash-5.0$jq 'now+.|gmtime[0]' <<< 100000000000 5190  Try it online! • Sorry, I totally misinterpreted the question and missed that it's n seconds instead of 1 second... – nyuszika7h Feb 17 at 15:12 # PowerShell, 3226 23 bytes date|% *dds* @args|% y*  Try it online! -3 bytes thanks to mazzy and ZaelinGoodman • Darnit, I didn't see that somebody already did Powershell before me! I came to almost the same solution, so here's a few bytes for you from mine! Try it online! – Zaelin Goodman Feb 15 at 19:55 • so that the array of args does not confuse anyone Try it online! :) – mazzy Feb 15 at 20:51 • @mazzy thanks!!! – wasif Feb 16 at 4:20 • @ZaelinGoodman thanks!!! – wasif Feb 16 at 4:20 # Python 3, 7472 65 bytes lambda x:(date.today()+timedelta(0,x)).year from datetime import*  Try it online! -7 bytes thanks to @Eric • According to the rules, you can get rid of the f=: Try it online! – movatica Feb 15 at 16:39 • @Movatica thanks!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! – wasif Feb 15 at 16:41 • You need to return a year, not print it. So it's allowed to move print() to the footer, for 7 fewer bytes. tio.run/##FcrBCoQgEADQe1/hcaYNibSlXehPukyoJGSKzCG/… – Eric Duminil Feb 15 at 22:24 • @EricDuminil thanks!!! – wasif Feb 16 at 4:22 # Japt, 12 10 bytes ÐKj +Ue3)i  Try it -2 bytes from AZTECCO. This transpiles to the following JS: new Date(K.j() + U * 1e3).i()  where K.j() is the current time converted to milliseconds, U is the input, and .i() gets the year from the date constructor. • e can be a number method for 10 – AZTECCO Feb 15 at 20:02 • As Ð is a two byte unicode character, this is actually 11 bytes. – timthelion Feb 16 at 17:10 • @timthelion Japt has a custom codepage, just like the 05AB1E answer and Ohm answers do. Click on the "bytes" link to see its encoding. – Razetime Feb 17 at 3:09 # R, 12 bytes Sys.time()+n  This returns a full date, the year is at the beginning of the string. This is according to the rules, which didn't say to print just the year; and this is not in the list of "standard loopholes" by the time of this answer. To print just a year, R would need 25 bytes: format(Sys.time()+n,"%Y")  • Even if you used the format solution, you still would have the shortest R answer. – Recursive Co. Feb 16 at 10:38 • Actually, I think the ISO specification only requires 4-digit years, so you can use substr(...,1,4) which is a byte shorter. – JDL Feb 17 at 15:17 • @JDL thanks for the idea! :-) But not sure we can rely that the year will be 4-digit after addition/subtraction? More general sub("-.*","",Sys.time()+n) would work but is one char longer. – Tomas Feb 17 at 18:48 • @Tomas I don't think that matters if you interpret the rules as meaning the output is undefined if it would give rise to a year > 9999. From the wikipedia page: "ISO 8601 prescribes, as a minimum, a four-digit year [YYYY] to avoid the year 2000 problem. It therefore represents years from 0000 to 9999" – JDL Feb 18 at 12:01 # IBM/Lotus Notes Formula Language, 34 32 Bytes @Year(@Adjust(@Now;0;0;0;0;0;i))  Takes input from a field named i. Unfortunately, Formula only supports 32 bit signed integers so it is restricted to a maximum input of +/- 2,147,483,647. There is no TIO for Formula so here are a couple of screenshots: # GNU coreutils (16 bytes) date +%Y -d$1sec


Saved 4 bytes, thanks to @ovs.

• You can remove the onds from seconds: Try it online! – ovs Feb 16 at 8:28
• @ovs ah, I tried s and secs but missed sec somehow, thanks – rexkogitans Feb 16 at 8:31
• Unfortunately, this is a dupe of 2x-1's answer (label for Bash) codegolf.stackexchange.com/a/219053/55953 – CSM Feb 16 at 10:40
• @CSM really oops. I only looked if someone posted for GNU coreutils, bash slipped my attention. – rexkogitans Feb 16 at 12:34
• @CSM Duplicate answers are allowed. – Dingus Feb 16 at 14:05

# MATL, 11 bytes

12L/Z'+10XO


Try it out at MATL Online

Explanation

        % Implicitly grab input as an integer (seconds)
12L     % Push the literal 86400 to the stack (seconds in a day)
/       % Divide the input (in seconds) by the seconds in a day to convert to days
Z'      % Get the current time in days as a float
+       % Add the current time and the seconds in the future together
10XQ    % Determine the year of this date
% Implicitly display the result

• not all days are 86400 seconds long! – Agos Feb 17 at 10:07
• Hey, @Suever, it's been long! :-D Regarding what Agos says, I have asked the OP if leap seconds need to be taken into account (which would be very difficult) – Luis Mendo Feb 17 at 11:03
• OP has confirmed it is not necessary – Luis Mendo Feb 17 at 13:17

# Julia, 38 bytes

using Dates
f(x)=Year(now()+Second(x))


Try it online!

# Raku, 28 bytes

{DateTime.new($_+time).year}  Try it online! # Python 3, 51 bytes lambda x:gmtime(time()+x).tm_year from time import*  Try it online! # AWK, 30 $1=strftime("%Y",$1+systime())  Try it online! • 5 bytes saved thanks to @manatwork. • As strftime() returns string and in AWK even 0 is truthy as long as it's string, you can reduce it to $1=strftime("%Y",$1+systime()), because will always produce output.. – manatwork Feb 16 at 0:14 • @manatwork thanks! that saves 5 bytes! – Digital Trauma Feb 16 at 0:57 # Java (JDK), 57 bytes n->java.time.LocalDateTime.now().plusSeconds(n).getYear()  Try it online! Beats the Date API (71 bytes): n->new java.util.Date(System.currentTimeMillis()+n*1000).getYear()+1900  Try it online! Note that this one returns the year in absolute form (no negative year). And I don't even speak about the Calendar API. # C# (.NET Core), 98 bytes public class E{public static void m(double x){Console.WriteLine(DateTime.Now.AddSeconds(x).Year);}  Try it online! Didn't count the using System; and calling function in Main(), if they needed to be added, please inform me! • Still a fine solution, but I kinda doubt whether C# is an appropriate golfing language. – Recursive Co. Feb 15 at 16:35 • @expressjs123 C# is a valid golfing language and has been used in many questions, still they are harder to golf – wasif Feb 15 at 16:36 • Can probably cut this down using the C# interactive window.. – Caius Jard Feb 15 at 22:25 • You can golf in any language. I don't normally consider getting the best overall score all that interesting (since many golfing languages can solve a problem in only a couple of bytes) but prefer seeing the best score possible in a language that people use for everyday programming. – Turksarama Feb 15 at 22:28 # Visual Basic .NET (VBC), 89 bytes public class E Shared sub m(x) Console.WriteLine(DateTime.Now.AddSeconds(x).Year) end Sub  Try it online! # VBScript, 52 bytes MsgBox Year(DateAdd("s",Wscript.Arguments(0),Now())  # C# (Visual C# Interactive Compiler), 34 bytes x=>DateTime.Now.AddSeconds(x).Year  Try it online! # AppleScript function, 46 to y(s) (current date+s/60*minutes)'s year end  ### Test driver: repeat with sec in {100000000000, 1000, 54398643, 54398643234, -100000000000} log y(sec) end repeat  Save the function and the test driver as text to nseconds.applescript, then run in the terminal: osascript nseconds.applescript  Or run in the AppleScript Editor app. # T-SQL, 42 bytes select year(dateadd(s,a,getdate()))from t;  Uses the standard input method for T-SQL of taking input from a table. You can create a suitable table like this: create table t (a int not null); insert into t values (1000000000), (1000), (54398643), (-1000000000);  Note that T-SQL is limited to 32-bit integers for the number of seconds. To avoid that and allow the resulting year to vary between 0 and 9999 costs 6 bytes: select year(dateadd(d,a/86400,getdate()))from t;  Don't forget to declare a as bigint if you do this. (Note that hours is represented by hh so it's no shorter, and minutes won't let you reach 9999.) # MySQL, 35 bytes select year(now()+interval [input] second) # APL (Dyalog Unicode), 20 bytes (SBCS) Full program, prompting for n from stdin. ⊃⊃20 ¯1⎕DT⎕+20⎕DT'J'  20⎕DT'J' get current local* (Juliett) DateTime as UNIX time (code 20; seconds from beginning of 1970) ⎕+ prompt for n and use that to increment the UNIX time. 20 ¯1 interpret as UNIX times (code 20) and convert to an array of time stamps (code -1) ⊃ extract the first (and only) time stamp ⊃ extract the first element (the year) Try APL! (first and last case scaled down by a factor of 10 to avoid hitting date-time limits, 1 January 0001 though 28 February 4000; turned into function for ease of use) * could also have 'Z' (Zulu) to use the current UTC time instead of local time. • I don't really understand APL, so I don't entirely know what the problem is, but when I paste your code into tryapl it gives me an error? – Recursive Co. Feb 15 at 14:17 • @expressjs123 tryAPL uses a safe version of APL which prevents people from running malicious code, so it'll give you an error for using ⎕. – Razetime Feb 15 at 14:43 • Lots of multibyte unicode characters here, "echo '⊃⊃20 ¯1⎕DT⎕+20⎕DT\'J\'' | wc -c" gives me 32 which after removing the newline makes 31 bytes. – timthelion Feb 16 at 17:16 • @timthelion Sorry about that. Fixed now. – Adám Feb 16 at 17:17 # Perl 5-p, 23 bytes $_=gmtime$^T+$_;s/.* //


Try it online!

# Mathematica, 43 bytes

IntegerPart@DatePlus[#/86400]["YearExact"]&


Try it online!

Thanks to @LegionMammal978 for hinting that DatePlus[#/86400][[1,1]]&` fails for negative years

• This fails on negative year numbers. – LegionMammal978 Feb 16 at 3:08
• @LegionMammal978 oh... you're absolutely right! thanks, guess i'll have to add a few more bytes :-/ – sanchez Feb 16 at 21:36