Adding Time

dgoss

Member
Licensed User
Longtime User
I have searched and searched but don't seem to get anywhere. All i'm after doing is to add X number of hours/minutes to current datetime to give a start date and time.
i.e> 26/04/2013 17:30
add 45Hrs
start date and time = 28/04/2013 14:30
It looks simple enough to do but i really am struggling to get my head into it:sign0104:
 

dgoss

Member
Licensed User
Longtime User
thx erel. Had a look at dateutils. Sorry to say but i must admit i of a look of boy lost in the woods about me.:sign0085:Any pointers will greatly appreciated as i am new to this.:sign0013:
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
I built this function that calculates a new date and time after a certain number of hours and minutes were added to or subtracted from a given date and time. I tested it and it seems to work correctly forward and backward. Hopefully, Erel can check it out and give his blessings:
B4X:
Msgbox(NewDateTime("26/04/2013", "17:30",45,0),"")  'returns 28/04/2013 14:30
Msgbox(NewDateTime("26/04/2013", "17:30",-45,0),"")  'returns 24/04/2013 20:30

Sub NewDateTime(StartDate As String, StartTime As String, HrsToAdd As Int, MnsToAdd As Int ) As String
   Dim OrigDateFormat,OrigTimeFormat As String
   Dim NewT As Long
   Dim D As Int 
   If HrsToAdd > 0 Then
      D=Floor(HrsToAdd/24)
   Else
      D=Ceil(HrsToAdd/24)
   End If
   Dim H As Int=HrsToAdd Mod 24
   OrigDateFormat=DateTime.Dateformat   'store original date format
   OrigTimeFormat=DateTime.TimeFormat   'store original time format
   DateTime.DateFormat="dd/MM/yyyy"
   DateTime.TimeFormat="HH:mm"
   NewT=DateTime.Add(DateTime.DateTimeParse(StartDate, StartTime),0,0,D) 
   NewT=NewT+ H*DateTime.TicksPerHour + MnsToAdd*DateTime.TicksPerMinute 'add the ticks for the hours and mns added
   Return DateTime.Date(NewT) & " " & DateTime.Time(NewT)
   DateTime.Dateformat=OrigDateFormat  'Revert back to original date format
   DateTime.Timeformat=OrigTimeFormat  'Revert back to original time format
End Sub
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
@Erel: Your code works well. It yields the same result as my function does. The only problem is: Every time you need a time or date calculation you have to add the code module (extra baggage). Perhaps consider embedding it in a future core function library.
 
Upvote 0

dgoss

Member
Licensed User
Longtime User
Sorry took so long to reply but i'm doing this on the road and internet is a bit sketchy at best of times.
Thx Mahares will have a look at your code but i think i'l go with dateutils now that i know how to use properly. many thx to Erel for pointing me in the right direction.
 
Upvote 0
Top