date comparison problem
I have a string named date
. date
holds date like jan 10
. I want to check whether it falls betwee开发者_开发技巧n two dates or not . Example jan 10
is between dec 10
and feb 10
. How can I do this task?
Convert your dates to DateTime and than use the JPLabs extension method Between.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JpLabs.Extensions
{
public static class ComparableExt
{
static public bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>
{
return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) < 0;
}
}
}
I hope it helps.
Manish
This should do it if you are using c#
public bool IsDateBetweenOtherDates(DateTime startDate,DateTime endDate, DateTime testDate)
{
return startDate < testDate && endDate > testDate;
}
string date = "jan 10";
var dt = DateTime.ParseExact(date, "MMM dd", CultureInfo.InvariantCulture);
if (dt < new DateTime(dt.Year, 12, 10) &&
dt > new DateTime(dt.Year, 2, 10))
{
// the date is between 10 feb and 10 dec.
}
You need to use DateTime.TryParse()
to turn your string into a DateTime, which can then be compared to other dates.
DateTime minDate = // minimum boundary
DateTime maxDate = // maximum boundary
string input = "January 10, 2010";
DateTime inputDate;
if (DateTime.TryParse(input, out inputDate))
{
if (inputDate > minDate && inputDate < maxDate)
{
...
}
}
Try this:
public bool IsDateBetweenOtherDates(DateTime startDate,DateTime endDate, DateTime testDate)
{
return startDate < testDate && endDate > testDate;
}
精彩评论