在C#中处理时间的简单方法? [英] Simple way to handle time in C#?

查看:76
本文介绍了在C#中处理时间的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的方法是

DateTime startHour = new DateTime(1900,1,1,12,25,43);
DateTime endHour = new DateTime(1900,1,1,13,45,32);

// I need to, say, know if a complete DateTime instance 
// is later than startHour plus 15 minutes

DateTime now = DateTime.Now();

startHour = startHour.addMinutes(15);

if (now.CompareTo(new DateTime(now.Year, now.Month, now.Day, startHour.Hour, 
                    startHour.Minute, startHour.Second)) > 0) 
{
    //I can do something now
}

这非常麻烦,甚至容易失败。就我所知,TimeSpans并不是一个解决方案,因为它们代表跨度并且不受24小时限制的约束(TimeSpan为56小时34分钟有效。)

This is very cumbersome and even failure prone. TimeSpans are not a solution as far as I can see, because they represent spans and aren't bound by the 24 hours limit (a TimeSpan of 56 hours 34 minutes is valid.)

这种类型的计算的首选方法是什么?

What's the preferred approach for this type of calculations?

我想念什么?

编辑:我要进行的计算是比较完整DateTime的方法实例,其中一个小时,分钟,第二个三元组代表一天中的实际时间,以及在这些三元组上进行操作的方式(加时,分秒)。

The calculations I'm after are ways to compare a complete DateTime instance with an hour, minute, second triplet representing an actual time of day and a way to operate over those triplets (add hours, minutes seconds).

编辑2:谢谢大家,我认为我现在掌握了DateTime API的要旨。 :)我唯一想念的是指定TimeSpan的方法,该TimeSpan仅应表示TimeOfDay,但这是次要的。

EDIT 2: Thanks everybody, I got the gist of the DateTime API now, I think. :) The only thing I miss is a means to specify a TimeSpan that should represent a TimeOfDay only, but that's minor.

推荐答案

尚不清楚您所说的大于startHour是什么意思...但是

It's not at all clear what you mean by "is greater than startHour"... but taking

TimeSpan startHour = new TimeSpan(12, 25, 43);
if (endHour.TimeOfDay > startHour)
{
    ...
}

...的工作非常简单。

... works pretty simply.

总而言之,请添加参数检查以确保您未为startHour指定值< 0或> 23小时,但这很容易。

By all means add argument checking to make sure that you don't specify a value for startHour which is < 0 or > 23 hours, but that's all pretty easy.

.NET的日期和时间API与Joda Time相比是相当原始的(即使在3.5中)-但在这种特殊情况下,我认为还不错。

.NET's date and time API is quite primitive (even in 3.5) compared with, say, Joda Time - but in this particular case I think it's not too bad.

这篇关于在C#中处理时间的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆