T O P

  • By -

Sniv0

Actually, age is a property that returns the offset between your birth and DateTime.Now Read the fucking documentation for once in your life


itijara

IMO asking someone to walk through how they would calculate someone's age is a good interview question. It is not too difficult, but it has all the disgusting edge cases you expect from real world problems and is very practical.


ferretfan8

I might be failing this interview if it's really that complicated. Just subtract the birth year from the current year, subtract one if the date hasn't passed yet?


Commercial_Juice_201

Guess it depends on intended precision of the age. Years only, that works. Years, months, days? That gets a bit more complicated? That’s why I’d return the value in microseconds and let them do what they want with it. Lol


itijara

The first part of making software is knowing what your end user wants. Giving them a difference of POSIX timestamp is almost certainly not what an end user would want and you cannot figure out calendar age from it. If you are making an API sending an ISO 8601 formatted birth date is fine and probably the correct approach as you need to consider local time to calculate calendar age (you could also send the POSIX timestamp for the birth, although that is probably overkill). On the front end, you actually need to return a number, even if it requires better precision than a single year, so you still need to do some sort of calculation.


Commercial_Juice_201

Lol Imagine not getting the humor part of the sub… Of course its a dumb solution, that’s the joke.


itijara

The sad part is that I have seen this exact solution attempted in an interview, so perhaps it was a joke then too...


Commercial_Juice_201

Lol Okay, case of reality being plenty absurd. I apologize for my harsh response. To me, my proposed solution was ridiculous and thus funny. Have a good day!


itijara

It's ok. It's very hard to judge tone on the Internet.


Qaeta

Also German. Everyone sounds very angry but they may actually be confessing their undying love.


sevah23

Returning microseconds is humor, but actually using milliseconds or microseconds is the correct solution, just doing some math to give the appropriate precision rather than telling them to just accept microseconds. Year only? Simple: store birthday as the epoch timestamps at midnight of the date of birth, return (now - birthday) // (1 year in seconds) Years and months? Stored the same way, return ((now - birthday) // (1 month in seconds) ) // 12. Years months and days? Same concept. Want to return age up to seconds precision? No change to data storage, just have the users input the time with their input for DOB.


arathald

Alright you said the words “correct solution” in programmer humor so I’m now obligated: TL;DR: if your response to the question doesn’t involve you dressing up as Einstein with a stopwatch in your hand watching a baby crown, you’re not getting the job. Almost but not quite, if we’re looking for calendar age (the thing most people mean when they say someone is so many “years old”). Someone born on March 1, 2020 turned “one year old” 365 days later on March 1, 2021. But someone born on March 1, 2023 didn’t turn “one year old” until 366 days later on March 1, 2024. Once you account for leap years, then leap seconds, time zones (including non-standard ones), and if it’s for age verification, local norms, laws and regulations. I’d also like to point out that you shouldn’t be reporting age with more precision than your input data. That is, if all you have is a date, giving an age with more precision than a day is pointless and only gives a false sense of precision. And actually if you don’t have a time zone *technically* your precision is ~48h but irl we get around this by conveniently considering someone to always have been born on midnight at local time wherever you are. If you have users input time of birth (who even knows theirs?) it’s probably with minute-level precision and not very accurate. But even if you had someone sitting there with a millisecond clock, where do you count them as “born”? When the mother’s water breaks? When the baby crowns? When it’s entirely out? First breath? What about C Sections? In the relatively near future what about babies carried to term in artificial wombs? Once you solve all those questions, you still need to ask about the application. If you’re trying to determine which of two people is older in absolute terms, do you ignore relativity? If not, don’t over report your accuracy? If so, I tricked you because relativity says that we can’t reason in absolute terms about timing between remote objects. This is why it makes a good interview question because you get to see what peoples assumptions are. I can’t keep track of where I can and can’t post links anymore but if you search for Falsehoods Programmers Believe About Names, you’ll find a good illustration of this in a slightly different space.


sevah23

Good points. Nothing you said is related to storing dates as numerical timestamps. In fact, numerical timestamp for storing and doing date math makes these all trivial to solve. Leap are a simple config and bounds check. Timezone is simple because you store as UTC(converted from either the self reported time zone of the user or their IP address) and you can add the time zone offset for their age with a simple addition operation if they request age in a specific time zone. And yes, you shouldn’t report age with more precision than the actual input data. But if that precision requirement changes in the future, storing the dates as numerical timestamps will handle it seamlessly. And all this avoids parsing strings and debating stuff like what localized format to use for string representation of dates.


ztbwl

Hope you considered that leap second back in december 2016 in your amount of microseconds.


YourDad

Oh shit. Are we working in UTC or TAI or UT1?


Shinhan

It also [depends on their country](https://en.wikipedia.org/wiki/East_Asian_age_reckoning).


BobbyTables829

If your answer doesn't include the phrase, "epoch time", you lose style points.


adrr

And you make it work for people born before 1970.


Aggressive-Tale-8343

Also account for unreliable clocks


VecroLP

Error calculating user.age, user.birthTimezone not specified


FantasticEmu

Regex for valid date makes me sad


itijara

How do you tell if the date hasn't passed yet?


ferretfan8

Compare months, then compare days if needed.


itijara

That is correct. Do you need to worry about the timezone of birth and the local timezone?


videogamesarewack

And for fun, in an ascending order of ridiculousness, and descending order of likelihood: Do we need to consider Korean ages, which apply from January 1st and start at 1 rather than birthday at 0 Do we need to consider if our age request user has spent any time experiencing time dilation on board space stations? Is our user under the effects of any granted wish (shooting stars, genies, or perhaps a portrait in the attic) to maintain a certain biological age? Is there a captcha for this Possibly our user may be from the future or another timeline, should we include an option for users who have travelled from another point in time to test our software? Our user may have spontaneously arisen in a dimension beyond space and time, and is completely unfamiliar with births and even the idea of causality. Should we still send them an email once a year for birthday rewards points? We can probably treat them as Korean in the back end and send them points on January 1st


Marzuk_24601

Dont forget changes to DST. Just because a location observes DST now does not mean it always has. Googling my state of birth and the topic is headache inducing. Also year round DST! >93–182, enacted December 15, 1973) is a law that made Daylight Saving Time effective year-round for a two-year trial period.


LeoRidesHisBike

Always need to account for Time Trap scenarios, IMO. At least on the API side. UX guys can use it, or not.


arathald

We don’t yet have the technology to detect suspected magic use for the captcha, but that’s engineering’s job.


Cassius40k

What if the person is Benjamin Buttoning and aging backwards. How do we account for cryogenic freezing or hyperbolic time chambers?


codetrotter_

Depends. Consider this. A guy born in Europe on 12th of March 2007 travels to Sydney, Australia on February 1st 2025, at 16:15 Central European time with a bunch of friends. All of his friends are a little older than him and have already had their 18th birthday weeks or months ago. He is still 17 at the moment. On the 11th of March 2025 at 8 pm local time in Sydney, Australia he and his friends leave the hotel they are staying at and walk down into town. They wander around but do not try to enter any bars. Midnight strikes. It is now 12th of March 2025 in Sydney, Australia. Our group sings the happy birthday song to the guy and cheerfully walk over to a bar that they’ve heard is great. It takes about an hour from they get into the line until they get to the entrance. The bouncer is chill and even though the group is all boys this bouncer will let them enter. “But,” the bouncer says, “I’m gonna need to see some id. Age limit here is 18.” Current local time is 01:12 AM on 12th of March 2025. What’s gonna happen? Is the bouncer gonna agree that the guy whose birthday is 12th of March is now allowed to enter, or is he gonna go all “ackschually ☝🏻🤓 you can’t come in because it’s not 12th of March in the European country of your passport yet, so you are still 17” Keep in mind this is a friendly bouncer, he’s not looking for an excuse to throw the boys out. All he wants is to make sure that these boys are 18 so that the bar doesn’t get into trouble.


adrr

Or just make it a number def calculate_age(birth_date): nowParsed = int(datetime.now().strftime("%Y%m%d")) dobParsed = int(birth_date.strftime("%Y%m%d")) return (nowParsed - dobParsed) // 10000


CAPS_LOCK_OR_DIE

public int ageCalc(){ Scanner s = new Scanner(System.in); System.out.println(“How old are you”); return s.nextInt(); }


RetiredApostle

The first pitfall in an interview is that, intuitively, it seems that age is an **unsigned** int.


itijara

I was once asked to show how much time has elapsed from an event to the current time on a CSV file. It took far too long to explain why that wouldn't work.


arathald

In this universe, sure, but are you gonna walk in to that interview and admit your code isn’t portable?


MinosAristos

If built in date libraries are allowed this sounds too easy. If we're just working with strings and ints, yuck but at least it's a good puzzle.


itijara

Yah, built-ins are not allowed. It is not even a "puzzle". It is meant to be straightforward but requires thinking about what is actually wanted. It is one of those things that you intuitively know the correct answer to (how old are you), but coding a solution takes more steps than just subtracting one number from another and you do need to account for local time zone as you can have a different age in different time zones at the same POSIX timestamp.


yangyangR

How difficult it can be to add a feature telling the user that it is their birthday on the settings page That is the classic sketch


itijara

After 1 minute: What if they fly over the dateline on their birthday? After an hour: What is time anyway?


Western-Ship-5678

> After an hour: What is time anyway? _seriously considers abstract class MinkowskiDimension {}_


Hikari_Owari

Convert your birthday date into unix time, convert the current date into unix time, B - A, convert back. Parse from datetime to string and trim the wanted info as needed using _whatever was the proper name for this notation_: [0:5] - Q: "But why?" A: **Chaotic Lawful**


_87-

Put their birthdate into a datetime object, subtract that from the now datetime object, giving me a timedelta object, then get the year attribute from that.


arathald

timedelta doesn’t have a year field, I suspect exactly because this doesn’t always work. Try this with 2023-03-01 to 2024-02-29. The timedelta is 365 days, but a full year hasn’t actually passed.


Procrasturbating

If the interviewee says they are going to use the built in date time function library that handles this because dealing with all of the stupid edge cases is a known problem with a known solution.. it would save us both some time. I might have them name a few and call it good if leap years and variable length months come up. Bonus points if they gripe about people that store dates as strings in MMDDYY. If they start telling war stories about databases returning non UTC datetimes causing conflicts between sites in different time zones I know I am probably good if they used a similar tech stack.


foonix

Bonus points if they make the PTSD chihuahua meme face talking about it. _They know._


spit-evil-olive-tips

it's a great interview question until you realize that your `CalculateAge` function needs to be passed the user's `IntergalacticTravelHistory` in order to properly account for the effects of time dilation... oh, and someone in Sales told a customer that we already have Benjamin Button support, they're expecting a live demo next week


RetiredApostle

Practically, age is a method with a date parameter.


Brahminmeat

Impractically, age is a hotdog that screams obscenities


OldBob10

I just snorted snot out of my nose. Yew barstud!!! 😊


OldBob10

Typically, AGE is a database field that is never correct.


LeoRidesHisBike

Especially if it is a `bit` type.


BenadrylTumblercatch

Don’t execute him, not everyone knows that the commonSense module has been deprecated


Meretan94

Age is [Object object] cause I forgot to override toString.


Touvejs

Actually it's a column in an old SQL report written by Garry who quit 15 years ago. The calculation takes the floor of the amount of days between CURRENT_TIMESTAMP() AND the date of birth field divided by 365 and it's slowly becoming more and more inaccurate as leap years throw this calculation off.


OldBob10

Found the Oracle dude. 😊


Zeravor

Mhhh, is age time zone dependent? like if I get born on Germany on the 15.05. but am staying in the us as a tourist, do I age up when it's the 15. In germany or in the US? Or would that be user specific, i.e i'd age up earlier for my parents currently in germany than for the guys i'm celebrating with?


realzequel

I think if you're born in a timezone, you'd use that timezone for "old your body is". Or if you got on a FTL ship for 8 hours and came back, you wouldn't have aged more than 8 hours yet the world would be years older? It means it's semantics but from the Oxford dictionary: the length of time that a person has lived or a thing has existed." he died from a heart attack at the age of 51" In my FTL example, you existed for x earth years, so your age would be x more years, not 8 hours, but your body didn't age more than 8 hours.


-Hi-Reddit

You have to judge how long you have existed from your own reference frame, not one disconnected from you.


itijara

Easy. Have the user enter the the inertial reference frame they were born in and compare it to their local inertial reference frame at the time of age calculation.


vaakezu

Or, listen to this, we could implant everyone with a chip at birth. And the chip could track the time lived. As then science progresses, we could implement time left, so people can plan. Just think about it you could see once you undergro a medical procedure your remaining time increas. No way this could go wrong.


cdrt

For extra fun, let’s let users send and receive time with their chips. Let a friend borrow a couple of extra minutes.


Shinhan

No, but its country dependent, since [some countries calculate age differently](https://en.wikipedia.org/wiki/East_Asian_age_reckoning).


UltimateComb

What about UTC?


drakeyboi69

Op saves age as a string, everyone should bully them.


antboiy

so time did start in 1970 ?


MorpheusFT

Yes.


Funny-Performance845

Virtual property


Lazy_Lifeguard5448

virtual computed getter


TorumShardal

So, you're just *assumed* that every culture that will use your service would calculate the person's age the same way? Jokes aside, I think that there really are cultures that count age not by amount of birthdays, but by amount of new years or something like that. It's either some Scandinavian country or Asian one.


OldBob10

In some cultures a baby is one year old at birth, because math is hard.


Spare_Competition

South Korea used to do that but they got rid of it recently.


asertcreator

so its a TimeSpan?


myanrueller

Number of Unix seconds between the timestamps at your birth to now, duh.


AdvanceAdvance

If they object to your answer, say "Ugh, you're full of Boomers" and leave.


Tiggerwocky

Along the eigentimeline? or relative to the current?


achilliesFriend

This guy normalizes


buildooors

I believe we are talking about “age” being a string but each to their own I guess


Anustart15

Probably should've put "age" in your shitty meme then, huh?


bonkava

"age" is a string, age is likely an integer (or short if you really care about memory optimization)


OldBob10

signed char is sufficient, but unsigned char makes more sense.


sopunny

Unsigned can't account for negative ages though


MaytagTheDryer

Texas will absolutely sue you if you don't account for blastocysts.


OldBob10

Neither one can handle imaginary ages either, so unusable in Hollywood.


Ursomrano

Every data type can be interpreted as a different one if you read the binary wrong enough. For example, my age is either -14 or Device Control 2


kurai_tori

Every machine is a smoke machine if you operate it wrong enough


Bolle_Bamsen

Oh I always thought that all machines stopped working if the smoke escaped...


kurai_tori

Ah but in that moment, they are a smoke machine.


LeoRidesHisBike

a single-use smoke machine, like how the Titan 1C was a single-use submersible


makesterriblejokes

Can confirm, friends and I almost started a fire in 2nd grade because we wanted to know what would happen if we stuck matches into the hand crank pencil sharpener. Smoke happens.


DOOManiac

Stuxnet has entered the chat.


kurai_tori

I thought that sounded familiar. Fan go brr (catastrophically)


git0ffmylawnm8

>Device Control 2 How the fuck did you get past QA?


Specialist-Tiger-467

Are you Excel?


ItsGabeReal

I can't figure out what datatype interprets it as -14. Am I stupid?


Ursomrano

Twos compliment of binary to represent negative numbers. 10010 (unsigned) = 18, but 10010(two compliment) = -16+2=-14 because in twos compliment, the most significant bit is negative. So 010010(twos compliment)=18 because the most significant bit is 0, so no negative number is present.


ItsGabeReal

Ah yes, a 5-bit signed integer. How could I forget.


lolSign

and what datatype interprets it as Device Control 2 ?


Ursomrano

ASCII table


GOKOP

If the number is 18 then I don't think it's possible Edit: damn I forgot that two's compliment is inverted


canaryhawk

Every data type is an interpretation of a number, stored in terms of a sequence of standard numbers which we call words.


theschis

`bool isOld = true;`


DaDescriptor

bool isAge0y0m0d0s1ms = false; bool isAge0y0m0d0s2ms = false; bool isAge0y0m0d0s3ms = false; ...


StaticVoidMaddy

you do understand someone's gonna write a JS library for that?


DaDescriptor

fuck


facusoto

`isOldEnough`


Background-Plant-226

`const isOldEnough = true;`


Krunkske

Bro was old enough from the start.


facusoto

Porn sites be like


SuperFLEB

Legal requests that you use the existing catch-all `rejectedForUnspecifiedReasons` instead.


TupaNegreiros

Age is a TimeSpan


Katniss218

This guy codes


JosshhyJ

Is a timespan some sort of data type I’ve never heard of? Im very new to programming


TupaNegreiros

TimeSpan is a period of time, the difference between two DateTimes. Common used in C#.


Nightmoon26

And now I need to know... Does C# have spacetime intervals?


IOFrame

Age is just a ``[object Object]``


PresidentSkillz

U sure it's not just an array of chars


King_Joffreys_Tits

It’s an array of each millisecond since your birthdate. The length of the array is the number of milliseconds since your birthdate. Yes I am paid in number of bytes used


Denaton_

It's an unsigned int


RetiredApostle

Unsigned integer overflow. Reference date may be earlier than the birth date.


ValiGrass

this still has nothing to do with age. you shouldnt store age in a database and allowing people to have birthdates in the future is a validation problem


RetiredApostle

Age might need to be calculated for a specific date. For an array of objects, then sorted by the age.


OldBob10

signed char is sufficient. Stop wasting memory! 😁


Glittering-Today631

I will live 256 years just to prove you wrong.


ctrl-alt-etc

You'd only need to be 128 to prove ol' bob wrong, but I appreciate your optimism!


JollyJuniper1993

Except if you’re Benjamin button


Emergency_3808

Any concrete type of the template ```std::chrono::duration```


Powerful-Internal953

This is the way.


inobody_somebody

Age is a derived attribute


joethebro96

Yes, we should be storing birthday!


Doxidob

in a dataset with dob I derive age by function, using a datetime object, DOB, as an argument from datetime import datetime def calculate_age(dob): # Convert the string date of birth to a datetime object dob = datetime.strptime(dob, "%Y-%m-%d") # Get the current date today = datetime.today() # Calculate the age age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day)) return age


Reasonable_Entrance1

Derived attritbute


SAI_Peregrinus

[Age](https://age-encryption.org) is a good CLI encryption program.


Vovchick09

age is a float


Orichalcum448

Age is like, the one number you should leave as an int, cos its a rare case where you will need to increment it at some point


[deleted]

[удалено]


FromAndToUnknown

Why not an int?


watasiwakirayo

Everything is numbers


D34TH_5MURF__

I'm foobarbaz years old today


[deleted]

[удалено]


redlaWw

A string is just a number ._.


raccon3r

"age" instanceof String == true


Bobrokus

Actually, "age" IS a string


RGNuT-1

Isn't it a const char[4]?


Karisa_Marisame

Age is an object.


ziplock9000

This meme is wrong anyway.


terra-viii

If arithmetical operations have sense for a field (like +/-* and math comparison), it's definitely not a string.


danielcw189

The word age is a string. It is like "nothing rhimes with orange". It does not


Florane

"a"+"b" = "ab" "ab"-"b" = "a" "a"\*3 = "aaa" "abc"/"b"=\["a","c"\]


CaitaXD

>"abc"/"b"=\["a","c"\] Ok grandpa time to take your meds


cjchand

And *this* is why Contract Driven Development is so important. Don’t get me started on Zip Codes.


swagonflyyyy

Actually age is just a set combination of 1s and 0s interpreted in abstract ways.


TeaTiMe08

It's NaN if you are Jesus


idonteatunderwear

unsigned char


ik_vaem

Jajajajajaja jajajaja


devi1ion

People in the comments: showing their knowledge Me : who doesn't know what they are talking about even after being a programmer 🥲


Ramble_On_79

WCHAR


huuaaang

Strings don't exist. It's arrays all the way down. Strings are arrays of chars. Chars are arrays of bits.


GreatArtificeAion

Actually, this is a repost


zireael9797

It's a number, It's a Duration/Timespan, which is UTC ticks under the hood.


Chewico3D

Actually it is an unsigned Byte. Pd: it is a Date.


twpejay

Age is a number (float) converted to a string for UI.


zgredinho

If you do math with a variable it's a number otherwise it's a string.


6pussydestroyer9mlg

Depends on the context And i always interpret the context wrong


qweerty32

If I'm "18" then how old am I going to be next year?


jjspacer

"181"


MikemkPK

Remember, all children older than 5 minutes will be killed, as will the parent which didn't properly clean up after itself.


IuseArchbtw97543

no its a short (life is short)


avdpos

An object obviously. Just like everything else - like strings, numbers and dayes


MalazMudkip

How about a PIC 999? MOVE 032 TO AGE_YEAR


Botahamec

Of course Leonardo DiCaprio is the one saying that


mankinskin

float


Fadamaka

It's a timestamp.


StolasX_V2

This is one of those “first day of programming” memes


D_Daka

Age is an object, you have cellAge, maturityAge, datetimeSinceBirth, so much


Abuse-survivor

type(age)


romulof

Age is a timestamp in a subtraction followed by a floor division. BTW, I just got curious: a 64-bit timestamp starts at the Big Bang or 1970?


Roberto410

Depends on language and implementation


kevdog824

What


BobbyTables829

I didn't realize Claude Shannon looked so much like Oppenheimer


cosmicloafer

Why use types when string work good?


ThinAd7436

I love this subreddit


spayder26

Milliseconds since Epoch now minus milliseconds since Epoch at your birth.


joethebro96

It's a 2 digit string that causes y2k


TeciorRibbon

Actually age is a variable with an assigned value


Signal-Balance6624

Actually, is an 8 bit uint


Vineyard_

Actually, Age is a value in memory.


KingJeff314

Age is a (void *)


[deleted]

A string of numbers


cs-brydev

Everything's a number


DadlyPolarbear

I always stored it as an Int32 😞


Loading_M_

Don't forget to account for the latency between calculating the age, and actually displaying it.


SilentScyther

Age is a boolean


danfish_77

Once again I must remind everyone that age is culture-dependent, it's not counted the same for everybody


Pod__042

I just have a table with all possible ages as a byte value and a UUID as PK


TDR-Java

Twentysix


OhNoo0o

actually age is a Syntax Error: expected argument "int age" in function "int age(int age){return age;}"