0

I have to load some articles from different sources and give how much time elapsed from the article and now :

Hre is my method :

 TimeSpan diff = DateTime.Now - articleDate; 
                            if(diff.Seconds < 60)
                            {
                                article.date = diff.Seconds + "Sec";
                            }
                            else if (diff.Minutes < 60)
                            {
                                article.date = diff.Minutes + "Min";
                            }
                            else if (diff.Hours  < 24)
                            {
                                article.date = diff.Hours + "Hrs";
                            }
                            else 
                            {
                                article.date = diff.Days + "Days";                            
                            }

This method appears to be quite redundant , what is the best method to give the time that elapsed, and if it is seconds add "Sec" like I did after ?

user2505650
  • 1,293
  • 6
  • 20
  • 38
  • Does this help? http://stackoverflow.com/questions/574881/how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net?rq=1 – Patrick Hofman Aug 11 '14 at 15:06
  • 1
    [Or this ?](http://stackoverflow.com/questions/16689468/how-to-produce-human-readable-strings-to-represent-a-timespan) – Sriram Sakthivel Aug 11 '14 at 15:07
  • Or try [Humanizer](https://github.com/MehdiK/Humanizer) or using the search, FWIW. – CodeCaster Aug 11 '14 at 15:09
  • i read the answers but i don't understand how to apply this to my specific example can you please provide a quick code to show me how should I proceed? – user2505650 Aug 11 '14 at 15:14
  • I'd split it in two functions. One takes a TimeSpan as input and produces a string. The other takes the current time and time to print. – CodesInChaos Aug 11 '14 at 17:33
  • Your code looks totally broken to me since you mixed up `Hours` and `TotalHours` etc. Outputting a 25h timespan as `1Hrs` is certainly not what you want. – CodesInChaos Aug 11 '14 at 17:35

0 Answers0