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