View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.intl;
16  
17  import java.time.ZoneId;
18  import java.time.chrono.Chronology;
19  import java.time.chrono.JapaneseChronology;
20  import java.time.chrono.ThaiBuddhistChronology;
21  import java.time.format.DateTimeFormatter;
22  import java.time.format.DecimalStyle;
23  import java.time.temporal.TemporalAccessor;
24  import java.util.Date;
25  import java.util.HashMap;
26  import java.util.Map;
27  import java.util.concurrent.ConcurrentHashMap;
28  
29  import org.htmlunit.BrowserVersion;
30  import org.htmlunit.corejs.javascript.Context;
31  import org.htmlunit.corejs.javascript.Function;
32  import org.htmlunit.corejs.javascript.FunctionObject;
33  import org.htmlunit.corejs.javascript.NativeArray;
34  import org.htmlunit.corejs.javascript.Scriptable;
35  import org.htmlunit.javascript.HtmlUnitScriptable;
36  import org.htmlunit.javascript.JavaScriptEngine;
37  import org.htmlunit.javascript.configuration.JsxClass;
38  import org.htmlunit.javascript.configuration.JsxConstructor;
39  import org.htmlunit.javascript.configuration.JsxFunction;
40  import org.htmlunit.javascript.host.Window;
41  import org.htmlunit.util.StringUtils;
42  
43  /**
44   * A JavaScript object for {@code DateTimeFormat}.
45   *
46   * @author Ahmed Ashour
47   * @author Ronald Brill
48   */
49  @JsxClass
50  public class DateTimeFormat extends HtmlUnitScriptable {
51  
52      private static final ConcurrentHashMap<String, String> CHROME_FORMATS_ = new ConcurrentHashMap<>();
53      private static final ConcurrentHashMap<String, String> EDGE_FORMATS_ = new ConcurrentHashMap<>();
54      private static final ConcurrentHashMap<String, String> FF_FORMATS_ = new ConcurrentHashMap<>();
55      private static final ConcurrentHashMap<String, String> FF_ESR_FORMATS_ = new ConcurrentHashMap<>();
56  
57      private static final ConcurrentHashMap<String, Chronology> CHROME_CHRONOLOGIES_ = new ConcurrentHashMap<>();
58      private static final ConcurrentHashMap<String, Chronology> EDGE_CHRONOLOGIES_ = new ConcurrentHashMap<>();
59      private static final ConcurrentHashMap<String, Chronology> FF_CHRONOLOGIES_ = new ConcurrentHashMap<>();
60      private static final ConcurrentHashMap<String, Chronology> FF_ESR_CHRONOLOGIES_ = new ConcurrentHashMap<>();
61  
62      private transient DateTimeFormatHelper formatter_;
63  
64      static {
65          final String ddSlash = "\u200Edd\u200E/\u200EMM\u200E/\u200EYYYY";
66          final String ddDash = "\u200Edd\u200E-\u200EMM\u200E-\u200EYYYY";
67          final String ddDot = "\u200Edd\u200E.\u200EMM\u200E.\u200EYYYY";
68          final String ddDotDot = "\u200Edd\u200E.\u200EMM\u200E.\u200EYYYY\u200E.";
69          final String ddDotBlank = "\u200Edd\u200E. \u200EMM\u200E. \u200EYYYY";
70          final String ddDotBlankDot = "\u200Edd\u200E. \u200EMM\u200E. \u200EYYYY.";
71          final String mmSlash = "\u200EMM\u200E/\u200Edd\u200E/\u200EYYYY";
72          final String yyyySlash = "\u200EYYYY\u200E/\u200EMM\u200E/\u200Edd";
73          final String yyyyDash = "\u200EYYYY\u200E-\u200EMM\u200E-\u200Edd";
74          final String yyyyDotBlankDot = "\u200EYYYY\u200E. \u200EMM\u200E. \u200Edd.";
75  
76          final Map<String, String> commonFormats = new HashMap<>();
77          commonFormats.put("", ddDot);
78          commonFormats.put("ar", "dd\u200F/MM\u200F/YYYY");
79          commonFormats.put("ban", mmSlash);
80          commonFormats.put("be", ddDot);
81          commonFormats.put("bg", ddDot + "\u200E \u0433.");
82          commonFormats.put("ca", ddSlash);
83          commonFormats.put("cs", ddDotBlank);
84          commonFormats.put("da", ddDot);
85          commonFormats.put("de", ddDot);
86          commonFormats.put("el", ddSlash);
87          commonFormats.put("en", mmSlash);
88          commonFormats.put("en-CA", yyyyDash);
89          commonFormats.put("en-NZ", ddSlash);
90          commonFormats.put("en-PA", ddSlash);
91          commonFormats.put("en-PR", ddSlash);
92          commonFormats.put("en-PH", mmSlash);
93          commonFormats.put("en-AU", ddSlash);
94          commonFormats.put("en-GB", ddSlash);
95          commonFormats.put("en-IE", ddSlash);
96          commonFormats.put("en-IN", ddSlash);
97          commonFormats.put("en-MT", ddSlash);
98          commonFormats.put("en-SG", ddSlash);
99          commonFormats.put("en-ZA", yyyySlash);
100         commonFormats.put("es", ddSlash);
101         commonFormats.put("es-CL", ddDash);
102         commonFormats.put("es-PA", mmSlash);
103         commonFormats.put("es-PR", mmSlash);
104         commonFormats.put("es-US", ddSlash);
105         commonFormats.put("et", ddDot);
106         commonFormats.put("fi", ddDot);
107         commonFormats.put("fr", ddSlash);
108         commonFormats.put("fr-CA", yyyyDash);
109         commonFormats.put("ga", ddSlash);
110         commonFormats.put("hi", ddSlash);
111         commonFormats.put("hr", ddDotBlankDot);
112         commonFormats.put("hu", yyyyDotBlankDot);
113         commonFormats.put("id", ddSlash);
114         commonFormats.put("in", ddSlash);
115         commonFormats.put("is", ddDot);
116         commonFormats.put("it", ddSlash);
117         commonFormats.put("iw", ddDot);
118         commonFormats.put("ja", yyyySlash);
119         commonFormats.put("ja-JP-u-ca-japanese", "'H'yy/MM/dd");
120         commonFormats.put("ko", yyyyDotBlankDot);
121         commonFormats.put("lt", yyyyDash);
122         commonFormats.put("lv", ddDotDot);
123         commonFormats.put("mk", ddDot + "\u200E \u0433.");
124         commonFormats.put("ms", ddSlash);
125         commonFormats.put("mt", mmSlash);
126         commonFormats.put("nl", ddDash);
127         commonFormats.put("nl-BE", ddSlash);
128         commonFormats.put("pl", ddDot);
129         commonFormats.put("pt", ddSlash);
130         commonFormats.put("ro", ddDot);
131         commonFormats.put("ru", ddDot);
132         commonFormats.put("sk", ddDotBlank);
133         commonFormats.put("sl", ddDotBlank);
134         commonFormats.put("sq", ddDot);
135         commonFormats.put("sr", ddDotBlankDot);
136         commonFormats.put("sv", yyyyDash);
137         commonFormats.put("th", ddSlash);
138         commonFormats.put("tr", ddDot);
139         commonFormats.put("uk", ddDot);
140         commonFormats.put("vi", ddSlash);
141         commonFormats.put("zh", yyyySlash);
142         commonFormats.put("zh-HK", ddSlash);
143         commonFormats.put("zh-SG", "\u200EYYYY\u200E\u5E74\u200EMM\u200E\u6708\u200Edd\u200E\u65E5");
144         commonFormats.put("fr-CH", ddDot);
145 
146         FF_FORMATS_.putAll(commonFormats);
147         FF_ESR_FORMATS_.putAll(commonFormats);
148 
149         commonFormats.put("be", mmSlash);
150         commonFormats.put("ga", mmSlash);
151         commonFormats.put("is", mmSlash);
152         commonFormats.put("mk", mmSlash);
153 
154         EDGE_FORMATS_.putAll(commonFormats);
155 
156         CHROME_FORMATS_.putAll(commonFormats);
157         CHROME_FORMATS_.put("sq", mmSlash);
158 
159         final Map<String, Chronology> commonChronologies = new HashMap<>();
160         commonChronologies.put("ja-JP-u-ca-japanese", JapaneseChronology.INSTANCE);
161         commonChronologies.put("th", ThaiBuddhistChronology.INSTANCE);
162         commonChronologies.put("th-TH", ThaiBuddhistChronology.INSTANCE);
163 
164         FF_CHRONOLOGIES_.putAll(commonChronologies);
165         FF_ESR_CHRONOLOGIES_.putAll(commonChronologies);
166         CHROME_CHRONOLOGIES_.putAll(commonChronologies);
167         EDGE_CHRONOLOGIES_.putAll(commonChronologies);
168     }
169 
170     /**
171      * Default constructor.
172      */
173     public DateTimeFormat() {
174         super();
175     }
176 
177     private DateTimeFormat(final String[] locales, final BrowserVersion browserVersion) {
178         super();
179 
180         final Map<String, String> formats;
181         final Map<String, Chronology> chronologies;
182         if (browserVersion.isChrome()) {
183             formats = CHROME_FORMATS_;
184             chronologies = CHROME_CHRONOLOGIES_;
185         }
186         else if (browserVersion.isEdge()) {
187             formats = EDGE_FORMATS_;
188             chronologies = EDGE_CHRONOLOGIES_;
189         }
190         else if (browserVersion.isFirefoxESR()) {
191             formats = FF_ESR_FORMATS_;
192             chronologies = FF_ESR_CHRONOLOGIES_;
193         }
194         else {
195             formats = FF_FORMATS_;
196             chronologies = FF_CHRONOLOGIES_;
197         }
198 
199         String locale = browserVersion.getBrowserLocale().toLanguageTag();
200         String pattern = getPattern(formats, locale);
201 
202         for (final String l : locales) {
203             pattern = getPattern(formats, l);
204             if (pattern != null) {
205                 locale = l;
206             }
207         }
208 
209         if (pattern == null) {
210             pattern = formats.get("");
211         }
212 
213         if (!locale.startsWith("ar")) {
214             pattern = pattern.replace("\u200E", "");
215         }
216 
217         final Chronology chronology = getChronology(chronologies, locale);
218 
219         formatter_ = new DateTimeFormatHelper(locale, chronology, pattern);
220     }
221 
222     private static String getPattern(final Map<String, String> formats, String locale) {
223         if ("no-NO-NY".equals(locale)) {
224             throw JavaScriptEngine.rangeError("Invalid language tag: " + locale);
225         }
226         String pattern = formats.get(locale);
227         while (pattern == null && locale.indexOf('-') != -1) {
228             locale = locale.substring(0, locale.lastIndexOf('-'));
229             pattern = formats.get(locale);
230         }
231         return pattern;
232     }
233 
234     private static Chronology getChronology(final Map<String, Chronology> chronologies, String locale) {
235         Chronology chronology = chronologies.get(locale);
236         while (chronology == null && locale.indexOf('-') != -1) {
237             locale = locale.substring(0, locale.lastIndexOf('-'));
238             chronology = chronologies.get(locale);
239         }
240         return chronology;
241     }
242 
243     /**
244      * JavaScript constructor.
245      * @param cx the current context
246      * @param scope the scope
247      * @param args the arguments to the WebSocket constructor
248      * @param ctorObj the function object
249      * @param inNewExpr Is new or not
250      * @return the java object to allow JavaScript to access
251      */
252     @JsxConstructor
253     public static Scriptable jsConstructor(final Context cx, final Scriptable scope,
254             final Object[] args, final Function ctorObj, final boolean inNewExpr) {
255         final String[] locales;
256         if (args.length != 0) {
257             if (args[0] instanceof NativeArray) {
258                 final NativeArray array = (NativeArray) args[0];
259                 locales = new String[(int) array.getLength()];
260                 for (int i = 0; i < locales.length; i++) {
261                     locales[i] = JavaScriptEngine.toString(array.get(i));
262                 }
263             }
264             else {
265                 locales = new String[] {JavaScriptEngine.toString(args[0])};
266             }
267         }
268         else {
269             locales = new String[0];
270         }
271 
272         final Window window = getWindow(ctorObj);
273         final DateTimeFormat format = new DateTimeFormat(locales, window.getBrowserVersion());
274         format.setParentScope(window);
275         format.setPrototype(((FunctionObject) ctorObj).getClassPrototype());
276         return format;
277     }
278 
279     /**
280      * Formats a date according to the locale and formatting options of this {@code DateTimeFormat} object.
281      * @param object the JavaScript object to convert
282      * @return the dated formated
283      */
284     @JsxFunction
285     public String format(final Object object) {
286         final Date date = (Date) Context.jsToJava(object, Date.class);
287         return formatter_.format(date, Context.getCurrentContext().getTimeZone().toZoneId());
288     }
289 
290     /**
291      * @return A new object with properties reflecting the locale and date and time formatting options
292      *         computed during the initialization of the given {@code DateTimeFormat} object.
293      */
294     @JsxFunction
295     public Scriptable resolvedOptions() {
296         final Context cx = Context.getCurrentContext();
297         final Scriptable options = cx.newObject(getParentScope());
298         options.put("timeZone", options, cx.getTimeZone().getID());
299 
300         if (StringUtils.isEmptyOrNull(formatter_.locale_)) {
301             options.put("locale", options, cx.getLocale().toLanguageTag());
302         }
303         else {
304             options.put("locale", options, formatter_.locale_);
305         }
306         return options;
307     }
308 
309     /**
310      * Helper.
311      */
312     static final class DateTimeFormatHelper {
313 
314         private final DateTimeFormatter formatter_;
315         private final Chronology chronology_;
316         private final String locale_;
317 
318         DateTimeFormatHelper(final String locale, final Chronology chronology, final String pattern) {
319             locale_ = locale;
320             chronology_ = chronology;
321 
322             if (locale.startsWith("ar")
323                     && !"ar-DZ".equals(locale)
324                     && !"ar-LY".equals(locale)
325                     && !"ar-MA".equals(locale)
326                     && !"ar-TN".equals(locale)) {
327                 final DecimalStyle decimalStyle = DecimalStyle.STANDARD.withZeroDigit('\u0660');
328                 formatter_ = DateTimeFormatter.ofPattern(pattern).withDecimalStyle(decimalStyle);
329             }
330             else {
331                 formatter_ = DateTimeFormatter.ofPattern(pattern);
332             }
333         }
334 
335         /**
336          * Formats a date according to the locale and formatting options of this {@code DateTimeFormat} object.
337          * @param date the JavaScript object to convert
338          * @param zoneId the current time zone id
339          * @return the dated formated
340          */
341         String format(final Date date, final ZoneId zoneId) {
342             TemporalAccessor zonedDateTime = date.toInstant().atZone(zoneId);
343             if (chronology_ != null) {
344                 zonedDateTime = chronology_.date(zonedDateTime);
345             }
346             return formatter_.format(zonedDateTime);
347         }
348     }
349 }