比较 DateTime 对象
目标 - 找出哪个日期时间更新。
我可以用这段代码解决这个问题:
DateTime dt1 = new DateTime(...); //let's say it was created on 1/1/2000
DateTime dt2 = new DateTime(...); //let's say it was create on 1/1/2011
if (dt2.ToBinary() > dt1.ToBinary()) {
print dt2 is newer than dt1 }
我可以简单地将 DateTime 对象转换为二进制,然后假设较大的对象更新吗?
谢谢, 凯文
Goal - find out which DateTime is more recent.
Can I figure this out with this code:
DateTime dt1 = new DateTime(...); //let's say it was created on 1/1/2000
DateTime dt2 = new DateTime(...); //let's say it was create on 1/1/2011
if (dt2.ToBinary() > dt1.ToBinary()) {
print dt2 is newer than dt1 }
Can I simply convert the DateTime objects to binary, then presume that the larger one is more recent?
Thanks,
Kevin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
应该足够了,因为 DateTime 会重载比较运算符。
should be enough as DateTime overloads the comparison operators.
您通常可以做得更好:
棘手的一点是考虑时区...您可以使用,
但前提是您知道任何“本地”时间确实是系统时区的本地时间。
.NET 中的日期和时间有点混乱:(
You can usually do better than that:
The tricky bit is taking time zones into consideration... you can potentially use
but only if you know that any "local" times really are local in the system's time zone.
Dates and times in .NET are a bit of a mess :(
不,你不能。
ToBinary()
返回还存储时区信息的内部格式。相反,您可以直接比较
DateTime
:DateTime
会重载比较运算符。您可以比较
Ticks
属性,但您不必费心。No, you can't.
ToBinary()
returns an internal format that also stores time zone info.Instead, you can compare the
DateTime
s directly:DateTime
overloads the comparison operators.You could compare the
Ticks
property, but you shouldn't bother.您可以使用 Datetime.Compare
-1 = 第一个日期小于第二个日期
0 = 第一个日期等于第二个日期
1 = 第一个日期大于第二个日期
You can use Datetime.Compare
-1 = The Fisrt Date is Less than the Second
0 = The First Date is equal than the Second
1 = The First Date is Greater than the Second
DateTime
对象本身是可比较的,因此也可以工作。
此外
DateTime
实现了IComparable
接口,因此您可以执行以下操作:编辑:这会忽略时区、当地时间等...
DateTime
objects are comparable themselves, sowill work too.
In addition
DateTime
implements theIComparable<DateTime>
interface, so you can do:EDIT: This ignores time zones, local times, etc...