How to obtain week start and enddate from a date

rwblinn

Well-Known Member
Licensed User
Longtime User
Hi All,

has someone a hint how to obtain the week start and enddate from a date given?
Example:
Date = 24 May 2013 (Fri)
Week Startdate = 20 May 2013 (Mon)
Week Enddate = 26 May 2013 (Sun)

Want to use the start and enddate to select data from a SQLite DB and show the cursor results in a Listview.

Appreciated,
Rob
 

Mahares

Expert
Licensed User
Longtime User
This is how I would do it, unless someone has a more elegant way:

B4X:
Dim SD, ED As String   'in global
Dim OrigDateFormat As String


B4X:
OrigDateFormat=DateTime.Dateformat  'store original date format
DateTime.DateFormat="dd MMM yyyy"
Dim ThisDate As String ="24 May 2013"
Select DateTime.GetDayOfWeek(DateTime.DateParse(ThisDate)) 
Case 1  'Sunday
  SE(ThisDate,-6)
Case 2  'Monday
  SE(ThisDate,0)
Case 3 'Tuesday
   SE(ThisDate,-1)
Case 4 'Wednesday
   SE(ThisDate,-2)
Case 5 'Thursday
   SE(ThisDate,-3)
Case 6 'Friday
   SE(ThisDate,-4)
Case 7 'Saturday
   SE(ThisDate,-5)
End Select
DateTime.Dateformat=OrigDateFormat  'Revert back to original date format
B4X:
Sub SE(MyDate As String,x As Int)
   SD= DateTime.Date(DateTime.Add(DateTime.DateParse(MyDate),0,0,x))
   ED= DateTime.Date(DateTime.Add(DateTime.DateParse(SD),0,0,6))
   Msgbox("Monday's date is: " & SD & "  Sunday's date is: " & ED,"")
End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here:
B4X:
Sub WeekStartAndEnd(d As Long) As Long()
   Dim firstDay As Int = 2 'Monday
   Dim day As Int = DateTime.GetDayOfWeek(d)
   Dim start As Long = DateTime.Add(d, 0, 0, -1 * (day - firstDay))
   Return Array As Long(start, DateTime.Add(start, 0, 0, 7) - 1)
End Sub

Example:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim startAndEnd() As Long = WeekStartAndEnd(DateTime.DateParse("05/24/2013"))
   Log(DateUtils.TicksToString(startAndEnd(0)))
   Log(DateUtils.TicksToString(startAndEnd(1)))
End Sub
 
Upvote 0

rwblinn

Well-Known Member
Licensed User
Longtime User
Week Start End Function

Thank You for the great solutions given.

Pls consider to add this function to the DateUtils library.

Rob
 
Upvote 0

Eumel

Active Member
Licensed User
Longtime User
B4X:
Sub WeekStartAndEnd(d As Long) As Long()
  Dim firstDay As Int = 2 'Monday
  Dim day As Int = DateTime.GetDayOfWeek(d)
  If day = 1 Then day = day + 7  'this line added
  Dim start As Long = DateTime.Add(d, 0, 0, -1 * (day - firstDay))
  Return Array As Long(start, DateTime.Add(start, 0, 0, 7) - 1)
End Sub

I had to add the line above, because Sunday as 1, and Monday as 2 so day-firstday = -1
and Datetime.Add results as Datetime.Add(d,0,0,-1*(-1) will be Tomorrow as -1*-1 = 1
 
Upvote 0
Top