Results 1 to 3 of 3

Thread: Date - Date = TimeSpan?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2005
    Location
    Maine, USA
    Posts
    277

    Date - Date = TimeSpan?

    I'm subtracting one date from another, it appears to output the result as a TimeSpan, which I can't format with the Format() function.
    Any ideas on how to get around this?
    <deis> I turn on god mode when I program
    <deis> I just call it .NET


    If my post was helpful, please Rate it

  2. #2
    PowerPoster
    Join Date
    Aug 2005
    Location
    College Station, TX
    Posts
    4,521

    Re: Date - Date = TimeSpan?

    how are you trying to format it in?? It is a span of time, not a particular "date", so you cant format it into a "date". What are you trying to get?

    There are different methods of timespan, like days, hours, minutes, etc...
    Code:
            'shows total days between the two dates
            Dim MyDate As Date = Date.Now
            Dim MyFutureDate As Date = Date.Parse("12/25/2007")
            Dim Difference As TimeSpan = MyFutureDate.Subtract(MyDate)
            MessageBox.Show(Difference.TotalDays & ":TotalDays")
    You also might want to look into the DateDiff function (in the Microsoft.VisualBasic namespace) if you want years, months, etc...

    For an example on DateDiff, see post #8 in this thread:
    http://www.vbforums.com/showthread.php?t=385300
    Last edited by gigemboy; Feb 5th, 2006 at 05:19 PM.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Date - Date = TimeSpan?

    I'd suggest using the .ToString method rather than Format in general, but neither work for a TimeSpan anyway. Note that the largest unit a TimeSpan will give you is days, because months and years are dependent on the start and end of the period, which the TimeSpan doesn't know about. You can do something like this:
    VB Code:
    1. Dim d1 As Date
    2. Dim d2 As Date
    3. Dim t As TimeSpan = d2.Subtract(d1)
    4.  
    5. MessageBox.Show(String.Format("{0}:{1:d2}:{2:d2}:{3:d2}", t.Days, t.Hours, t.Minutes, t.Seconds))
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width