How do I check for time for between. suppose I have Time in string format like "02:00 PM" and I want to check it between two other times. How can I check for this, as the time is in string format ? The value to be compare with the开发者_如何学C times is store in DataTable, and I am using the Select function of the datatable.
Try DateTime.Parse(dateString1) > DateTime.Parse(dateString2)
.
If your string format is not compatible with the string format of DateTime
, you'll need to parse your date manually.
Edit:
You can use ParseExact
to specify your own format:
string Format = "T";
CultureInfo provider = new CultureInfo("en-US");
if (DateTime.ParseExact(dateString1, format, provider) >
DateTime.ParseExact(dateString2, format, provider))
{
...
You can always convert to string to a timespan (or datetime) something like this:
TimeSpan ts = Convert.ToDateTime("02:00 PM").TimeOfDay;
TimeSpan checkValue1 = Convert.ToDateTime("01:00 PM").TimeOfDay;
TimeSpan checkValue2 = Convert.ToDateTime("03:00 PM").TimeOfDay;
bool passed = (ts >= checkValue1 && ts <= checkValue2);
Convert it to a DateTime
with the current date as date, or a TimeSpan
representing the time from midnight:
DateTime time = DateTime.Parse(timeString);
Or:
TimeSpan time = DateTime.Parse(timeString).TimeOfDay;
Having the value as a TimeSpan
might be easier when you compare it, otherwise you have to make sure that the DateTime
values that you compare it to also have the current date as date. On the other hand, the DateTime
value can be used to compare times across midnight, e.g. between 23.00 today and 01.00 tomorrow.
精彩评论