开发者

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

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 :)


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.


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


        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)


"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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜