I am writing a custom component that allows users to choose a date from the calendar using JAVA SDK. I want to set a day as the first day of the week(e.g. MONDAY), which would then display the calendar with that day as the first day of the week(the first column of Calendar will be that day which was set).
In Android, we have setFirstDayOfWeek(int firstDayOfWeek)
method in DatePicker which does that for us.
What is the alternative for the above in DatePicker
of Harmony OS?
Regards, Subham
Currently, there have no directly apis interface to implemente that, but you can use the tool class code to implement this. like following:
public static LocalDateTime getMondayForThisWeek(LocalDate localDate) {
LocalDateTime monday = LocalDateTime.of(localDate, LocalTime.MIN).with(DayOfWeek.MONDAY);
return monday;
}
Reference Code:
Core code of Tool class:
public class LocalDateTimeUtil {
...
/***
* constructor method
*/
private LocalDateTimeUtil() {
}
/**
* Obtains the date of the Monday of the week to which the specified date belongs.
*
* @param localDate Time
* @return LocalDateTime
*/
public static LocalDateTime getMondayForThisWeek(LocalDate localDate) {
LocalDateTime monday = LocalDateTime.of(localDate, LocalTime.MIN).with(DayOfWeek.MONDAY);
return monday;
}
/**
* Obtains the date of the Sunday of the week to which the specified date belongs.
*
* @param localDate Time
* @return LocalDateTime
*/
public static LocalDateTime getSundayForThisWeek(LocalDate localDate) {
LocalDateTime sunday = LocalDateTime.of(localDate, LocalTime.MIN).with(DayOfWeek.SUNDAY);
return sunday;
}
...
}
XML file layout:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical"
>
<DatePicker
ohos:id="$+id:data_picker"
ohos:height="match_content"
ohos:width="match_parent"
ohos:background_element="#C89FDEFF"
/>
</DirectionalLayout>
Codes in AbilitySlice
:
public class MainAbilitySlice extends AbilitySlice {
private DatePicker datePicker;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
initView();
}
private void initView() {
if (findComponentById(ResourceTable.Id_data_picker) instanceof DatePicker) {
datePicker = (DatePicker) findComponentById(ResourceTable.Id_data_picker);
}
if (datePicker != null) {
// If you select Monday or Sunday as the first day of a week, select the corresponding method. This example selects Monday as the first day of the week
LocalDateTime mondayForThisWeek = LocalDateTimeUtil.getMondayForThisWeek(LocalDate.now());
datePicker.updateDate(mondayForThisWeek.getYear(), mondayForThisWeek.getMonth().getValue(), mondayForThisWeek.getDayOfMonth());
}
}
}