fork download
  1. using System;
  2. using static System.Console;
  3.  
  4. public class Program {
  5. public static void Main() {
  6. var d = new DateTime(2014, 1, 15);
  7. var d2 = new DateTime(2015, 7, 15);
  8. var d3 = new DateTime(2015, 8, 25, 8, 0, 0);
  9. var d4 = new DateTime(2015, 8, 24);
  10. var agora = new DateTime(2015, 8, 25, 0, 0, 0);
  11. WriteLine((d - agora).RelativeTime());
  12. WriteLine((d2 - agora).RelativeTime());
  13. WriteLine((d3 - agora).RelativeTime());
  14. WriteLine((d4 - agora).RelativeTime());
  15. }
  16. }
  17.  
  18. public static class RelativeTimeExtensions {
  19. public static String RelativeTime(this TimeSpan ts) {
  20. const int second = 1;
  21. const int minute = 60 * second;
  22. const int hour = 60 * minute;
  23. const int day = 24 * hour;
  24. const int month = 30 * day;
  25. double delta = Math.Abs(ts.TotalSeconds);
  26. //melhor se escrever só "Agora há pouco"
  27. if (delta < 1 * minute) return "Há " + (ts.Seconds == 1 ? "um segundo" : ts.Seconds + " segundos");
  28. if (delta < 2 * minute) return "Há um minuto";
  29. if (delta < 45 * minute) return "Há " + ts.Minutes + " minutos";
  30. if (delta < 90 * minute) return "Há uma hora";
  31. if (delta < 24 * hour) return "Há " + ts.Hours + " horas";
  32. if (delta < 48 * hour) return "ontem";
  33. if (delta < 30 * day) return "Há " + ts.Days + " dias";
  34. if (delta < 12 * month) {
  35. var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  36. return "Há " + (months <= 1 ? "um mês" : months + " meses");
  37. } else {
  38. var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  39. return "Há " + (years <= 1 ? "um ano" : years + " anos");
  40. }
  41. }
  42. }
  43.  
  44. //https://pt.stackoverflow.com/q/82278/101
Success #stdin #stdout 0.02s 16168KB
stdin
Standard input is empty
stdout
Há um ano
Há um mês
Há 8 horas
ontem