首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sony Xperia日期问题

Sony Xperia日期问题
EN

Stack Overflow用户
提问于 2014-03-25 22:18:56
回答 2查看 116关注 0票数 2

我遇到了索尼Xperia LT26i上最奇怪的日期问题。A日期格式:"hh:mm:ss a“将打印"01:00 p.m.”在大多数设备上,它会打印"01:00 pm“。你知道为什么会这样吗?它弄乱了我的joda时间,因为我无法解析来自服务器的时间。

EN

回答 2

Stack Overflow用户

发布于 2014-03-26 01:00:13

JodaTime可以解析设备生成的本地am/pm字符串。如何处理来自服务器的不同字符串?幸运的是,您期望从服务器获得的只有"am“或"pm”标记,因此我建议使用两个使用am/pm文字的专用格式化程序对象进行解析。这就是解决方法:

代码语言:javascript
复制
static final DateTimeFormatter AM_PARSER = DateTimeFormat.forPattern("hh:mm:ss 'am'");
static final DateTimeFormatter PM_PARSER = DateTimeFormat.forPattern("hh:mm:ss 'pm'");

public static LocalTime parseServer(String input) {
  if (input.endsWith("am")) {
    return AM_PARSER.parseLocalTime(input);
  } else {
    LocalTime lt = PM_PARSER.parseLocalTime(input);
    return lt.plusHours(12); // necessary because we parse pm only as literal
  }
}

说明:

如果你研究字符串,你会发现am/pm- JodaTime-source code最终来自于DateFormatSymbols.getInstance(locale).getAmPmStrings()。所以问题来了,为什么你会有“下午”。而不是索尼Xperia设备上的"pm“。这就引出了DateFormatSymbols类的数据源是什么的问题。这取决于在任何资源目录中管理此类数据的JVM提供程序(在您的情况下取决于您的特殊Android配置,在我的情况下在资源捆绑包类sun.text.resources.FormatData中)。这对于每个JVM来说都是不同的( Android甚至不是官方的Java-VM)。

票数 0
EN

Stack Overflow用户

发布于 2014-03-27 17:11:38

在考虑了一下之后,我提出了这个解决方案

代码语言:javascript
复制
public static LocalTime localTimeParse(String date, DateTimeFormatter dateTimeFormatter)       {

    if(!StringUtils.hasText(date) || dateTimeFormatter == null)
        return null;

    LocalTime localTime = null;

    try {
        localTime = LocalTime.parse(date,dateTimeFormatter);
    } catch(IllegalArgumentException exception) {
        //This can happen on devices that have their time in the following format "01:00 p.m." insetad of "01:00 pm" 
        //Sony Xperia lT26i is one of them

        String newDate = date.toLowerCase(Locale.getDefault()).contains("am") ? date.toLowerCase(Locale.getDefault()).replace("am", "a.m.") : date.toLowerCase(Locale.getDefault()).replace("pm", "p.m.");
        localTime = LocalTime.parse(newDate,dateTimeFormatter);
    }

    return localTime;
}

这可以像这样使用:

代码语言:javascript
复制
DateTimeFormatter formatter = DateTimeFormat.forPattern("hh:mm a");
LocalTime localTime = DateUtils.localTimeParse("09:00 PM",formatter);

它可以在Xperia和非Xperia上运行

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22637309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档