PageRenderTime 36ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/Utilities/Helpers/DateHelper.cs

#
C# | 393 lines | 257 code | 25 blank | 111 comment | 33 complexity | ea05b37f10fc8fbb0bf7eeda3ca48c35 MD5 | raw file
Possible License(s): Apache-2.0
  1. using System;
  2. using System.Globalization;
  3. using NUnit.Framework;
  4. namespace Delta.Utilities.Helpers
  5. {
  6. /// <summary>
  7. /// Date helper class, mostly used just to present date times in a common
  8. /// format (like ISO date strings), but also has some helper methods to
  9. /// check different dates and parse date strings.
  10. /// </summary>
  11. public static class DateHelper
  12. {
  13. #region GetTimeString (Static)
  14. /// <summary>
  15. /// GetTimeString
  16. /// </summary>
  17. /// <param name="time">Time</param>
  18. /// <returns>String</returns>
  19. public static string GetTimeString(this DateTime time)
  20. {
  21. return String.Format("{0:00}:{1:00}", time.Hour, time.Minute);
  22. }
  23. #endregion
  24. #region GetForumDateAndTime (Static)
  25. /// <summary>
  26. /// Get forum date and time in german format, day.month.year hour:minute
  27. /// </summary>
  28. /// <param name="date">Date</param>
  29. /// <returns>String</returns>
  30. public static string GetForumDateAndTime(this DateTime date)
  31. {
  32. string dateString =
  33. String.Format("{0:00}.{1:00}.{2}", date.Day, date.Month, date.Year);
  34. string timeString =
  35. // Skip time if it is 00:00 (which usually means no time is given)
  36. (date.Hour != 0 || date.Minute != 0
  37. ? String.Format("{0:00}:{1:00}", date.Hour, date.Minute)
  38. : "");
  39. // Make bold if this was posted today!
  40. bool wasPostedToday =
  41. date.DayOfYear == DateTime.Now.DayOfYear &&
  42. date.Year == DateTime.Now.Year;
  43. if (wasPostedToday &&
  44. String.IsNullOrEmpty(timeString) == false)
  45. {
  46. return String.Format("<b>{0}</b>", timeString);
  47. }
  48. else
  49. {
  50. return String.Format("{0} {1}", dateString, timeString);
  51. }
  52. }
  53. #endregion
  54. #region GetAtForumDateAndTime (Static)
  55. /// <summary>
  56. /// Get at forum date and time
  57. /// </summary>
  58. /// <param name="date">DateHelper</param>
  59. /// <returns>String</returns>
  60. public static string GetAtForumDateAndTime(this DateTime date)
  61. {
  62. string dateString =
  63. String.Format("{0:00}.{1:00}.{2}", date.Day, date.Month, date.Year);
  64. string timeString =
  65. // Skip time if it is 00:00 (which usually means no time is given)
  66. (date.Hour != 0 || date.Minute != 0
  67. ? String.Format("{0:00}:{1:00}", date.Hour, date.Minute)
  68. : "");
  69. // Make bold if this was posted today!
  70. bool wasPostedToday =
  71. date.DayOfYear == DateTime.Now.DayOfYear &&
  72. date.Year == DateTime.Now.Year;
  73. if (wasPostedToday &&
  74. String.IsNullOrEmpty(timeString) == false)
  75. {
  76. return String.Format("um <b>{0}</b>", timeString);
  77. }
  78. else
  79. {
  80. return String.Format("am {0} {1}", dateString, timeString);
  81. }
  82. }
  83. #endregion
  84. #region GetDateFromString (Static)
  85. /// <summary>
  86. /// Get date from string
  87. /// </summary>
  88. /// <param name="dateString">Date string</param>
  89. /// <returns>Date time</returns>
  90. public static DateTime GetDateFromString(string dateString)
  91. {
  92. // First check if this contains a space and might be a date + time
  93. if (dateString.Contains(" "))
  94. {
  95. return GetDateAndTimeFromString(dateString);
  96. }
  97. // Try to get it the normal way ^^
  98. DateTime ret = DateTime.Now;
  99. bool dateSucceeded = true;
  100. try
  101. {
  102. dateSucceeded = DateTime.TryParse(dateString,
  103. CultureInfo.InvariantCulture, DateTimeStyles.None, out ret);
  104. }
  105. catch
  106. {
  107. }
  108. if (dateSucceeded == false)
  109. {
  110. try
  111. {
  112. string[] dateParts = dateString.SplitAndTrim('.');
  113. if (dateParts.Length >= 3)
  114. {
  115. ret = new DateTime(
  116. Convert.ToInt32(dateParts[2]),
  117. Convert.ToInt32(dateParts[1]),
  118. Convert.ToInt32(dateParts[0]));
  119. }
  120. else if (dateParts.Length == 1)
  121. {
  122. // Support formats like "2011-07-27" as well (should already be
  123. // handled above, but sometimes it does not work).
  124. dateParts = dateString.SplitAndTrim('-');
  125. if (dateParts.Length >= 3)
  126. {
  127. ret = new DateTime(
  128. Convert.ToInt32(dateParts[0]),
  129. Convert.ToInt32(dateParts[1]),
  130. Convert.ToInt32(dateParts[2]));
  131. }
  132. else
  133. {
  134. // Finally check for American dates with / like "07/27/2011"
  135. dateParts = dateString.SplitAndTrim('/');
  136. if (dateParts.Length >= 3)
  137. {
  138. ret = new DateTime(
  139. Convert.ToInt32(dateParts[2]),
  140. Convert.ToInt32(dateParts[0]),
  141. Convert.ToInt32(dateParts[1]));
  142. }
  143. else
  144. {
  145. // Just grab the year, but even that might not work ..
  146. ret = new DateTime(
  147. Convert.ToInt32(dateParts[0]), 1, 1);
  148. }
  149. }
  150. }
  151. }
  152. catch { }
  153. // catch
  154. // If this did not work, then just use the current time.
  155. // This sometimes seems to happen with WebNews, but not often!
  156. if (ret.Year <= 1)
  157. {
  158. ret = DateTime.Now;
  159. }
  160. }
  161. return ret;
  162. }
  163. #endregion
  164. #region GetDateAndTimeFromString (Static)
  165. /// <summary>
  166. /// Get date and time from string
  167. /// </summary>
  168. /// <param name="dateString">Date string</param>
  169. /// <returns>Date time</returns>
  170. public static DateTime GetDateAndTimeFromString(string dateString)
  171. {
  172. if (dateString.Trim().Length == 0)
  173. {
  174. return DateTime.Now;
  175. }
  176. DateTime date = DateTime.Now;
  177. try
  178. {
  179. // You might ask yourself why go through all this trouble parsing
  180. // the date ourselves when DateTime.TryParse can do the same. Well,
  181. // this is several times faster and most dates are in this format :)
  182. string[] dateAndTime = dateString.Split(new[]
  183. {
  184. ' ', ':'
  185. });
  186. date = GetDateFromString(dateAndTime[0]);
  187. if (dateAndTime.Length >= 3)
  188. {
  189. date = date.AddHours(Convert.ToInt32(dateAndTime[1]));
  190. date = date.AddMinutes(Convert.ToInt32(dateAndTime[2]));
  191. if (dateAndTime.Length >= 4)
  192. {
  193. date = date.AddSeconds(Convert.ToInt32(dateAndTime[3]));
  194. }
  195. }
  196. }
  197. catch
  198. {
  199. // Else just use the normal parser
  200. DateTime.TryParse(dateString, out date);
  201. }
  202. return date;
  203. }
  204. #endregion
  205. #region IsDateNewer (Static)
  206. /// <summary>
  207. /// Is date newer than the older date. Very useful for file comparisions.
  208. /// </summary>
  209. /// <param name="newerDate">Newer date</param>
  210. /// <param name="olderDate">Older date</param>
  211. /// <returns>True if the newer date is newer than the older date</returns>
  212. public static bool IsDateNewer(DateTime newerDate, DateTime olderDate)
  213. {
  214. return newerDate.CompareTo(olderDate) == 1;
  215. }
  216. #endregion
  217. #region IsDateInRange (Static)
  218. /// <summary>
  219. /// Is date in range. Will return true if currentData is between beginDate
  220. /// and endDate.
  221. /// </summary>
  222. /// <param name="currentDate">Current date</param>
  223. /// <param name="beginDate">Range begin</param>
  224. /// <param name="endDate">Range end</param>
  225. /// <returns>
  226. /// True if currentData is between beginDate and endDate.
  227. /// </returns>
  228. public static bool IsDateInRange(this DateTime currentDate,
  229. DateTime beginDate, DateTime endDate)
  230. {
  231. return
  232. beginDate.CompareTo(currentDate) < 1 &&
  233. endDate.CompareTo(currentDate) > -1;
  234. }
  235. #endregion
  236. #region AreSameDays (Static)
  237. /// <summary>
  238. /// Are day1 and day2 are the same day?
  239. /// </summary>
  240. /// <param name="day1">Day 1</param>
  241. /// <param name="day2">Day 2</param>
  242. /// <returns>
  243. /// True if the days are the same (ignoring all the other datetime values).
  244. /// </returns>
  245. public static bool AreSameDays(DateTime day1, DateTime day2)
  246. {
  247. return day1.Date.CompareTo(day2.Date) == 0;
  248. }
  249. #endregion
  250. #region GetIsoDate (Static)
  251. /// <summary>
  252. /// Returns the "Iso Date" stamp (Year-Month-Day).
  253. /// </summary>
  254. /// <param name="date">Date</param>
  255. /// <returns>"Iso Date" stamp (Year-Month-Day)</returns>
  256. public static string GetIsoDate(this DateTime date)
  257. {
  258. return date.Year + "-" +
  259. date.Month.ToString("00") + "-" +
  260. date.Day.ToString("00");
  261. }
  262. #endregion
  263. #region GetIsoTime (Static)
  264. /// <summary>
  265. /// Get Iso time stamp (Hour:Minute:Second)
  266. /// </summary>
  267. /// <param name="time">Datetime input</param>
  268. /// <returns>String with the time in hours:minutes:seconds</returns>
  269. public static string GetIsoTime(this DateTime time)
  270. {
  271. return time.Hour.ToString("00") + ":" +
  272. time.Minute.ToString("00") + ":" +
  273. time.Second.ToString("00");
  274. }
  275. #endregion
  276. #region GetIsoTimeWithMiliseconds (Static)
  277. /// <summary>
  278. /// Get iso time with miliseconds. Note: DateTime is not very accurate,
  279. /// use better timings with the Time or GameTime classes for ingame
  280. /// purposes (profiling, debugging, etc. otherwise strings should not be
  281. /// needed anyway). This is mostly
  282. /// </summary>
  283. /// <param name="time">Time for output</param>
  284. /// <returns>
  285. /// Text with the time in hours:minutes:seconds.milliseconds format.
  286. /// </returns>
  287. public static string GetIsoTimeWithMiliseconds(this DateTime time)
  288. {
  289. return time.Hour.ToString("00") + ":" +
  290. time.Minute.ToString("00") + ":" +
  291. time.Second.ToString("00") + "." +
  292. time.Millisecond.ToString("000");
  293. }
  294. #endregion
  295. #region GetIsoDateTime (Static)
  296. /// <summary>
  297. /// Get Iso date time stamp (Year-Month-Day Hour:Minute:Second)
  298. /// </summary>
  299. /// <param name="dateTime">Date Time</param>
  300. /// <returns>Date Time</returns>
  301. public static string GetIsoDateTime(this DateTime dateTime)
  302. {
  303. return GetIsoDate(dateTime) + " " + GetIsoTime(dateTime);
  304. }
  305. #endregion
  306. #region IsDate (Static)
  307. /// <summary>
  308. /// Is date, to check if for example the string contains DateTime value
  309. /// if not return false
  310. /// </summary>
  311. /// <param name="obj">Object to check if this is a date</param>
  312. /// <returns>True if this is a date, false otherwise</returns>
  313. public static bool IsDate(Object obj)
  314. {
  315. string dateString = obj.ToString();
  316. try
  317. {
  318. DateTime dateLocal = DateTime.Parse(dateString);
  319. if (dateLocal != DateTime.MinValue &&
  320. dateLocal != DateTime.MaxValue)
  321. {
  322. return true;
  323. }
  324. return false;
  325. }
  326. catch
  327. {
  328. return false;
  329. }
  330. }
  331. #endregion
  332. /// <summary>
  333. /// Test
  334. /// </summary>
  335. internal class DateHelperTests
  336. {
  337. #region IsDateNewer
  338. /// <summary>
  339. /// Is date newer
  340. /// </summary>
  341. [Test]
  342. public void IsDateNewer()
  343. {
  344. DateTime newerDate = new DateTime(2007, 6, 21);
  345. DateTime olderDate = new DateTime(2007, 6, 20);
  346. Assert.True(DateHelper.IsDateNewer(newerDate, olderDate));
  347. Assert.False(DateHelper.IsDateNewer(newerDate, newerDate));
  348. DateTime notOlderDate = new DateTime(2008, 6, 21);
  349. Assert.False(DateHelper.IsDateNewer(newerDate, notOlderDate));
  350. }
  351. #endregion
  352. #region GetIsoDateTime
  353. /// <summary>
  354. /// Get iso date time stamp
  355. /// </summary>
  356. [Test]
  357. public void GetIsoDateTime()
  358. {
  359. Assert.Equal("2009-11-17 13:06:01",
  360. new DateTime(2009, 11, 17, 13, 6, 1).GetIsoDateTime());
  361. DateTime testTime = new DateTime(2009, 11, 17, 13, 6, 1);
  362. Assert.Equal(testTime, GetDateAndTimeFromString(
  363. testTime.GetIsoDateTime()));
  364. }
  365. #endregion
  366. }
  367. }
  368. }