【问题标题】:conver Datetime String to milliseconds将日期时间字符串转换为毫秒
【发布时间】:2015-10-29 15:27:02
【问题描述】:

我有支持这个 json 的服务:

 JSON={"time":"2015-10-29 14:05:13 +0000"}

所以我想通过以下方式将其转换为毫秒:

String temp = json.getString("time");
            int point = temp.indexOf("+");
            temp = temp.substring(0,point-1);
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd hh:mm:ss");
            Date d = f.parse(temp);
            long milliseconds = d.getTime();

我可以看到我的温度更改为:2015-10-29 14:05:13 但似乎解析有问题。我的格式问题是什么

【问题讨论】:

  • 你已经输入了:“yyyy-MMM-dd hh:mm:ss”,但你应该只有两个 M 的月份。即“yyyy-MM-dd hh:mm:ss”
  • @user2145222 你是对的。谢谢

标签: android date parsing formatting


【解决方案1】:

ss 最多只能返回几秒钟的数据。要返回毫秒,您需要使用以下内容:

   String temp = json.getString("time");
   int point = temp.indexOf("+");
   temp = temp.substring(0,point-1);
   SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSZZ");
   Date d = f.parse(temp);
   long milliseconds = d.getTime();

希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    最重要的改进是选择带有符号 MM 和 HH(不是 hh)和 Z 的正确模式:

    String input = "2015-10-29 14:05:13 +0000";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
    Date d = sdf.parse(input);
    
    • MM 是月份的数字表示,由 2 位数字组成,而 MMM 是文本缩写。

    • H 代表 24 小时制,h 代表 12 小时制。

    • Z 就是所谓的rfc 822 timezone offset。您的输入中有这样的偏移量,那么为什么要过滤掉它呢?将其排除在外甚至是错误的,因为您的格式化程序会解释系统时区中过滤后的输入(其偏移量可能与原始输入中包含的偏移量不同)。

    【讨论】:

    • 感谢我的问题是我错误地将 MMM 而不是 mm,这种格式不起作用并解析错误。 :(
    • @Kenji 不确定你是否问过 Z?无论如何,我已经添加了一个解释,为什么你应该考虑解析的偏移量。
    猜你喜欢
    • 2017-10-11
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多