0

So I'm trying to get the amount of days a blog post was posted ago. The end result would be something like "posted X days ago."

After spending some time on the problem, I figured it out by getting the NSTimeInterval, dividing to get days and then rounding. Although I got the output I wanted, I feel I am doing it wrong or there is a much more straight forward way of doing it.

tempDate is a NSDate object of when the blog was posted.

NSTimeInterval timeSince = [tempDate timeIntervalSinceNow];
timeSince = timeSince/60/60/24*-1; // seconds to days
int daysSince = lroundf(timeSince);
apolo
  • 441
  • 4
  • 18
  • What is it that makes you feel like you are doing it wrong? From a design perspective, this is very important to know. – abiessu Apr 26 '14 at 22:10
  • 1
    You could rearrange it as `int daysSince = lroundf([tempDate timeIntervalSinceNow] / -86400);` but it's basically the same thing. I don't think you could get it much simpler than this. – Crowman Apr 26 '14 at 22:11
  • Shouldn't I be using NSDate or something? (I'm a beginner, maybe it's just that..) – apolo Apr 26 '14 at 22:11
  • Never do date calculations that assumes 86400 seconds per day. It's wrong when dealing with daylight savings and other similar issues. – rmaddy Apr 26 '14 at 22:12
  • @espitia: Presumably `tempDate` is an `NSDate`? – Crowman Apr 26 '14 at 22:15
  • @PaulGriffiths tried that but nope, gave me errors. I think [rmaddys](http://stackoverflow.com/questions/4937230/relative-string-from-nsdate) gives a good answer. – apolo Apr 26 '14 at 22:17
  • @rmaddy: Which isn't a problem if you're dealing with UTC times, for instance, or if by "days" you just want "24 hour blocks". If a blog post was made 30 minutes ago, and it's now 12:01 local time, for instance, would you really want it showing "One day ago" for some parts of the world, and "One hour ago" for others? There are certainly cases where you'd want to do this, and it'd be fine. – Crowman Apr 26 '14 at 22:17

1 Answers1

0

you could use NSCalendar and NSDateComponent to get the number of days (and you don't even need to convert your tempDate)... See the good answer given here Number of days between two NSDates

Community
  • 1
  • 1
Esses77
  • 86
  • 2
  • 7