如何比较C#中hh:mm:ss格式的日期时间? [英] How to compare time from datetime in hh:mm:ss format in C# ?
本文介绍了如何比较C#中hh:mm:ss格式的日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
i有视觉工作室winform c#
i希望比较日期时间的hh:mm格式在特定范围内的时间。
但是它不能正常工作
我的源代码中的
范围是[start_time,End_time]。
换句话说,从日期时间我只想提取时间
例如:2015-04-05 2:14:00只提取2:14:00
并将其与具有相同格式的特定范围进行比较。
我尝试了什么:
hi all,
i have visual studio winform c#
i want to compare the time from DateTime in hh:mm format in a specific range.
but it is not working
in my source code below the range is [start_time ,End_time].
In other words, from the datetime i want to extract the time only
e.g: 2015-04-05 2:14:00 extract only 2:14:00
and compare it with a specific range that has also the same format.
What I have tried:
DateTime current_time = DateTime.Now;
var End_time=current_time.ToString("hh:mm"); //End_time
var start_time = current_time.AddHours(-2).ToString("hh:mm");//start_time
DataTable dchild= new DataTable();
string query=SELECT DATE_FORMAT( date_created, '%h:%i:%s' ) time_created from table ;
adap_child = new MySqlDataAdapter(query, strconnection);
adap_child.Fill(dchild);
foreach (DataRow items in dchild.Rows)
{
var date_to_be_compared = (int)items["time_created"];
if(time_to_compared >=start_time && date_to_be_compared<=End_time)//error appears here
{
//code
}
else
{
//code
}
}
推荐答案
将从SELECT
返回的内容更改为DATETIME
实际存储在数据库中的值。然后得到TimeOfDay
部分和在其他地方使用它!
尝试像:
Change what you get back from theSELECT
to be theDATETIME
value that is actually stored in the DB. Then get theTimeOfDay
part and use that everywhere else!
Try something like:
DateTime current_time = DateTime.Now;
TimeSpan End_time=current_time.TimeOfDay; //End_time
TimeSpan start_time = End_time.SubtractHours(-2);//start_time
DataTable dchild= new DataTable();
string query = "SELECT date_created FROM table";
adap_child = new MySqlDataAdapter(query, strconnection);
adap_child.Fill(dchild);
foreach (DataRow items in dchild.Rows)
{
TimeSpan time_to_be_compared = ((DateTime)items["date_created"]).TimeOfDay;
if (start_time <= time_to_be_compared && time_to_be_compared <= End_time)
{
//code
}
else
{
//code
}
}
你可以得到时间作为TimeSpan对象
You can get the time as a TimeSpan object
DateTime current_time = DateTime.Now;
DateTime date_to_be_compared = DateTime.ParseExact("12 Aug 2014 13:45:22", "dd MMM yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
TimeSpan ts_current = current_time.TimeOfDay;
TimeSpan ts_compare = date_to_be_compared.TimeOfDay;
if (ts_current > ts_compare)
{
System.Diagnostics.Debug.WriteLine("Current time is after compare time");
}
else
{
System.Diagnostics.Debug.WriteLine("Current time is not after compare time");
}
这篇关于如何比较C#中hh:mm:ss格式的日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文