0

When I am running the below code to convert the time string to Java date, it is failing.

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)

What is the correct format string to be used to convert the date string to java date ?

kiran
  • 2,280
  • 2
  • 23
  • 30

3 Answers3

3

add -0600 instead -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); 
}
}
Mohsin AR
  • 2,998
  • 2
  • 24
  • 36
2

As the SimpleDateFormat time zone documentation explain :

RFC 822 time zone: For formatting, the RFC 822 4-digit time zone format is used:

RFC822TimeZone:
         Sign TwoDigitHours Minutes
 TwoDigitHours:
         Digit Digit

ISO 8601 Time zone: The number of pattern letters designates the format for both formatting and parsing as follows:

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

Hours is always seen with two digits so you need to pass -0600 as a timezone or -06

The only way you can have a one digit hours is with :

General time zone: Time zones are interpreted as text if they have names. For time zones representing a GMT offset value, the following syntax is used:

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
AxelH
  • 14,325
  • 2
  • 25
  • 55
1

Try,

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

Please read this to check how to use "Z".

ProgrammerBoy
  • 876
  • 6
  • 19