如何从具有未来日期的变量中减去1个月? [英] How do I subtract 1 month from my variable that has a future date?
问题描述
我想要做的是使用SQL获取上个月的报告。因此,如果查询今天(2018年5月7日)运行,我应该得到上个月的报告,即从4月1日到4月30日。
在我的vb.net代码中查询看起来像这样strSQL = GetSql (dtmStartDateTime,dtmEndDateTime)。
对于测试,我使用的是strALTCURDATE字符串变量中的未来日期(06/01/2018)。
如何将此变量用作dtmStartDateTime,然后从中减去1个月并将其用作dtmEndDateTime?
我还需要将strALTCURDATE转换为日期。
所以dtmStartDateTime应该是dtmStartDateTime = strALTCURDATE而dtmEndDateTime应该是dtmStartDateTime - 1月份是5月31日。
有人可以帮我吗?
我的dtmEndDateTime显示为5/6/2018,但我希望它显示为5/31/2018。
我尝试了什么:
我试过了
dtmStartDateTime = DateTime.Parse(strALTCURDATE)
dtmEndDateTime = DateTime(AddInterval.Month,-1,dtmStartDateTime)
strSQL = GetSql(dtmStartDateTime,dtmEndDateTime)
What I am trying to do is using SQL get last month's report. So if the query runs today (May 07 2018), I should get a report for last month i.e. from April 1 to April 30.
In my vb.net code the query looks like this strSQL = GetSql(dtmStartDateTime, dtmEndDateTime).
For testing I am using a future date (06/01/2018) which is in strALTCURDATE string variable.
How do I use this variable as dtmStartDateTime and then subtract 1 month from it and use that as dtmEndDateTime?
I also need to convert strALTCURDATE to a date.
So dtmStartDateTime should be dtmStartDateTime = strALTCURDATE and dtmEndDateTime should be dtmStartDateTime - 1 month which is May 31.
Can someone help me with this please?
My dtmEndDateTime is showing as 5/6/2018 but I would like it to show as 5/31/2018.
What I have tried:
I have tried
dtmStartDateTime = DateTime.Parse(strALTCURDATE)
dtmEndDateTime = DateTime(AddInterval.Month, -1, dtmStartDateTime)
strSQL = GetSql(dtmStartDateTime, dtmEndDateTime)
推荐答案
检查这个:
Check this:
Dim tdate As DateTime = DateTime.Today
Dim sdate As DateTime = New DateTime(tdate.Year, tdate.Month-1, 1)
Dim edate As DateTime = sdate.AddMonths(1).AddDays(-1)
Console.WriteLine("Today is: '{0}'", tdate.ToString("yyyy-MM-dd"))
Console.WriteLine("Report date range is: '{0}' and '{1}'", sdate.ToString("yyyy-MM-dd"), edate.ToString("yyyy-MM-dd"))
结果:
Result:
Today is: '2018-05-07'
Report date range is: '2018-04-01' and '2018-04-30'
你可以这样做:
You could do it like this:
Dim curDateTime = DateTime.Parse(strALTCURDATE)
Dim prevMonth = curDateTime.AddMonths(-1)
Dim firstOfPrevMonth = New Date(prevMonth.Year, prevMonth.Month, 1)
Dim firstOfCurMonth = New Date(curDateTime.Year, curDateTime.Month, 1)
Dim lastOfPrevMonth = firstOfCurMonth.AddDays(-1)
firstOfPrevMonth将是您的开始日期,lastOfPrevMonth将是您的结束日期。
"firstOfPrevMonth" will be your start date and "lastOfPrevMonth" your end date.
这篇关于如何从具有未来日期的变量中减去1个月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!