以每月的第一天为变量赋值

本文关键字:变量 赋值 第一天 | 更新日期: 2023-09-27 18:09:25

我有一个程序,我想给一个变量赋值为"每月的第一天"。以下是目前为止的内容:

Dim dtToday As DateTime = DateTime.Today 'Sets todays date (04/15/13)
Dim dtYesterday As DateTime = DateTime.Today.AddDays(-1) 'Sets Yesterdays Date (04/14/13)

接下来我想定义"dtFirstOfMonth"。它会将月的第一天设置为"04/01/13",这显然会根据它运行的日期而改变…

以每月的第一天为变量赋值

Dim dtFirstOfMonth as DateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)

可以用当前日期减去当前日期。然后加上1,得到第一天:

var firstDayOfMonth = DateTime.Today.AddDays(1 - DateTime.Today.Day);

试试下面的方法,它会帮助你…

 Dim dtToday As DateTime = DateTime.Today
 Dim dtFrom As DateTime
 dtFrom = dtToday.AddDays(-(dtToday.Day - 1))