A reader recently asked how to determine the day of the week – Monday, Tuesday, Wednesday and so on, using MIT App Inventor code. Obtaining the day of the week is easy, although not obvious.
Using TimePicker and DatePicker
I previously posted a tutorial titled “Using TimePicker and DatePicker for entering time and data information“. Refer to that tutorial for basic information on the handling of time and data information in App Inventor.
Converting Time Instants into Different Formats
App Inventor has built-in functions to convert the date into different formats. However, the function to convert a calendar date into the day of the week is not in the DatePicker component, but in the Clock component.
To demonstrate, we use the original app from the TimePicker and DatePicker tutorial (you may download the sample code from the original tutorial page) and then we add two small bits of code to do identify the day of the week.
In the original sample code, the screen’s Initialize event handler displays the current date and time on screen. To that code, we add the block shown within the yellow rectangle, below:
“call Clock1.Now” returns a value called a time instant. The time instant contains both date and time in a special format: the format is not important to us as App Inventor provides routines to convert the time instant into common values like year or hours and minutes.
The Clock component has a method “call Clock1.WeekdayName” that extracts the date information and calculates the day of the week, returning a text string with values like “Sunday” or “Monday”.
In the original tutorial, the DatePicker is used to select a new calendar date (different than what ever the current date is). Once the data is selected with that user interface, the event “.AfterDateSet” is thrown. Within the AfterDateSet event handler, we extract the Year, Month, Day and also the “WeekdayName” name. To convert the date instant to a day of the week format, we use the WeekdayName method of the Clock component – easy but not obvious!
Converting a date or time instance into normal formats like Year, Month, Day or day of the week is easy when you use the appropriate conversion functions built in to the App Inventor components.
The weekday value conversion is a little odd in that its hidden in the Clock component. But once you find it, obtaining the day of the week is easy!