2017-06-28 187 views
1

我有以下代码以字符串yyyy-MM-dd HH:mm:ss(UTC时区)的形式取日期并将其转换为EEEE d(st, nd, rd, th) MMMM yyyy HH:mm(设备的默认时区)。解析和格式日期

但是,我所做的方式的问题是代码看起来凌乱和低效。有没有一种方法可以实现我想要的功能,而无需多次格式化和解析同一日期以提高效率?还是有其他改进?

最好的Android支持API级别14


String inputExample = "2017-06-28 22:44:55"; 

//Converts UTC to Device Default (Local) 
private String convertUTC(String dateStr) { 
    try { 
     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     df.setTimeZone(TimeZone.getTimeZone("UTC")); 
     Date temp = df.parse(dateStr); 
     df.setTimeZone(TimeZone.getDefault()); 
     String local = df.format(temp); 
     Date localDate = df.parse(dateStr); 
     SimpleDateFormat outputDF1 = new SimpleDateFormat("EEEE "); 
     SimpleDateFormat outputDF2 = new SimpleDateFormat(" MMMM yyyy HH:mm"); 
     return outputDF1.format(temp) + prefix(local) + outputDF2.format(temp); 
    } catch(java.text.ParseException pE) { 
     Log.e("", "Parse Exception", pE); 
     return null; 
    } 
} 

private String prefix(String dateStr) { 
    try { 
     SimpleDateFormat outputDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     Date temp = outputDF.parse(dateStr); 
     SimpleDateFormat df = new SimpleDateFormat("d"); 
     int d = Integer.parseInt(df.format(temp)); 
     if(1 <= d && d <= 31) { 
      if(11 <= d && d <= 13) 
       return d + "th"; 
      switch (d % 10) { 
       case 1: return d + "st"; 
       case 2: return d + "nd"; 
       case 3: return d + "rd"; 
       default: return d + "th"; 
      } 
     } 
     Log.e("", "Null Date"); 
     return null; 
    } catch(java.text.ParseException pE) { 
     Log.e("", "Parse Exception", pE); 
     return null; 
    } 
} 
+7

我投票结束这个问题作为题外话,因为它属于[codereview.se]。 – shmosel

+0

@shmosel谢谢你指出。我会在那里发布 – Dan

+0

你必须剖析你的代码,找出导致性能差的原因。至于“杂乱”的部分 - 好吧,java.util.date API被广泛认为是“杂乱”,没有太多可以做的事情。重构代码以找到更清洁的方法。在开始重构之前,确保你有一套防弹套装的单元测试。 – Egor

回答

2

随着SimpleDateFormat有可能没有太大的改善。由于您的输出格式有EEEE(星期几)和MMMM(月份名称),您必须解析日期以了解这些日期的值。如果不使用日期格式化程序,则必须执行大量if以获取每个值的相应名称。


在Android中,作为替代SimpleDateFormat,您可以使用ThreeTen Backport,对Java 8的新的日期/时间类大反向移植,与ThreeTenABP在一起(更多关于如何使用它here)。

所有类都低于org.threeten.bp包。在下面的代码我还使用Locale.ENGLISH,否则将使用系统的默认(如我的是不是英语,我假设你是):

String inputExample = "2017-06-28 22:44:55"; 
// parser for input 
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); 
// parse the date and set to UTC 
ZonedDateTime z = LocalDateTime.parse(inputExample, parser).atZone(ZoneOffset.UTC); 

// map of custom values - map each numeric value to its string with suffix (st, nd...) 
Map<Long, String> textLookup = new HashMap<Long, String>(); 
for (int i = 1; i <= 31; i++) { 
    String suffix = ""; 
    switch (i) { 
    case 1: 
    case 21: 
    case 31: 
     suffix = "st"; 
     break; 
    case 2: 
    case 22: 
     suffix = "nd"; 
     break; 
    case 3: 
    case 23: 
     suffix = "rd"; 
     break; 
    default: 
     suffix = "th"; 
    } 
    textLookup.put((long) i, i + suffix); 
} 
// output formatter 
DateTimeFormatter fmt = new DateTimeFormatterBuilder() 
    // day of week 
    .appendPattern("EEEE ") 
    // append day with suffix (use map of custom values) 
    .appendText(ChronoField.DAY_OF_MONTH, textLookup) 
    // rest of pattern 
    .appendPattern(" MMMM yyyy HH:mm") 
    // create formatter with English locale 
    .toFormatter(Locale.ENGLISH); 

// print date, convert it to device default timezone 
System.out.println(fmt.format(z.withZoneSameInstant(ZoneId.systemDefault()))); 

输出将是:

周三2017年6月28日19:44

的时间为19:44,因为我的默认时区为America/Sao_Paulo(在UTC-03:00)。

不知道它是否足够混乱,但至少海事组织,它比SimpleDateFormat更清晰。只创建了2个格式化器(一个用于输出,另一个用于输出)。当然有textLookup映射,但它只有31个条目,格式化程序也可以重用。

SimpleDateFormat is not thread safe,而the new API is