如何更改 DateTime 中的时间? [英] How to change time in DateTime?

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

问题描述

如何仅更改 DateTime 变量s"中的时间?

How can I change only the time in my DateTime variable "s"?

DateTime s = some datetime;

推荐答案

您不能更改 DateTime 值 - 它是不可变的.但是,您可以将变量更改为具有新值.更改时间的最简单方法是使用相关时间创建一个 TimeSpan,并使用 DateTime.Date 属性:

You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.Date property:

DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;

s 现在将是相同的日期,但在上午 10 点 30 分.

s will now be the same date, but at 10.30am.

请注意,DateTime 不考虑夏令时转换,代表两个方向的原始"格里高利时间(请参阅 DateTime 文档).唯一的例外是 .Now.Today:它们检索反映这些事件发生时的当前系统时间.

Note that DateTime disregards daylight saving time transitions, representing "naive" Gregorian time in both directions (see Remarks section in the DateTime docs). The only exceptions are .Now and .Today: they retrieve current system time which reflects these events as they occur.

正是这种原因促使我开始了 Noda Time 项目,该项目现已投入生产.它的 ZonedDateTime 类型通过将其链接到 code>tz 数据库入口.

This is the kind of thing which motivated me to start the Noda Time project, which is now production-ready. Its ZonedDateTime type is made "aware" by linking it to a tz database entry.

这篇关于如何更改 DateTime 中的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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