Brendan
Brendan

Reputation: 55

SimpleDateFormat issue

I have this code below and im not getting the right dates out For example a date going in is 01/01/2013 12:35 but the format.parse is only returning the dd/mm/yyyy and excluding the hh:mm

This is a sample date time 03/09/2012 15:26 and the output is producing 1346649960000

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm");
long data = format.parse(childNode.getTextContent()).getTime();

Any clues as to why this would be formatting the time oddly ?

Upvotes: 0

Views: 261

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338584

java.time

Your input string 03/09/2012 15:26 lacks an indicator of time zone or offset-from-UTC. So, in modern Java, parse as a LocalDateTime.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

Apparently you want a count of milliseconds from the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

You cannot derive that count from that input. Your input lacks the context of a time zone or offset. So we have no way to know if your input means around half-past 3 in Tokyo Japan, half-past 3 in Toulouse France, or half-past 3 in Toledo Ohio US — three very different moments several hours apart.

If you know the intended time zone, apply a ZoneId to get a ZonedDateTime.

Or perhaps you intended that date and time to represent a moment as seen in UTC, an offset of zero hours-minutes-seconds from UTC. If so, apply an offset of zero to produce an OffsetDateTime object. Then extract an Instant, and from that get a count.

long count = ldt.atOffset( ZoneOffset.UTC ).toInstant().getEpochSecond() ; 

Upvotes: 0

Dan D.
Dan D.

Reputation: 32391

I see 2 issues in your code:

  1. If you parse a 24 hours formatted time, you have to use HH instead of hh.
  2. You may want to specify the time zone you are using for parsing, 15:26 in your time zone happens at a different time in another time zone.

Please see my proposed fixes below:

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
format.setTimeZone(TimeZone.getTimeZone("UTC"));

Upvotes: 1

Chris
Chris

Reputation: 5654

I think it is giving a valid output. getTime() returns the number of milliseconds since January 1, 1970, 00:00:00. So last 3 zeros are for milliseconds

Upvotes: 1

Related Questions