Home | History | Annotate | Download | only in icu
      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 libcore.icu;
     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 
     26 import libcore.util.BasicLruCache;
     27 
     28 /**
     29  * A formatter that outputs a single date/time.
     30  */
     31 public class DateTimeFormat {
     32   private static final FormatterCache CACHED_FORMATTERS = new FormatterCache();
     33 
     34   static class FormatterCache extends BasicLruCache<String, DateFormat> {
     35     FormatterCache() {
     36       super(8);
     37     }
     38   }
     39 
     40   private DateTimeFormat() {
     41   }
     42 
     43   public static String format(ULocale icuLocale, Calendar time, int flags,
     44       DisplayContext displayContext) {
     45     String skeleton = DateUtilsBridge.toSkeleton(time, flags);
     46     String key = skeleton + "\t" + icuLocale + "\t" + time.getTimeZone();
     47     synchronized(CACHED_FORMATTERS) {
     48       DateFormat formatter = CACHED_FORMATTERS.get(key);
     49       if (formatter == null) {
     50         DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(icuLocale);
     51         formatter = new SimpleDateFormat(generator.getBestPattern(skeleton), icuLocale);
     52         CACHED_FORMATTERS.put(key, formatter);
     53       }
     54       formatter.setContext(displayContext);
     55       return formatter.format(time);
     56     }
     57   }
     58 }
     59