androider
androider

Reputation: 992

Convert String to Date java error

My date in string format is 2016-09-17 12:12:44. I am converting it to date object by this:

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH);
            Date endDate = sdf1.parse(expiry);

The output is Sat Sep 17 00:12:44 GMT+05:30 2016. However the output should be: Sat Sep 17 12:12:44 GMT+05:30 2016

Upvotes: 0

Views: 744

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 340148

tl;dr

LocalDateTime.parse( "2016-09-17 12:12:44".replace( " " , "T" ) )

Details

The Answer by Crowder is correct.

java.time

Even easier is use with the modern java.time classes.

These classes use the standard ISO 8601 formats by default in parsing and generating strings. So no need to specify a formatting pattern for such strings.

Your input string can be made to comply by replacing SPACE in the middle with a T.

String input = "2016-09-17 12:12:44".replace( " " , "T" );

We parse as a LocalDateTime since your input lacks any info about offset-from-UTC nor time zone.

LocalDateTime ldt = LocalDateTime.parse( input );

By context, you know this value is meant to be a time in India. So apply a time zone of Asia/Kolkata to get a ZonedDateTime.

ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ldt.atZone( z );

Upvotes: 0

Ravindra Devadiga
Ravindra Devadiga

Reputation: 692

As mentioned in the document H - represents 24 hours format and h - represents 12 hours format with am/pm

So the format should be yyyy-MM-dd HH:mm:ss

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
        Date endDate = sdf1.parse("2016-09-17 12:12:44");
        System.out.println(endDate.toString());

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075597

h is "Hour in am/pm (1-12)". Without an am/pm indicator, the assumption is a.m. Use HH where you have hh:

String expiry = "2016-09-17 12:12:44";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
// ------------------------------------------------------^^
Date endDate = sdf1.parse(expiry);
System.out.println(endDate);

Output:

Sat Sep 17 12:12:44 GMT 2016

Live Example

...or update your string to include an am/pm indicator and add a to the format string.

Upvotes: 1

Related Questions