• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 @android.ravenwood.annotation.RavenwoodKeepWholeClass
33 class DateTimeFormat {
34     private static final FormatterCache CACHED_FORMATTERS = new FormatterCache();
35 
36     static class FormatterCache extends LruCache<String, DateFormat> {
FormatterCache()37         FormatterCache() {
38             super(8);
39         }
40     }
41 
DateTimeFormat()42     private DateTimeFormat() {
43     }
44 
format(ULocale icuLocale, Calendar time, int flags, DisplayContext displayContext)45     public static String format(ULocale icuLocale, Calendar time, int flags,
46             DisplayContext displayContext) {
47         String skeleton = DateUtilsBridge.toSkeleton(time, flags);
48         String key = skeleton + "\t" + icuLocale + "\t" + time.getTimeZone();
49         synchronized (CACHED_FORMATTERS) {
50             DateFormat formatter = CACHED_FORMATTERS.get(key);
51             if (formatter == null) {
52                 DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(
53                         icuLocale);
54                 formatter = new SimpleDateFormat(generator.getBestPattern(skeleton), icuLocale);
55                 CACHED_FORMATTERS.put(key, formatter);
56             }
57             formatter.setContext(displayContext);
58             return formatter.format(time);
59         }
60     }
61 }
62