Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Check if a DateTime is between two other DateTimes
Message
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Versions des environnements
Environment:
C# 2.0
Divers
Thread ID:
01375956
Message ID:
01375968
Vues:
9
This message has been marked as a message which has helped to the initial question of the thread.
>I could have sworn that I have seen a built in function/method that will return a bool if a Datetime variable is between two other DateTime variables, but I can't find it. I am getting hungry now so all I can think of if the leftover pizza in my fridge.
>Have anyone seem a built in function that will do what I need it to do? Otherwise if you have some code that does this it would be great.
>
>Off to get some pizza :)


Extension method ok ?
Console.WriteLine(" {0}", DateTime.Today.Between(DateTime.Today, DateTime.Today));
Console.ReadLine();
using System;
using System.Linq;

// Generic
namespace GregoryAdam.Base.ExtensionMethods
{

	public static partial class ExtensionMethods
	{
		#region Between
		/// <summary>
		/// tells whether s between s1 and s2
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="s"></param>
		/// <param name="s1"></param>
		/// <param name="s2"></param>
		/// <returns>true or false</returns>
		//
		// IComparable<T>
		//	- By definition, any object compares greater than a null reference 
		//	- two null references compare equal to each other
		public static bool Between<T>(this T s, T s1, T s2) where T : IComparable<T>
		{
			if( s != null )
				return (s.CompareTo(s1) >= 0) && (s.CompareTo(s2) <= 0);

			// s == null here

			/*
			 *		s1		s		s2		s1<=s	s<=s2	final
			 *		!=null	null	!null	false	true	false
			 *		null	null	!null	true	true	true	*
			 *		!null	null	null	false	true	false
			 *		null	null	null	true	true	true	*
			 */
			/*
			 * conclusion
			 * It does not matter whether s2 is null or not
			 *		s < non-null-s2
			 *		s == null-s2
			 *		hence always:	s <= s2
			 *		
			 * the only thing that matters is s1
			 *		non_null_s1 < s
			 *		null_s1 == s
			 */
			return (s1 == null);
		}
#if false
		// 3 times slower
		public static bool Between(this IComparable s, IComparable s1, IComparable s2)
		{
			return (s.CompareTo(s1) >= 0) && (s.CompareTo(s2) <= 0);
		}
#endif
		#endregion
		//--------------------------------------------------------------------------------
}
}
Gregory
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform