如何在Java简单日期格式

时间:2017-04-20 11:45:25

标签: java

当我运行以下代码将时间字符串转换为Java日期时,它失败了。

String s = "04/17/2017 06:46:53 -600";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");
Date value = format.parse(s);

Exception in thread "main" java.text.ParseException: Unparseable date: "04/17/2017 06:46:53 -600"
    at java.text.DateFormat.parse(Unknown Source)

将日期字符串转换为java日期的正确格式字符串是什么?

3 个答案:

答案 0 :(得分:2)

正如SimpleDateFormat time zone documentation解释:

  

RFC 822时区:对于格式化,使用RFC 822 4位时区格式:

RFC822TimeZone:
         Sign TwoDigitHours Minutes
 TwoDigitHours:
         Digit Digit
  

ISO 8601时区:模式字母的数量指定格式化和解析的格式,如下所示:

ISO8601TimeZone:
         OneLetterISO8601TimeZone
         TwoLetterISO8601TimeZone
         ThreeLetterISO8601TimeZone
    OneLetterISO8601TimeZone:
         Sign TwoDigitHours
         Z
    TwoLetterISO8601TimeZone:
         Sign TwoDigitHours Minutes
         Z
    ThreeLetterISO8601TimeZone:
         Sign TwoDigitHours : Minutes
         Z

小时数始终为两位数,因此您需要将-0600作为时区或-06

您可以使用:

来获得一位数小时的唯一方法
  

常规时区:如果时区具有名称,则会将其解释为文本。对于表示GMT偏移值的时区,使用以下语法:

GMTOffsetTimeZone:
         GMT Sign Hours : Minutes
 Sign: one of
         + -
 Hours:
         Digit
         Digit Digit
 Minutes:
         Digit Digit
 Digit: one of
         0 1 2 3 4 5 6 7 8 9

答案 1 :(得分:2)

添加-0600而不是-600 read link

import java.text.*;
import java.util.*;
class TestFormatDate {


public static void main(String arg[]) throws Exception{

String s = "04/17/2017 06:46:53 -0600";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");
Date value = format.parse(s);
System.out.println("value "+value); 
}
}

答案 2 :(得分:0)

尝试,

String s = "04/17/2017 06:46:53 -0600";

请阅读this以查看如何使用" Z"。