Function for calculating time between when comment was posted and now? (elapsed time)
Hello! I have a task in my current project where I need to calculate time between when comment was posted and now. So If comment was posted 2 days ago, it will say "2 days ago" etc.
Now, my question is, is there a built in function or whatever that shows elapsed time between in whatever format you want? So, seconds, minutes, hours, days, week, months years etc.
Or do I need to write that code myself? Since it looks like something basic that should be built in.
Cheers!
22 Replies
Not built-in directly, unless the new Temporal API has/will have that funcionality, but there are libraries that can handle this for you. Try out date-fns, for example.
For some reason I'm not fond of libraries right now since I'm still a beginner trying to understand basics and logic instead of just playing puzzle where I take finished products of something that seems to be just a few lines of code. Even though I do fully understand how powerful and useful libraries are, I just have a feeling that they are bad workaround for simple things a s beginner.
Thanks for suggestion either way! Good to know for future! (or even now if I give up on trying to do it myself) xD
you'll need to make liberal use of the modulo operator
%
if you're building your own 🙂I had something in mind like Math.floor since I do not need exact time
Just like YT comments, 2 years ago, eve thought it was maybe 2years and 6 months ago xD
Basically I save the date of posted comment, and just substract it from current date, then convert it to seconds and based on the number, I present it as "seconds, minutes, days, weeks, months, years ago"
Or maybe there is a way where it just substracts 2 days and gives me an option to choose seconds, minutes, days etc. Which is what I hoped to get here
xD
2 dates*
You can get the Unix epoch of a Date object very easily, and subtract those. You'll have to do the conversion to minutes and such yourself though
Yeah that is what my initial code is
I get seconds, then go on to determine whether it is minutes or something bigger
It just seemed like something that has an already built in option and I was doing it unnecessarily
But guess not. xD
Nope, doesn't exist
Roger! Thanks for all the advices!
That's the right attitude! And you know what I've never attempted to do this on my own so I might just give it a shot at it as well 😄
@joao6246 Oh thanks for encouragement! Yeah, It seemed not so hard to me, that I why I asked if there is a simple way, maybe you will be able to do it in few lines of code. xD
Not sure the number of lines is relevant to this since there are many ways to get it done. But either way I thought it was quite an interesting challenge indeed 🙂 Although, depending on how you'd like to output things this can get quite messy so I would still suggest using a library for this type of task. Especially to handle things like error handling, different date formats, timezone differences, etc.
In any case, here's my solution in case it helps. I'm curious to see yours as well, as I'm sure I made things more complicated than they need to (as usual 😅 ):
https://codepen.io/D10f/pen/MWqRPBB
I did something like this in C# in our basic codebase at work.
Basically there is a type Timespan that you get from using a subtract method on two DateTimes. It’s really clean in C# but I haven’t looked at this with JavaScript
Also for all those return statements I’m also rounding them to numbers with no decimal places in more verbose code but I typed this in my phone and you’re probably not using C# anyway but you get the coding pattern. I’m sure there are some nice JS shortcuts but off the top of my head you could convert all datetimes to UNIX time as numbers and get the number of seconds difference between the two then use math to determine the if statement breakpoints in numbers of seconds and math your rounded outputs diving by 24 and 60 and 60 etc… to drive the formatted return strings.
That's definitely a lot cleaner. There's a work in progress proposal for the Temporal API which is an improvement over the current Date object, that will make working with dates and times a lot easier. I don't know if calculating dates will be included but I hope it is.
Anyway, coming at it with a good night sleep immediately made me realize there's a terrible bug in my code above! Dates over 12 years in the past would wrap around back to zero so they would appear as some number of years between 0 and 12... I don't even know what was I thinking, but anyway I've updated the code to make it a little nicer this time around, following the same OOP approach. I left the faulty code commented out for reference.
@joao6246 Sorry for answering late, was super busy. (still kinda am xD)
Yeah, that is kinda the logic I followed, but yours look cleaner. Also I did not mention background of my project so maybe it would have been easier to understand my objective. xD
Basically my project was asking me to calculate time since for comments, that is it.
Frontend Mentor
Frontend Mentor | Interactive comments section coding challenge
This is project will put your JavaScript skills to the test. We provide a JSON file to pull the data, but it's also a perfect project to build as a full-stack CRUD app!
task: "- Bonus: Instead of using the
createdAt
strings from the data.json
file, try using timestamps and dynamically track the time since the comment or reply was posted."
So mine is MUCH MUCH more ugly, but If you are interested I will make a codepen
But it is kinda hard without the whole codeits super elaborate but you can catch the drift
xD
@rowe2ry Thanks for the writeup as well
Luckily I do not need to be super precise so I can just get close enough time xD
Most of the "ugliness" is handling the plural form of minute(s), etc., so I think it's pretty well done 😎
One quick tip though about this:
When using array methods like
forEach
, map
, etc, you don't need an external variable to keep track of the index. It's provided to you on the callback function:
Oh thanks for that! I was wondering where was the counter, but did not really bother searching for answer. xD
Or index*