Задача: Преобразование сумм из цифрового представления в строковое
Исходник: дата словам - и, язык: C# [code #581, hits: 10008]
аноним: student [добавлен: 25.01.2009]
  1. namespace ITArts.SyncFox.Utils
  2. {
  3. using System;
  4. using System.Web;
  5. using System.Text;
  6. using ITArts.SyncFox.Utils;
  7. using System.Web.Query.Dynamic;
  8.  
  9. public static class DataTimeExtension
  10. {
  11. public static string NumericTxt(int Number,
  12. string nominative, //Именительный падеж
  13. string genitive_singular,//Родительный падеж, единственное число
  14. string genitive_plural) //Родительный падеж, множественное число
  15. {
  16.  
  17. int[] FormsTable = { 2, 0, 1, 1, 1, 2, 2, 2, 2, 2 };
  18.  
  19. Number = Math.Abs(Number);
  20. int res = FormsTable[((((Number % 100) / 10) != 1) ? 1 : 0) * (Number % 10)];
  21. switch (res)
  22. {
  23. case 0:
  24. return nominative;
  25. case 1:
  26. return genitive_singular;
  27. default:
  28. return genitive_plural;
  29. }
  30. }
  31.  
  32.  
  33.  
  34. public static string Ago(this DateTime targetUTC)
  35. {
  36. StringBuilder result = new StringBuilder();
  37. TimeSpan diff = (DateTime.Now - targetUTC);
  38.  
  39.  
  40. if (diff.Days > 0)
  41. {
  42.  
  43. result.AppendFormat(NumericTxt(diff.Days,CommonRes.msg_AgoDaysI, CommonRes.msg_AgoDaysR1,CommonRes.msg_AgoDaysRm), diff.Days);
  44. }
  45.  
  46. if (diff.Hours > 0)
  47. {
  48. if (result.Length > 0)
  49. {
  50. result.Append(", ");
  51. }
  52.  
  53. result.AppendFormat(NumericTxt(diff.Hours, CommonRes.msg_AgoHoursI, CommonRes.msg_AgoHoursR1, CommonRes.msg_AgoHoursRm), diff.Hours);
  54. }
  55.  
  56. if (diff.Minutes > 0)
  57. {
  58. if (result.Length > 0)
  59. {
  60. result.Append(", ");
  61. }
  62.  
  63. result.AppendFormat(NumericTxt(diff.Minutes, CommonRes.msg_AgoMinutesI, CommonRes.msg_AgoMinutesR1, CommonRes.msg_AgoMinutesRm), diff.Minutes);
  64. }
  65.  
  66. if (result.Length == 0)
  67. {
  68. result.Append(CommonRes.msg_AgoFewMoments);
  69. }
  70. else
  71. {
  72.  
  73. result.Insert(0, CommonRes.msg_About);
  74. result.AppendFormat(" " + CommonRes.msg_Ago);
  75. }
  76.  
  77. return result.ToString();
  78. }
  79. }
Недавно стояла задача отображать количество дней, часов, минут, прошедших после внесения изменений в данные.

Т.е., например:
1 день 23 часа и 20 минут назад.
или 11 дней 1 час и 2 минуты назад и пр.

Решил выложить небольшой кусок кода проекта, который позволяет это делать, расширяя тип DateTime.

формат строк для отображения берется из файла с ресурсами:

msg_About ~
msg_Ago назад
msg_AgoDaysI {0} день
msg_AgoDaysR1 {0} дня
msg_AgoDaysRm {0} дней
msg_AgoFewMoments только что
msg_AgoHoursI {0} час
msg_AgoHoursR1 {0} часа
msg_AgoHoursRm {0} часов
msg_AgoMinutesI {0} минута
msg_AgoMinutesR1 {0} минуты
msg_AgoMinutesRm {0} минут


пример использования оного кода:

DateTime hz;
string data = hz.Ago();

+добавить реализацию