/Utilities/Helpers/DateHelper.cs
# · C# · 393 lines · 257 code · 25 blank · 111 comment · 33 complexity · ea05b37f10fc8fbb0bf7eeda3ca48c35 MD5 · raw file
- using System;
- using System.Globalization;
- using NUnit.Framework;
-
- namespace Delta.Utilities.Helpers
- {
- /// <summary>
- /// Date helper class, mostly used just to present date times in a common
- /// format (like ISO date strings), but also has some helper methods to
- /// check different dates and parse date strings.
- /// </summary>
- public static class DateHelper
- {
- #region GetTimeString (Static)
- /// <summary>
- /// GetTimeString
- /// </summary>
- /// <param name="time">Time</param>
- /// <returns>String</returns>
- public static string GetTimeString(this DateTime time)
- {
- return String.Format("{0:00}:{1:00}", time.Hour, time.Minute);
- }
- #endregion
-
- #region GetForumDateAndTime (Static)
- /// <summary>
- /// Get forum date and time in german format, day.month.year hour:minute
- /// </summary>
- /// <param name="date">Date</param>
- /// <returns>String</returns>
- public static string GetForumDateAndTime(this DateTime date)
- {
- string dateString =
- String.Format("{0:00}.{1:00}.{2}", date.Day, date.Month, date.Year);
- string timeString =
- // Skip time if it is 00:00 (which usually means no time is given)
- (date.Hour != 0 || date.Minute != 0
- ? String.Format("{0:00}:{1:00}", date.Hour, date.Minute)
- : "");
-
- // Make bold if this was posted today!
- bool wasPostedToday =
- date.DayOfYear == DateTime.Now.DayOfYear &&
- date.Year == DateTime.Now.Year;
- if (wasPostedToday &&
- String.IsNullOrEmpty(timeString) == false)
- {
- return String.Format("<b>{0}</b>", timeString);
- }
- else
- {
- return String.Format("{0} {1}", dateString, timeString);
- }
- }
- #endregion
-
- #region GetAtForumDateAndTime (Static)
- /// <summary>
- /// Get at forum date and time
- /// </summary>
- /// <param name="date">DateHelper</param>
- /// <returns>String</returns>
- public static string GetAtForumDateAndTime(this DateTime date)
- {
- string dateString =
- String.Format("{0:00}.{1:00}.{2}", date.Day, date.Month, date.Year);
- string timeString =
- // Skip time if it is 00:00 (which usually means no time is given)
- (date.Hour != 0 || date.Minute != 0
- ? String.Format("{0:00}:{1:00}", date.Hour, date.Minute)
- : "");
-
- // Make bold if this was posted today!
- bool wasPostedToday =
- date.DayOfYear == DateTime.Now.DayOfYear &&
- date.Year == DateTime.Now.Year;
- if (wasPostedToday &&
- String.IsNullOrEmpty(timeString) == false)
- {
- return String.Format("um <b>{0}</b>", timeString);
- }
- else
- {
- return String.Format("am {0} {1}", dateString, timeString);
- }
- }
- #endregion
-
- #region GetDateFromString (Static)
- /// <summary>
- /// Get date from string
- /// </summary>
- /// <param name="dateString">Date string</param>
- /// <returns>Date time</returns>
- public static DateTime GetDateFromString(string dateString)
- {
- // First check if this contains a space and might be a date + time
- if (dateString.Contains(" "))
- {
- return GetDateAndTimeFromString(dateString);
- }
-
- // Try to get it the normal way ^^
- DateTime ret = DateTime.Now;
- bool dateSucceeded = true;
- try
- {
- dateSucceeded = DateTime.TryParse(dateString,
- CultureInfo.InvariantCulture, DateTimeStyles.None, out ret);
- }
- catch
- {
- }
-
- if (dateSucceeded == false)
- {
- try
- {
- string[] dateParts = dateString.SplitAndTrim('.');
- if (dateParts.Length >= 3)
- {
- ret = new DateTime(
- Convert.ToInt32(dateParts[2]),
- Convert.ToInt32(dateParts[1]),
- Convert.ToInt32(dateParts[0]));
- }
- else if (dateParts.Length == 1)
- {
- // Support formats like "2011-07-27" as well (should already be
- // handled above, but sometimes it does not work).
- dateParts = dateString.SplitAndTrim('-');
- if (dateParts.Length >= 3)
- {
- ret = new DateTime(
- Convert.ToInt32(dateParts[0]),
- Convert.ToInt32(dateParts[1]),
- Convert.ToInt32(dateParts[2]));
- }
- else
- {
- // Finally check for American dates with / like "07/27/2011"
- dateParts = dateString.SplitAndTrim('/');
- if (dateParts.Length >= 3)
- {
- ret = new DateTime(
- Convert.ToInt32(dateParts[2]),
- Convert.ToInt32(dateParts[0]),
- Convert.ToInt32(dateParts[1]));
- }
- else
- {
- // Just grab the year, but even that might not work ..
- ret = new DateTime(
- Convert.ToInt32(dateParts[0]), 1, 1);
- }
- }
- }
- }
- catch { }
- // catch
-
- // If this did not work, then just use the current time.
- // This sometimes seems to happen with WebNews, but not often!
- if (ret.Year <= 1)
- {
- ret = DateTime.Now;
- }
- }
-
- return ret;
- }
- #endregion
-
- #region GetDateAndTimeFromString (Static)
- /// <summary>
- /// Get date and time from string
- /// </summary>
- /// <param name="dateString">Date string</param>
- /// <returns>Date time</returns>
- public static DateTime GetDateAndTimeFromString(string dateString)
- {
- if (dateString.Trim().Length == 0)
- {
- return DateTime.Now;
- }
-
- DateTime date = DateTime.Now;
- try
- {
- // You might ask yourself why go through all this trouble parsing
- // the date ourselves when DateTime.TryParse can do the same. Well,
- // this is several times faster and most dates are in this format :)
- string[] dateAndTime = dateString.Split(new[]
- {
- ' ', ':'
- });
- date = GetDateFromString(dateAndTime[0]);
- if (dateAndTime.Length >= 3)
- {
- date = date.AddHours(Convert.ToInt32(dateAndTime[1]));
- date = date.AddMinutes(Convert.ToInt32(dateAndTime[2]));
- if (dateAndTime.Length >= 4)
- {
- date = date.AddSeconds(Convert.ToInt32(dateAndTime[3]));
- }
- }
- }
- catch
- {
- // Else just use the normal parser
- DateTime.TryParse(dateString, out date);
- }
-
- return date;
- }
- #endregion
-
- #region IsDateNewer (Static)
- /// <summary>
- /// Is date newer than the older date. Very useful for file comparisions.
- /// </summary>
- /// <param name="newerDate">Newer date</param>
- /// <param name="olderDate">Older date</param>
- /// <returns>True if the newer date is newer than the older date</returns>
- public static bool IsDateNewer(DateTime newerDate, DateTime olderDate)
- {
- return newerDate.CompareTo(olderDate) == 1;
- }
- #endregion
-
- #region IsDateInRange (Static)
- /// <summary>
- /// Is date in range. Will return true if currentData is between beginDate
- /// and endDate.
- /// </summary>
- /// <param name="currentDate">Current date</param>
- /// <param name="beginDate">Range begin</param>
- /// <param name="endDate">Range end</param>
- /// <returns>
- /// True if currentData is between beginDate and endDate.
- /// </returns>
- public static bool IsDateInRange(this DateTime currentDate,
- DateTime beginDate, DateTime endDate)
- {
- return
- beginDate.CompareTo(currentDate) < 1 &&
- endDate.CompareTo(currentDate) > -1;
- }
- #endregion
-
- #region AreSameDays (Static)
- /// <summary>
- /// Are day1 and day2 are the same day?
- /// </summary>
- /// <param name="day1">Day 1</param>
- /// <param name="day2">Day 2</param>
- /// <returns>
- /// True if the days are the same (ignoring all the other datetime values).
- /// </returns>
- public static bool AreSameDays(DateTime day1, DateTime day2)
- {
- return day1.Date.CompareTo(day2.Date) == 0;
- }
- #endregion
-
- #region GetIsoDate (Static)
- /// <summary>
- /// Returns the "Iso Date" stamp (Year-Month-Day).
- /// </summary>
- /// <param name="date">Date</param>
- /// <returns>"Iso Date" stamp (Year-Month-Day)</returns>
- public static string GetIsoDate(this DateTime date)
- {
- return date.Year + "-" +
- date.Month.ToString("00") + "-" +
- date.Day.ToString("00");
- }
- #endregion
-
- #region GetIsoTime (Static)
- /// <summary>
- /// Get Iso time stamp (Hour:Minute:Second)
- /// </summary>
- /// <param name="time">Datetime input</param>
- /// <returns>String with the time in hours:minutes:seconds</returns>
- public static string GetIsoTime(this DateTime time)
- {
- return time.Hour.ToString("00") + ":" +
- time.Minute.ToString("00") + ":" +
- time.Second.ToString("00");
- }
- #endregion
-
- #region GetIsoTimeWithMiliseconds (Static)
- /// <summary>
- /// Get iso time with miliseconds. Note: DateTime is not very accurate,
- /// use better timings with the Time or GameTime classes for ingame
- /// purposes (profiling, debugging, etc. otherwise strings should not be
- /// needed anyway). This is mostly
- /// </summary>
- /// <param name="time">Time for output</param>
- /// <returns>
- /// Text with the time in hours:minutes:seconds.milliseconds format.
- /// </returns>
- public static string GetIsoTimeWithMiliseconds(this DateTime time)
- {
- return time.Hour.ToString("00") + ":" +
- time.Minute.ToString("00") + ":" +
- time.Second.ToString("00") + "." +
- time.Millisecond.ToString("000");
- }
- #endregion
-
- #region GetIsoDateTime (Static)
- /// <summary>
- /// Get Iso date time stamp (Year-Month-Day Hour:Minute:Second)
- /// </summary>
- /// <param name="dateTime">Date Time</param>
- /// <returns>Date Time</returns>
- public static string GetIsoDateTime(this DateTime dateTime)
- {
- return GetIsoDate(dateTime) + " " + GetIsoTime(dateTime);
- }
- #endregion
-
- #region IsDate (Static)
- /// <summary>
- /// Is date, to check if for example the string contains DateTime value
- /// if not return false
- /// </summary>
- /// <param name="obj">Object to check if this is a date</param>
- /// <returns>True if this is a date, false otherwise</returns>
- public static bool IsDate(Object obj)
- {
- string dateString = obj.ToString();
- try
- {
- DateTime dateLocal = DateTime.Parse(dateString);
- if (dateLocal != DateTime.MinValue &&
- dateLocal != DateTime.MaxValue)
- {
- return true;
- }
- return false;
- }
- catch
- {
- return false;
- }
- }
- #endregion
-
- /// <summary>
- /// Test
- /// </summary>
- internal class DateHelperTests
- {
- #region IsDateNewer
- /// <summary>
- /// Is date newer
- /// </summary>
- [Test]
- public void IsDateNewer()
- {
- DateTime newerDate = new DateTime(2007, 6, 21);
- DateTime olderDate = new DateTime(2007, 6, 20);
-
- Assert.True(DateHelper.IsDateNewer(newerDate, olderDate));
- Assert.False(DateHelper.IsDateNewer(newerDate, newerDate));
-
- DateTime notOlderDate = new DateTime(2008, 6, 21);
- Assert.False(DateHelper.IsDateNewer(newerDate, notOlderDate));
- }
- #endregion
-
- #region GetIsoDateTime
- /// <summary>
- /// Get iso date time stamp
- /// </summary>
- [Test]
- public void GetIsoDateTime()
- {
- Assert.Equal("2009-11-17 13:06:01",
- new DateTime(2009, 11, 17, 13, 6, 1).GetIsoDateTime());
- DateTime testTime = new DateTime(2009, 11, 17, 13, 6, 1);
- Assert.Equal(testTime, GetDateAndTimeFromString(
- testTime.GetIsoDateTime()));
- }
- #endregion
- }
- }
- }