将Datetime字符串转换为毫秒

时间:2015-10-29 15:27:03

标签: android date parsing formatting

我有服务支持这个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 但它似乎在解析时遇到了问题。什么是我的形态问题

2 个答案:

答案 0 :(得分:0)

Most important improvement is choosing the right pattern with the symbols MM and HH (not hh) and 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 is the numerical representation of month consisting of 2 digits while MMM would be an text abbreviation.

  • H represents the 24-hour-clock and h the 12-hour-clock.

  • Z is the so-called rfc 822 timezone offset. You have such an offset in your input so why filtering it out? It is even an error to leave it out because then your formatter interpretes the filtered input in your system timezone (which has probably a different offset than the offset contained in your original input).

答案 1 :(得分:0)

ss only returns your data up to seconds. To return milliseconds, you need to use the following:

   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();

Hope this helps :)