1 /*
2  * Copyright (C) 2015 The Android Open Source Project
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  *
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,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.text.format;
18 
19 import android.icu.text.DateFormat;
20 import android.icu.text.DateTimePatternGenerator;
21 import android.icu.text.DisplayContext;
22 import android.icu.text.SimpleDateFormat;
23 import android.icu.util.Calendar;
24 import android.icu.util.ULocale;
25 import android.util.LruCache;
26 
27 /**
28  * A formatter that outputs a single date/time.
29  *
30  * @hide
31  */
32 class DateTimeFormat {
33     private static final FormatterCache CACHED_FORMATTERS = new FormatterCache();
34 
35     static class FormatterCache extends LruCache<String, DateFormat> {
FormatterCache()36         FormatterCache() {
37             super(8);
38         }
39     }
40 
DateTimeFormat()41     private DateTimeFormat() {
42     }
43 
format(ULocale icuLocale, Calendar time, int flags, DisplayContext displayContext)44     public static String format(ULocale icuLocale, Calendar time, int flags,
45             DisplayContext displayContext) {
46         String skeleton = DateUtilsBridge.toSkeleton(time, flags);
47         String key = skeleton + "\t" + icuLocale + "\t" + time.getTimeZone();
48         synchronized (CACHED_FORMATTERS) {
49             DateFormat formatter = CACHED_FORMATTERS.get(key);
50             if (formatter == null) {
51                 DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(
52                         icuLocale);
53                 formatter = new SimpleDateFormat(generator.getBestPattern(skeleton), icuLocale);
54                 CACHED_FORMATTERS.put(key, formatter);
55             }
56             formatter.setContext(displayContext);
57             return formatter.format(time);
58         }
59     }
60 }
61