为什么日期时间改变到16年前的1月1日不正确显示年份? [英] why datetime change to 1st Jan in 16 year ago does not show year part properly?

查看:143
本文介绍了为什么日期时间改变到16年前的1月1日不正确显示年份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将日期从今天的日期开始到1月16日的1日。我使用代码

i want to set the date to 1st of Jan 16 years ago from today's date. I used the code

DateTime dtm = new DateTime(DateTime.Today.Year, 1, 1);
dtm.AddYears(-16);
dtpDOB.Value = dtm;// assign value to date time picker

但它显示日期值为1/1/2014,为什么这不会在16年内设定年份?

but it shows the date value as 1/1/2014, why this does not set the year part back in 16 years?

谢谢

推荐答案

DateTime type是一个 struct 。因此,其属性是 immutable (它们不能被修改后的构造函数)。在C#中通过按值传递结构。

The DateTime type is a struct. Because of that, its properties are immutable (they can't be changed post-constructor). structs are passed by value in C#.

正如其他几个人所说,您需要重新分配价值。

Because of that, as a few other people have said, you need to reassign the value.

dtm = dtm.AddYears(-16);

这就像一个典型的字符串操作C#。当您调用 string.Replace(string,string)时,需要捕获该操作的返回值。对于LINQ-y IEnumerable< T> 操作也是如此。

It's just like a typical string operation in C#. When you call string.Replace(string, string), you need to capture the return value of the operation. The same is true for LINQ-y IEnumerable<T> operations.

虽然说,看起来像你最好是适当调用构造函数。

Although that said, it seems like you'd be better off to just call the constructor appropriately.

dtpDOB.Value = new DateTime(DateTime.Today.Year - 16, 1, 1);

这篇关于为什么日期时间改变到16年前的1月1日不正确显示年份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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