|
| 1 | +package fr.free.nrw.commons.utils |
| 2 | + |
| 3 | +import android.text.format.DateFormat.getBestDateTimePattern |
| 4 | +import java.text.ParseException |
| 5 | +import java.text.SimpleDateFormat |
| 6 | +import java.util.Date |
| 7 | +import java.util.HashMap |
| 8 | +import java.util.Locale |
| 9 | +import java.util.TimeZone |
| 10 | + |
| 11 | +/** |
| 12 | + * Utility class for date formatting and parsing. |
| 13 | + * TODO: Switch to DateTimeFormatter when minSdk = 26. |
| 14 | + */ |
| 15 | +object DateUtil { |
| 16 | + |
| 17 | + private val DATE_FORMATS: MutableMap<String, SimpleDateFormat> = HashMap() |
| 18 | + |
| 19 | + @JvmStatic |
| 20 | + @Synchronized |
| 21 | + fun iso8601DateFormat(date: Date): String { |
| 22 | + return getCachedDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT, true).format(date) |
| 23 | + } |
| 24 | + |
| 25 | + @JvmStatic |
| 26 | + @Synchronized |
| 27 | + @Throws(ParseException::class) |
| 28 | + fun iso8601DateParse(date: String): Date { |
| 29 | + return getCachedDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT, true).parse(date) |
| 30 | + } |
| 31 | + |
| 32 | + @JvmStatic |
| 33 | + fun getMonthOnlyDateString(date: Date): String { |
| 34 | + return getDateStringWithSkeletonPattern(date, "MMMM d") |
| 35 | + } |
| 36 | + |
| 37 | + @JvmStatic |
| 38 | + fun getExtraShortDateString(date: Date): String { |
| 39 | + return getDateStringWithSkeletonPattern(date, "MMM d") |
| 40 | + } |
| 41 | + |
| 42 | + @JvmStatic |
| 43 | + @Synchronized |
| 44 | + fun getDateStringWithSkeletonPattern(date: Date, pattern: String): String { |
| 45 | + return getCachedDateFormat( |
| 46 | + getBestDateTimePattern(Locale.getDefault(), pattern), |
| 47 | + Locale.getDefault(), false |
| 48 | + ).format(date) |
| 49 | + } |
| 50 | + |
| 51 | + @JvmStatic |
| 52 | + private fun getCachedDateFormat(pattern: String, locale: Locale, utc: Boolean): SimpleDateFormat { |
| 53 | + if (!DATE_FORMATS.containsKey(pattern)) { |
| 54 | + val df = SimpleDateFormat(pattern, locale) |
| 55 | + if (utc) { |
| 56 | + df.timeZone = TimeZone.getTimeZone("UTC") |
| 57 | + } |
| 58 | + DATE_FORMATS[pattern] = df |
| 59 | + } |
| 60 | + return DATE_FORMATS[pattern]!! |
| 61 | + } |
| 62 | +} |
0 commit comments