You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DateTimeService.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client;
  17. import java.util.Date;
  18. import java.util.logging.Level;
  19. import java.util.logging.Logger;
  20. import com.google.gwt.i18n.client.LocaleInfo;
  21. import com.google.gwt.i18n.client.TimeZone;
  22. import com.google.gwt.i18n.shared.DateTimeFormat;
  23. import com.vaadin.shared.ui.datefield.DateResolution;
  24. /**
  25. * This class provides date/time parsing services to all components on the
  26. * client side.
  27. *
  28. * @author Vaadin Ltd.
  29. *
  30. */
  31. @SuppressWarnings("deprecation")
  32. public class DateTimeService {
  33. private String locale;
  34. private static int[] maxDaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
  35. 31, 30, 31 };
  36. /**
  37. * Creates a new date time service with the application default locale.
  38. */
  39. public DateTimeService() {
  40. locale = LocaleService.getDefaultLocale();
  41. }
  42. /**
  43. * Creates a new date time service with a given locale.
  44. *
  45. * @param locale
  46. * e.g. {@code fi}, {@code en}, etc.
  47. * @throws LocaleNotLoadedException
  48. */
  49. public DateTimeService(String locale) throws LocaleNotLoadedException {
  50. setLocale(locale);
  51. }
  52. public void setLocale(String locale) throws LocaleNotLoadedException {
  53. if (!LocaleService.getAvailableLocales().contains(locale)) {
  54. throw new LocaleNotLoadedException(locale);
  55. }
  56. this.locale = locale;
  57. }
  58. public String getLocale() {
  59. return locale;
  60. }
  61. public String getMonth(int month) {
  62. try {
  63. return LocaleService.getMonthNames(locale)[month];
  64. } catch (final LocaleNotLoadedException e) {
  65. getLogger().log(Level.SEVERE, "Error in getMonth", e);
  66. return null;
  67. }
  68. }
  69. public String getShortMonth(int month) {
  70. try {
  71. return LocaleService.getShortMonthNames(locale)[month];
  72. } catch (final LocaleNotLoadedException e) {
  73. getLogger().log(Level.SEVERE, "Error in getShortMonth", e);
  74. return null;
  75. }
  76. }
  77. public String getDay(int day) {
  78. try {
  79. return LocaleService.getDayNames(locale)[day];
  80. } catch (final LocaleNotLoadedException e) {
  81. getLogger().log(Level.SEVERE, "Error in getDay", e);
  82. return null;
  83. }
  84. }
  85. public String getShortDay(int day) {
  86. try {
  87. return LocaleService.getShortDayNames(locale)[day];
  88. } catch (final LocaleNotLoadedException e) {
  89. getLogger().log(Level.SEVERE, "Error in getShortDay", e);
  90. return null;
  91. }
  92. }
  93. public int getFirstDayOfWeek() {
  94. try {
  95. return LocaleService.getFirstDayOfWeek(locale);
  96. } catch (final LocaleNotLoadedException e) {
  97. getLogger().log(Level.SEVERE, "Error in getFirstDayOfWeek", e);
  98. return 0;
  99. }
  100. }
  101. public boolean isTwelveHourClock() {
  102. try {
  103. return LocaleService.isTwelveHourClock(locale);
  104. } catch (final LocaleNotLoadedException e) {
  105. getLogger().log(Level.SEVERE, "Error in isTwelveHourClock", e);
  106. return false;
  107. }
  108. }
  109. public String getClockDelimeter() {
  110. try {
  111. return LocaleService.getClockDelimiter(locale);
  112. } catch (final LocaleNotLoadedException e) {
  113. getLogger().log(Level.SEVERE, "Error in getClockDelimiter", e);
  114. return ":";
  115. }
  116. }
  117. private static final String[] DEFAULT_AMPM_STRINGS = { "AM", "PM" };
  118. public String[] getAmPmStrings() {
  119. try {
  120. return LocaleService.getAmPmStrings(locale);
  121. } catch (final LocaleNotLoadedException e) {
  122. // TODO can this practically even happen? Should die instead?
  123. getLogger().log(Level.SEVERE,
  124. "Locale not loaded, using fallback : AM/PM", e);
  125. return DEFAULT_AMPM_STRINGS;
  126. }
  127. }
  128. public int getStartWeekDay(Date date) {
  129. final Date dateForFirstOfThisMonth = new Date(date.getYear(),
  130. date.getMonth(), 1);
  131. int firstDay;
  132. try {
  133. firstDay = LocaleService.getFirstDayOfWeek(locale);
  134. } catch (final LocaleNotLoadedException e) {
  135. getLogger().log(Level.SEVERE, "Locale not loaded, using fallback 0",
  136. e);
  137. firstDay = 0;
  138. }
  139. int start = dateForFirstOfThisMonth.getDay() - firstDay;
  140. if (start < 0) {
  141. start = 6;
  142. }
  143. return start;
  144. }
  145. public static void setMilliseconds(Date date, int ms) {
  146. date.setTime(date.getTime() / 1000 * 1000 + ms);
  147. }
  148. public static int getMilliseconds(Date date) {
  149. if (date == null) {
  150. return 0;
  151. }
  152. return (int) (date.getTime() - date.getTime() / 1000 * 1000);
  153. }
  154. public static int getNumberOfDaysInMonth(Date date) {
  155. final int month = date.getMonth();
  156. if (month == 1 && isLeapYear(date)) {
  157. return 29;
  158. }
  159. return maxDaysInMonth[month];
  160. }
  161. public static boolean isLeapYear(Date date) {
  162. // Instantiate the date for 1st March of that year
  163. final Date firstMarch = new Date(date.getYear(), 2, 1);
  164. // Go back 1 day
  165. final long firstMarchTime = firstMarch.getTime();
  166. final long lastDayTimeFeb = firstMarchTime - (24 * 60 * 60 * 1000); // NUM_MILLISECS_A_DAY
  167. // Instantiate new Date with this time
  168. final Date febLastDay = new Date(lastDayTimeFeb);
  169. // Check for date in this new instance
  170. return (29 == febLastDay.getDate()) ? true : false;
  171. }
  172. public static boolean isSameDay(Date d1, Date d2) {
  173. return (getDayInt(d1) == getDayInt(d2));
  174. }
  175. public static boolean isInRange(Date date, Date rangeStart, Date rangeEnd,
  176. DateResolution resolution) {
  177. Date s;
  178. Date e;
  179. if (rangeStart.after(rangeEnd)) {
  180. s = rangeEnd;
  181. e = rangeStart;
  182. } else {
  183. e = rangeEnd;
  184. s = rangeStart;
  185. }
  186. long start = s.getYear() * 10000000000l;
  187. long end = e.getYear() * 10000000000l;
  188. long target = date.getYear() * 10000000000l;
  189. if (resolution == DateResolution.YEAR) {
  190. return (start <= target && end >= target);
  191. }
  192. start += s.getMonth() * 100000000l;
  193. end += e.getMonth() * 100000000l;
  194. target += date.getMonth() * 100000000l;
  195. if (resolution == DateResolution.MONTH) {
  196. return (start <= target && end >= target);
  197. }
  198. start += s.getDate() * 1000000l;
  199. end += e.getDate() * 1000000l;
  200. target += date.getDate() * 1000000l;
  201. if (resolution == DateResolution.DAY) {
  202. return (start <= target && end >= target);
  203. }
  204. start += s.getHours() * 10000l;
  205. end += e.getHours() * 10000l;
  206. target += date.getHours() * 10000l;
  207. start += s.getMinutes() * 100l;
  208. end += e.getMinutes() * 100l;
  209. target += date.getMinutes() * 100l;
  210. start += s.getSeconds();
  211. end += e.getSeconds();
  212. target += date.getSeconds();
  213. return (start <= target && end >= target);
  214. }
  215. private static int getDayInt(Date date) {
  216. final int y = date.getYear();
  217. final int m = date.getMonth();
  218. final int d = date.getDate();
  219. return ((y + 1900) * 10000 + m * 100 + d) * 1000000000;
  220. }
  221. /**
  222. * Returns the ISO-8601 week number of the given date.
  223. *
  224. * @param date
  225. * The date for which the week number should be resolved
  226. * @return The ISO-8601 week number for {@literal date}
  227. */
  228. public static int getISOWeekNumber(Date date) {
  229. final long MILLISECONDS_PER_DAY = 24 * 3600 * 1000;
  230. int dayOfWeek = date.getDay(); // 0 == sunday
  231. // ISO 8601 use weeks that start on monday so we use
  232. // mon=1,tue=2,...sun=7;
  233. if (dayOfWeek == 0) {
  234. dayOfWeek = 7;
  235. }
  236. // Find nearest thursday (defines the week in ISO 8601). The week number
  237. // for the nearest thursday is the same as for the target date.
  238. int nearestThursdayDiff = 4 - dayOfWeek; // 4 is thursday
  239. Date nearestThursday = new Date(
  240. date.getTime() + nearestThursdayDiff * MILLISECONDS_PER_DAY);
  241. Date firstOfJanuary = new Date(nearestThursday.getYear(), 0, 1);
  242. long timeDiff = nearestThursday.getTime() - firstOfJanuary.getTime();
  243. // Rounding the result, as the division doesn't result in an integer
  244. // when the given date is inside daylight saving time period.
  245. int daysSinceFirstOfJanuary = (int) Math
  246. .round((double) timeDiff / MILLISECONDS_PER_DAY);
  247. int weekNumber = (daysSinceFirstOfJanuary) / 7 + 1;
  248. return weekNumber;
  249. }
  250. /**
  251. * Check if format contains the month name. If it does we manually convert
  252. * it to the month name since DateTimeFormat.format always uses the current
  253. * locale and will replace the month name wrong if current locale is
  254. * different from the locale set for the DateField.
  255. *
  256. * MMMM is converted into long month name, MMM is converted into short month
  257. * name. '' are added around the name to avoid that DateTimeFormat parses
  258. * the month name as a pattern.
  259. *
  260. * @param date
  261. * The date to convert
  262. * @param formatStr
  263. * The format string that might contain MMM or MMMM
  264. * @return
  265. */
  266. public String formatDate(Date date, String formatStr) {
  267. return formatDate(date, formatStr, null);
  268. }
  269. /**
  270. * Check if format contains the month name. If it does we manually convert
  271. * it to the month name since DateTimeFormat.format always uses the current
  272. * locale and will replace the month name wrong if current locale is
  273. * different from the locale set for the DateField.
  274. *
  275. * MMMM is converted into long month name, MMM is converted into short month
  276. * name. '' are added around the name to avoid that DateTimeFormat parses
  277. * the month name as a pattern.
  278. *
  279. * z is converted into the time zone name, using the specified
  280. * {@code timeZoneJSON}
  281. *
  282. * @param date
  283. * The date to convert
  284. * @param formatStr
  285. * The format string that might contain {@code MMM} or
  286. * {@code MMMM}
  287. * @param timeZone
  288. * The {@link TimeZone} used to replace {@code z}, can be
  289. * {@code null}
  290. *
  291. * @return the formatted date string
  292. * @since 8.2
  293. */
  294. public String formatDate(Date date, String formatStr, TimeZone timeZone) {
  295. /*
  296. * Format month and day names separately when locale for the
  297. * DateTimeService is not the same as the browser locale
  298. */
  299. formatStr = formatTimeZone(date, formatStr, timeZone);
  300. formatStr = formatMonthNames(date, formatStr);
  301. formatStr = formatDayNames(date, formatStr);
  302. // Format uses the browser locale
  303. DateTimeFormat format = DateTimeFormat.getFormat(formatStr);
  304. String result = format.format(date);
  305. return result;
  306. }
  307. private String formatDayNames(Date date, String formatStr) {
  308. if (formatStr.contains("EEEE")) {
  309. String dayName = getDay(date.getDay());
  310. if (dayName != null) {
  311. /*
  312. * Replace 4 or more E:s with the quoted day name. Also
  313. * concatenate generated string with any other string prepending
  314. * or following the EEEE pattern, i.e. 'EEEE'ta ' becomes 'DAYta
  315. * ' and not 'DAY''ta ', 'ab'EEEE becomes 'abDAY', 'x'EEEE'y'
  316. * becomes 'xDAYy'.
  317. */
  318. formatStr = formatStr.replaceAll("'([E]{4,})'", dayName);
  319. formatStr = formatStr.replaceAll("([E]{4,})'", "'" + dayName);
  320. formatStr = formatStr.replaceAll("'([E]{4,})", dayName + "'");
  321. formatStr = formatStr.replaceAll("[E]{4,}",
  322. "'" + dayName + "'");
  323. }
  324. }
  325. if (formatStr.contains("EEE")) {
  326. String dayName = getShortDay(date.getDay());
  327. if (dayName != null) {
  328. /*
  329. * Replace 3 or more E:s with the quoted month name. Also
  330. * concatenate generated string with any other string prepending
  331. * or following the EEE pattern, i.e. 'EEE'ta ' becomes 'DAYta '
  332. * and not 'DAY''ta ', 'ab'EEE becomes 'abDAY', 'x'EEE'y'
  333. * becomes 'xDAYy'.
  334. */
  335. formatStr = formatStr.replaceAll("'([E]{3,})'", dayName);
  336. formatStr = formatStr.replaceAll("([E]{3,})'", "'" + dayName);
  337. formatStr = formatStr.replaceAll("'([E]{3,})", dayName + "'");
  338. formatStr = formatStr.replaceAll("[E]{3,}",
  339. "'" + dayName + "'");
  340. }
  341. }
  342. return formatStr;
  343. }
  344. private String formatMonthNames(Date date, String formatStr) {
  345. if (formatStr.contains("MMMM")) {
  346. String monthName = getMonth(date.getMonth());
  347. if (monthName != null) {
  348. /*
  349. * Replace 4 or more M:s with the quoted month name. Also
  350. * concatenate generated string with any other string prepending
  351. * or following the MMMM pattern, i.e. 'MMMM'ta ' becomes
  352. * 'MONTHta ' and not 'MONTH''ta ', 'ab'MMMM becomes 'abMONTH',
  353. * 'x'MMMM'y' becomes 'xMONTHy'.
  354. */
  355. formatStr = formatStr.replaceAll("'([M]{4,})'", monthName);
  356. formatStr = formatStr.replaceAll("([M]{4,})'", "'" + monthName);
  357. formatStr = formatStr.replaceAll("'([M]{4,})", monthName + "'");
  358. formatStr = formatStr.replaceAll("[M]{4,}",
  359. "'" + monthName + "'");
  360. }
  361. }
  362. if (formatStr.contains("MMM")) {
  363. String monthName = getShortMonth(date.getMonth());
  364. if (monthName != null) {
  365. /*
  366. * Replace 3 or more M:s with the quoted month name. Also
  367. * concatenate generated string with any other string prepending
  368. * or following the MMM pattern, i.e. 'MMM'ta ' becomes 'MONTHta
  369. * ' and not 'MONTH''ta ', 'ab'MMM becomes 'abMONTH', 'x'MMM'y'
  370. * becomes 'xMONTHy'.
  371. */
  372. formatStr = formatStr.replaceAll("'([M]{3,})'", monthName);
  373. formatStr = formatStr.replaceAll("([M]{3,})'", "'" + monthName);
  374. formatStr = formatStr.replaceAll("'([M]{3,})", monthName + "'");
  375. formatStr = formatStr.replaceAll("[M]{3,}",
  376. "'" + monthName + "'");
  377. }
  378. }
  379. return formatStr;
  380. }
  381. private String formatTimeZone(Date date, String formatStr,
  382. TimeZone timeZone) {
  383. // if 'z' is found outside quotes and timeZone is used
  384. if (getIndexOf(formatStr, 'z') != -1 && timeZone != null) {
  385. return replaceTimeZone(formatStr, timeZone.getShortName(date));
  386. }
  387. return formatStr;
  388. }
  389. /**
  390. * Replaces the {@code z} characters of the specified {@code formatStr} with
  391. * the given {@code timeZoneName}.
  392. *
  393. * @param formatStr
  394. * The format string, which is the pattern describing the date
  395. * and time format
  396. * @param timeZoneName
  397. * the time zone name
  398. * @return the format string, with {@code z} replaced (if found)
  399. */
  400. private static String replaceTimeZone(String formatStr,
  401. String timeZoneName) {
  402. // search for 'z' outside the quotes (inside quotes is escaped)
  403. int start = getIndexOf(formatStr, 'z');
  404. if (start == -1) {
  405. return formatStr;
  406. }
  407. // if there are multiple consecutive 'z', treat them as one
  408. int end = start;
  409. while (end + 1 < formatStr.length()
  410. && formatStr.charAt(end + 1) == 'z') {
  411. end++;
  412. }
  413. return formatStr.substring(0, start) + "'" + timeZoneName + "'"
  414. + formatStr.substring(end + 1);
  415. }
  416. /**
  417. * Returns the first index of the specified {@code ch}, which is outside the
  418. * quotes.
  419. */
  420. private static int getIndexOf(String str, char ch) {
  421. boolean inQuote = false;
  422. for (int i = 0; i < str.length(); i++) {
  423. char c = str.charAt(i);
  424. if (c == '\'') {
  425. if (i + 1 < str.length() && str.charAt(i + 1) == '\'') {
  426. i++;
  427. } else {
  428. inQuote ^= true;
  429. }
  430. } else if (c == ch && !inQuote) {
  431. return i;
  432. }
  433. }
  434. return -1;
  435. }
  436. /**
  437. * Replaces month names in the entered date with the name in the current
  438. * browser locale.
  439. *
  440. * @param enteredDate
  441. * Date string e.g. "5 May 2010"
  442. * @param formatString
  443. * Format string e.g. "d M yyyy"
  444. * @return The date string where the month names have been replaced by the
  445. * browser locale version
  446. */
  447. private String parseMonthName(String enteredDate, String formatString) {
  448. LocaleInfo browserLocale = LocaleInfo.getCurrentLocale();
  449. if (browserLocale.getLocaleName().equals(getLocale())) {
  450. // No conversion needs to be done when locales match
  451. return enteredDate;
  452. }
  453. String[] browserMonthNames = browserLocale.getDateTimeConstants()
  454. .months();
  455. String[] browserShortMonthNames = browserLocale.getDateTimeConstants()
  456. .shortMonths();
  457. if (formatString.contains("MMMM")) {
  458. // Full month name
  459. for (int i = 0; i < 12; i++) {
  460. enteredDate = enteredDate.replaceAll(getMonth(i),
  461. browserMonthNames[i]);
  462. }
  463. }
  464. if (formatString.contains("MMM")) {
  465. // Short month name
  466. for (int i = 0; i < 12; i++) {
  467. enteredDate = enteredDate.replaceAll(getShortMonth(i),
  468. browserShortMonthNames[i]);
  469. }
  470. }
  471. return enteredDate;
  472. }
  473. /**
  474. * Parses the given date string using the given format string and the locale
  475. * set in this DateTimeService instance.
  476. *
  477. * @param dateString
  478. * Date string e.g. "1 February 2010"
  479. * @param formatString
  480. * Format string e.g. "d MMMM yyyy"
  481. * @param lenient
  482. * true to use lenient parsing, false to use strict parsing
  483. * @return A Date object representing the dateString. Never returns null.
  484. * @throws IllegalArgumentException
  485. * if the parsing fails
  486. *
  487. */
  488. public Date parseDate(String dateString, String formatString,
  489. boolean lenient) throws IllegalArgumentException {
  490. /* DateTimeFormat uses the browser's locale */
  491. DateTimeFormat format = DateTimeFormat.getFormat(formatString);
  492. /*
  493. * Parse month names separately when locale for the DateTimeService is
  494. * not the same as the browser locale
  495. */
  496. dateString = parseMonthName(dateString, formatString);
  497. Date date;
  498. if (lenient) {
  499. date = format.parse(dateString);
  500. } else {
  501. date = format.parseStrict(dateString);
  502. }
  503. // Some version of Firefox sets the timestamp to 0 if parsing fails.
  504. if (date != null && date.getTime() == 0) {
  505. throw new IllegalArgumentException(
  506. "Parsing of '" + dateString + "' failed");
  507. }
  508. return date;
  509. }
  510. private static Logger getLogger() {
  511. return Logger.getLogger(DateTimeService.class.getName());
  512. }
  513. }