c# - 如何从日期时间中减去一年零一天?

标签 c# datetime

我看到类似 this 的答案但是如何在此之后添加 1 天?就像 2 年前和 1 天。

var myDate = DateTime.Now;
var newDate = myDate.AddYears(-2);
var NewExpiryDate = myDate.AddDays(-1);
var NewFinalDate = ?

最佳答案

你做错了什么:

myDate 将是当前日期,然后您将 -2 年添加到当前日期并分配给 newDate。这不会更新 myDate 它仍然是当前日期,因此您需要将 -1 天添加到 newDate 以获得所需的输出。您可以像这样使用更简单的方法:

var newDate = myDate.AddYears(-2).AddDays(-1);

Note : The date Functions .AddYears() will not alter the source, it will return a new DateTime that adds the specified number of years to the value of this instance. As Soner said, DateTime is an immutable type Which means is an object whose state cannot be modified after it is created.

关于c# - 如何从日期时间中减去一年零一天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37605674/

相关文章:

c# - 我的数据绑定(bind)怎么会写出 Length 属性?

c# - Entity Framework Core 中 TimeSpan 的总和

c# - 替换 xml 元素

powershell - 尝试使用 ParseExact 将字符串转换为日期时间

c# - DateTime.TryParse 问题,日期由 a.m 而不是 am 组成

python - 从 apache/nginx 用户 id cookie 中提取日期

java - 日期格式化程序未正确格式化日期

c# - 如何使用BMG(BOOTSTRAPPER MANIFEST GENERATOR)工具的 "File Check"选项来检查系统上是否已经安装了preRequisite?

c# - resx 文件未部署

javascript - 如何在 javascript/Node.js 中获取时间?