如何在上午12:00之前测试晚上8点有效?

时间:2013-04-14 08:54:18

标签: c# asp.net datetime utc

所有

我最近posted a question限制用户登录4小时,并获得了很好的反馈/答案。

但我遇到了让我难过的情景。

客户从第二天晚上8点到第二天凌晨12点登录 - 总共4小时。但是,我的代码是在时间过去的晚上8点,而不是在上午12:00之前的晚上8点。

如何让系统看到晚上8点到次日凌晨12点之前尚未过去的时间?

这是我的代码使用带有AM和PM的12小时时钟 - 不是UTC或24小时制:

var orderTime = Convert.ToDateTime(orderDate); // 8:00 PM
var expirationTime = orderTime.AddHours(4); // 12:00 AM of the next day

// timeRemaining should be 4 hours but is 0
// DateTime.Now is 8:00 PM of the current day
// so timeRemaining = 8:00 PM - 12:00 AM (should be 4 hours) 
var timeRemaining = expirationTime - DateTime.Now;

// should be greater than 0 since timeRemaining is actually 4 hours (8:00 PM up to 12:00 AM of next day)
// but fails seeing it as passed
if (timeRemaining < TimeSpan.Zero)                     
    Response.Redirect("TimedOut.aspx");

如何让此方案有效?也就是说,系统在下午8点之前看到的时间是在第二天中午12:00之前尚未过去的时间?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您的代码对我来说非常合适。我相信这是你在这里没有展示的一些代码或者其他一些愚蠢的原因。我正在使用此代码(以及它的许多变体)进行测试:

// force the date format to be 12hour like in US
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

DateTime start = DateTime.Parse("1/1/2013 7:00 PM").ToUniversalTime();
DateTime end = start.AddHours(5); // returns 1/2/2013 12:00:00 AM as it should

Console.WriteLine(end - start); // 05:00:00
Console.WriteLine((end - start) > TimeSpan.Zero); // True