VB.Net 2005, how can I subtract a date from the (current date minus 7 days) and produce a number of days?

淺唱寂寞╮ 提交于 2021-01-27 14:21:40

问题


I have a date in the future e.g. 13/10/2008 I need to subtract the current date (today is the 28/09/2010) minus 7 days, so thats 21/09/2010 minus 13/10/2008, which would equal erm, 720 something ?

But the current date won't always be 28/09/2010, obviously.

I need the code for this.

EDIT: When i said future I mean past :)


回答1:


Sub Main()
    Dim dt As DateTime = New DateTime(2008, 10, 13)
    ' be careful what you are subtracting from what
    ' the date you have is not in the future (year 2008)
    ' if the date is in the future: (dt.Subtract(DateTime.Now.AddDays(-7))).TotalDays
    ' or simply take the absolute value
    Dim days As Double = (DateTime.Now.AddDays(-7).Subtract(dt)).TotalDays
    Console.WriteLine(days)
End Sub

You will also notice that the TotalDays property is of type Double.




回答2:


13/10/2008 is not exactly in the future :)

Sorry for using C# code, but:

(dateInFuture - DateTime.Now.AddDays(-7)).TotalDays

Should work. Of course the other way around if you mean in the past:

(DateTime.Now.AddDays(-7) - dateInPast).TotalDays



回答3:


        Dim ValidDate As Date =cDate("Tuesday, December 31, 2013") 'A date in Future

        Dim date1 As New System.DateTime(ValidDate.Year, ValidDate.Month, ValidDate.Day)
        Dim date2 = Now

        Dim Diff1 As System.TimeSpan

        Diff1 = date1.Subtract(date2)

        Dim TotRemDays = (Int(Diff1.TotalDays))

        MsgBox(TotRemDays)



回答4:


"I need the code for this" seems a bit too much like "Plz give meh teh codez", and your "date in the future" seems a little bit in the past.

Anyway, you should investigate the relevant methods of the DateTime structure, in particular the Subtract method (both overloads, or in alternative its subtraction operator), and you should have a look at the TimeSpan structure too.

You could create a DateTime for the date of today, subtract a TimeSpan of 7 days to it, and then subtract such result to a DateTime representing your date in the future (or, if it is in the past, do the opposite). You'll get a TimeSpan representing the difference in time between the two dates, from which you can easily get the number of days using its Days property.

As other said, to do the first subtraction you can also use the AddDays method of the DateTime structure.



来源:https://stackoverflow.com/questions/3810872/vb-net-2005-how-can-i-subtract-a-date-from-the-current-date-minus-7-days-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!