Posted By

Maelstrom on 05/17/11


Tagged

time date pretty formatted facebook


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

ovuncgursoy
Priestd09


Pretty Date (Facebook/Twitter style) - X Month(s)/Week(s)/Day(s)/Hour(s)/Minute(s)/Second(s) ago


 / Published in: C#
 

URL: prettydate

A simple C# function to take a standard DateTime and convert it to a pretty string saying how many seconds/minutes/days/weeks/months ago the date was, it doesn't return an actual date, but that wouldn't be hard to change the month/week/day section to return a formatted date instead of the string currently returned.

  1. public static string PrettyDate(String TimeSubmitted)
  2. {
  3. // accepts standard DateTime: 5/12/2011 2:36:00 PM
  4. // returns: "# month(s)/week(s)/day(s)/hour(s)/minute(s)/second(s)) ago"
  5. string prettyDate = TimeSubmitted;
  6.  
  7. DateTime SubmittedDate = DateTime.Parse(TimeSubmitted);
  8. DateTime Now = DateTime.Now;
  9. TimeSpan Diff = Now - SubmittedDate;
  10.  
  11. if (Diff.Seconds <= 0)
  12. {
  13. prettyDate = TimeSubmitted;
  14. }
  15. else if (Diff.Days > 30)
  16. {
  17. prettyDate = Diff.Days / 30 + " month" + (Diff.Days / 30 >= 2 ? "s " : " ") + "ago";
  18. }
  19. else if (Diff.Days > 7)
  20. {
  21. prettyDate = Diff.Days / 7 + " week" + (Diff.Days / 7 >= 2 ? "s " : " ") + "ago";
  22. }
  23. else if (Diff.Days >= 1)
  24. {
  25. prettyDate = Diff.Days + " day" + (Diff.Days >= 2 ? "s " : " ") + "ago";
  26. }
  27. else if (Diff.Hours >= 1)
  28. {
  29. prettyDate = Diff.Hours + " hour" + (Diff.Hours >= 2 ? "s " : " ") + "ago";
  30. }
  31. else if (Diff.Minutes >= 1)
  32. {
  33. prettyDate = Diff.Minutes + " minute" + (Diff.Minutes >= 2 ? "s " : " ") + "ago";
  34. }
  35. else
  36. {
  37. prettyDate = Diff.Seconds + " second" + (Diff.Seconds >= 2 ? "s " : " ") + "ago";
  38. }
  39. return prettyDate;
  40. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: joancaron2 on January 29, 2013

Great solution! I posted an another way to get a pretty date (timespan) with c#

You need to login to post a comment.