How to add time

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chaitukdr
    New Member
    • Mar 2010
    • 2

    How to add time

    suppose string x=10h.10m
    string y=10h.10m
    how to add x and y by converting them to double.

    because on converting x to double like

    double a= convert.todoubl e(x)
    it gives result 10.1 which represents 10h.1m

    how to convert so that I get result as 10h.10m

    h*-Hours
    m*- Minutes
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Since you are working with time I recommend that you use the DateTime structure instead of a Double.

    The reason is because of how doubles work verses how time values work.

    Here's what happens when you add Doubles:
    0.6 + 0.1 = 0.7

    However, if these were times that you were adding together you should have:
    0.6 + 0.1 = 1.0

    See the difference?


    If you use the DateTime structure instead of a Double then your addition will be correct.

    The important thing to know about adding DateTime structures is that:
    Originally posted by msdn
    A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.
    Check out the article I linked you to about the DateTime structure so that you have a good idea of how to use it to achieve what you're looking to do.

    -Frinny

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      It's also easier to start with something closer in format to your need.

      suppose string x=10h.10m

      Where is this string coming from? Why is it formated at 10h.10m?
      Can this be made to be entered as time, such as 10:10 ? Maybe using a MaskedTextBox? If you can use a DateTimePicker that would be ideal because you then are entering in a DateTimeObject and eliminating the conversion process altogether.

      If you process the string "10h.10m" into a recognizable time format then you can use DateTimeParse to turn it into a DateTime object. You can replace "h." with ":" and replace "m" with string.empty to create "10:10"

      Comment

      Working...