如何从 Date 对象中减去月份?

发布于 2024-08-19 17:44:25 字数 209 浏览 4 评论 0原文

如何从 VB.NET 中的日期对象中减去月份?

我已经尝试过:

Today.AddMonths(-1)

但是,鉴于今天是 2010 年 1 月 1 日,我得到的结果是 2010 年 12 月 1 日。我想要的答案是 2009 年 12 月 1 日。

在 .NET 框架中是否有一种方便的方法来执行此操作?

How do I subtract a month from a date object in VB.NET?

I have tried:

Today.AddMonths(-1)

However, given that Today is 01-Jan-2010, the result I get is 01-Dec-2010. The answer I want is 01-Dec-2009.

Is there a convenient way of doing this within the .NET framework?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

甜味拾荒者 2024-08-26 17:44:25

实际上,您必须将 Today 传输到一个变量中,并让该赋值在那里起作用。以下代码将产生您期望的结果(我刚刚验证了它,因为您的帖子让我三思而后行)。

Dim dt As DateTime = Date.Today
dt = dt.AddMonths(-2)

Dim x As String = dt.ToString()

You actually have to transport Today into a variable and let that assignment work there. The following code will produce the result you expect (I just verified it because your post made me think twice).

Dim dt As DateTime = Date.Today
dt = dt.AddMonths(-2)

Dim x As String = dt.ToString()
撩起发的微风 2024-08-26 17:44:25

这很好用,您需要记住 DateTime 是不可变的。

Dim d As DateTime
d = New DateTime(2010, 1, 1)
d = d.AddMonths(-1)

查看日期时间结构

对实例的计算
日期时间,例如加或减,
不修改的值
实例。相反,计算
返回 DateTime 的新实例
其值是结果
计算。

This works fine, you need to remember that the DateTime is imutable.

Dim d As DateTime
d = New DateTime(2010, 1, 1)
d = d.AddMonths(-1)

Have a look at DateTime Structure

A calculation on an instance of
DateTime, such as Add or Subtract,
does not modify the value of the
instance. Instead, the calculation
returns a new instance of DateTime
whose value is the result of the
calculation.

久光 2024-08-26 17:44:25
Dim d As DateTime = #1/1/2010#
d = d.AddMonths(-1)
Dim d As DateTime = #1/1/2010#
d = d.AddMonths(-1)
缪败 2024-08-26 17:44:25

我已经使用了以下内容并且有效。

Dim dtToday As DateTime = Date.Today
dtToday = dtToday.AddMonths(-2)

I have used the following and it works.

Dim dtToday As DateTime = Date.Today
dtToday = dtToday.AddMonths(-2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文