From 3640be47c3b21229c55a91b421aec3bbebd425fd Mon Sep 17 00:00:00 2001 From: Tatu Lund Date: Fri, 3 Jul 2020 13:17:34 +0300 Subject: Add support for "ww" in date format (#12037) Calculate number of the week in the year based on Date. Note, support for "ww" is missing from GWT DateTimeFormat and java.util.Calendar is not supported in GWT, hence DIY method is needed. Fixes: #10603 --- .../java/com/vaadin/client/DateTimeService.java | 49 ++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'client/src') diff --git a/client/src/main/java/com/vaadin/client/DateTimeService.java b/client/src/main/java/com/vaadin/client/DateTimeService.java index 00606a25c1..72d51edcae 100644 --- a/client/src/main/java/com/vaadin/client/DateTimeService.java +++ b/client/src/main/java/com/vaadin/client/DateTimeService.java @@ -39,6 +39,10 @@ public class DateTimeService { private static int[] maxDaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + private int[] yearDays = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, + 304, 334 }; + private int[] leapYearDays = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, + 305, 335}; private static final long MILLISECONDS_PER_DAY = 24 * 3600 * 1000; @@ -372,6 +376,10 @@ public class DateTimeService { * @since 8.2 */ public String formatDate(Date date, String formatStr, TimeZone timeZone) { + /* + * Format week numbers + */ + formatStr = formatWeekNumbers(date, formatStr); /* * Format month and day names separately when locale for the * DateTimeService is not the same as the browser locale @@ -388,6 +396,47 @@ public class DateTimeService { return result; } + /* + * Calculate number of the week in the year based on Date + * Note, support for "ww" is missing GWT DateTimeFormat + * and java.util.Calendar is not supported in GWT + * Hence DIY method needed + */ + private String getWeek(Date date) { + int year = date.getYear()+1900; + int month = date.getMonth(); + int day = date.getDate()+1; + int weekDay = date.getDay(); + if (weekDay == 6) { + weekDay = 0; + } else { + weekDay = weekDay - 1; + } + boolean leap = false; + if (((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0))) { + leap = true; + } + int week; + if (leap) { + week = countWeek(leapYearDays, month, day, weekDay); + } else { + week = countWeek(yearDays, month, day, weekDay); + } + return ""+week; + } + + private int countWeek(int[] days, int month, int day, int weekDay) { + return ((days[month] + day) - (weekDay + 7) % 7 + 7) / 7; + } + + private String formatWeekNumbers(Date date, String formatStr) { + if (formatStr.contains("ww")) { + String weekNumber = getWeek(date); + formatStr = formatStr.replaceAll("ww", weekNumber); + } + return formatStr; + } + private String formatDayNames(Date date, String formatStr) { if (formatStr.contains("EEEE")) { String dayName = getDay(date.getDay()); -- cgit v1.2.3