如何更改日期时间? [英] How to change time in datetime?

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

问题描述

如何在 DateTime 变量中单独更改时间?

  DateTime s = some datetime; 

我需要更改 s

解决方案

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

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

s 现在将是同一个日期,但是上午10时30分。



请注意, DateTime 忽略夏令时转换,代表天真格里高利时代方向(请参阅 <$中的注释部分c $ c> DateTime docs )。唯一的例外是 .Now .Today :它们检索当前系统时间,反映这些事件的发生。 / p>

这是促使我启动 Noda时间项目,现在已经准备就绪。它的 ZonedDateTime 类型被感知将其链接到 tz 数据库条目


How can I change the time alone in DateTime variable?

DateTime s = some datetime;

I need to the change only the time part in s.

解决方案

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 will now be the same date, but at 10.30am.

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.

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.

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

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