在每月的第一天分配变量

时间:2013-04-15 19:20:28

标签: c# vb.net datetime

我有一个程序,我想在“月的第一天”分配一个变量。以下是我到目前为止的情况:

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”。这将根据它运行的那天明显改变...

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

您可以从当前日期减去当月的当前日期。然后添加1以获得第一天:

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

答案 2 :(得分:0)

尝试如下,它会帮助你...

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