001package org.hl7.fhir.utilities;
002
003import java.util.Calendar;
004import java.util.Date;
005import java.util.Locale;
006import java.util.TimeZone;
007
008import org.apache.commons.lang3.time.FastDateFormat;
009
010import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
011
012public class DateTimeUtil {
013  private static final FastDateFormat ourHumanDateFormat = FastDateFormat.getDateInstance(FastDateFormat.MEDIUM);
014  private static final FastDateFormat ourHumanDateTimeFormat = FastDateFormat.getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM);
015
016
017  public static String toHumanDisplay(TimeZone theTimeZone, TemporalPrecisionEnum thePrecision, Date theValue, String theValueAsString) {
018    Calendar value = theTimeZone != null ? Calendar.getInstance(theTimeZone) : Calendar.getInstance();
019    value.setTime(theValue);
020
021    switch (thePrecision) {
022      case YEAR:
023      case MONTH:
024      case DAY:
025        return theValueAsString;
026      case MILLI:
027      case SECOND:
028      default:
029        return ourHumanDateTimeFormat.format(value);
030    }
031
032  }
033
034  public static String toHumanDisplayLocalTimezone(TemporalPrecisionEnum thePrecision, Date theValue, String theValueAsString) {
035    switch (thePrecision) {
036      case YEAR:
037      case MONTH:
038      case DAY:
039        return theValueAsString;
040      case MILLI:
041      case SECOND:
042      default:
043        return ourHumanDateTimeFormat.format(theValue);
044    }
045  }
046
047  public static String toHumanDisplay(Locale locale, TimeZone theTimeZone, TemporalPrecisionEnum thePrecision, Date theValue) {
048    Calendar value = theTimeZone != null ? Calendar.getInstance(theTimeZone) : Calendar.getInstance();
049    value.setTime(theValue);
050
051    FastDateFormat dateFormat = FastDateFormat.getDateInstance(FastDateFormat.MEDIUM, locale);
052    FastDateFormat dateTimeFormat = FastDateFormat.getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM, locale);
053
054    switch (thePrecision) {
055      case YEAR:
056      case MONTH:
057      case DAY:
058        return dateFormat.format(value);
059      case MILLI:
060      case SECOND:
061      default:
062        return dateTimeFormat.format(value);
063    }
064
065  }
066
067}