find Sunday of week

tremara1

Active Member
Licensed User
Longtime User
Hi, I have been trying to get this right all day....HELP. What I need to is select a date and then find the date of the previous Sunday. Could someone put me on the right path on how to do this....Thanks.
 

lagore

Active Member
Licensed User
Longtime User
that should be easy
B4X:
Dim lastsunday As String
   Dim somedate As Long
   Dim dayssincesunday As Int
   somedate = DateTime.Now
   dayssincesunday = DateTime.GetDayOfWeek(somedate)      'returns an int 1 is sunday 2 monday etc
   lastsunday = DateTime.Date(DateTime.Add(somedate,0,0, (dayssincesunday - 1) * -1))      'we subtract 1 as sunday is 1 based not zero based
this returns the date as a string, leave out 'DateTime.Date' and you will have a long
 
Upvote 0

keirS

Well-Known Member
Licensed User
Longtime User
Your code wouldn't work if the selected date was a Sunday. It would return the selected date and not the previous Sunday.
B4X:
LastSunday = SomeDate - (DateTime.GetDayOfWeek(SomeDate) * DateTime.TicksPerDay) + DateTime.TicksPerDay
   If SomeDate = LastSunday Then
      LastSunday = LastSunday - (7 * DateTime.TicksPerDay)
     
   End If
 
Upvote 0

tremara1

Active Member
Licensed User
Longtime User
thanks again

I knew there would be a better solution than the one I was attempting. Always learning.......
 
Upvote 0
Top