我想要做的是:
我正在尝试按当前小时显示xml文件中的电视节目表。例如..时间现在是下午2点,我想在这个时间显示来自所有频道的所有列表。
下面获取当前日期,并将其与XMl文件进行匹配,并显示所有匹配项。我想对当前小时执行相同的操作。
如果我将方法更改为下面,我会得到这个错误:
错误1运算符“==”不能应用于“System.DateTime”和“int”类型的操作数
bool MyDateCheckingMethod(string dateString)
{
DateTime otherDate = DateTime.ParseExact(dateString, "yyyyMMddHHmmss K", null);
// Is this today (ignoring time)?
return otherDate.Date == DateTime.Now.Hour;
}这是我目前正在使用的显示日期,它工作得很好。
bool MyDateCheckingMethod(string dateString)
{
DateTime otherDate = DateTime.ParseExact(dateString, "yyyyMMddHHmmss K", null);
// Is this today (ignoring time)?
return otherDate.Date == DateTime.Now.Date;
}下面是更多的代码,让它更清晰一些。
void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
var r = XDocument.Parse(e.Result);
listBox2.ItemsSource = from tv in r.Root.Descendants("programme")
where tv.Attribute("channel").Value == "1200"
where MyDateCheckingMethod(tv.Attribute("start").Value)
let channelE1 = tv.Attribute("channel")
let startE1 = tv.Attribute("start")
let nameEl = tv.Element("title")
orderby tv.Attribute("start").Value ascending
let urlEl = tv.Element("desc")
select new TV1guide
{
DisplayName = nameEl == null ? null : nameEl.Value,
ChannelName = channelE1 == null ? null : channelE1.Value,
ChannelURL = urlEl == null ? null : urlEl.Value,
StartTime = startE1 == null ? (DateTime?)null : DateTime.ParseExact(startE1.Value, "yyyyMMddHHmmss zzz", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AssumeLocal),
};发布于 2011-08-14 10:36:01
您收到的错误是因为您试图将日期和时间与一个小时进行比较,而不仅仅是比较小时。您不能直接将int与DateTime进行比较。
下面是一些可以工作的代码:
bool MyDateCheckingMethod(string dateString)
{
DateTime otherDate = DateTime.ParseExact(dateString, "yyyyMMddHHmmss K", null);
DateTime now = DateTime.Now;
// Is this the current date and hour?
return otherDate.Date == now.Date
&& otherDate.Hour == now.Hour;
}如果您只想在一小时内执行检查,并且不关心是否匹配不同的日期,则可以将代码更改为:
bool MyDateCheckingMethod(string dateString)
{
DateTime otherDate = DateTime.ParseExact(dateString, "yyyyMMddHHmmss K", null);
// Is this the current hour - regardless of date?
return otherDate.Hour == DateTime.Now.Hour;
}对于将来出现的类似问题,我建议您使用look up the docs on the DateTime class来准确地确定每个属性返回的内容。
日期和时间处理通常比您最初想象的要复杂,并且需要一些关于.Net框架如何处理时间的先验知识。查看文档并在单独的scratch项目中做一些实验通常是有帮助的。
发布于 2011-08-14 10:34:40
这应该是可行的:
return otherDate.Hour == DateTime.Now.Hour;然而,这并不一定意味着同一天,所以你可能正在寻找:
return otherDate.Date == DateTime.Now.Date &&
otherDate.Hour == DateTime.Now.Hour;https://stackoverflow.com/questions/7054582
复制相似问题