0

I am using below code to parse text to date datatype and get respective long value.

import java.text.DateFormat
import java.text.SimpleDateFormat

String TIMEZONE_DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ssZ";
DateFormat df = new SimpleDateFormat(TIMEZONE_DATE_FORMAT);
Date date = df.parse("2015-09-21T12:48:00+0000");
date.getTime();

In the above case I get getTime() value as: 1442796480000 which is 12:48 AM(GMT). But I am expecting 12:48 PM as its 24 hr format.

When I use the same code with text date: 2015-09-21T13:48:00+0000, I get 1:48 PM which is correct.

Am I using the wrong date format?

Bikas Katwal
  • 1,895
  • 1
  • 21
  • 42
  • in 24 hr format, 00:48 should be 12:48 AM and 12:48 should be 12:48 PM right? that is what I am thinking – Bikas Katwal Jun 04 '19 at 11:38
  • 2
    Get rid of java.Date. It's lucifer reincarnated in a java class – aran Jun 04 '19 at 11:41
  • 1
    Got an answer from Egeo, HH instead of hh. Which works for me. That's still weird that 13:48 doesn't throw an error as an invalid date String if `hh` is used. – Bikas Katwal Jun 04 '19 at 11:44
  • By default, date parsing is lenient. Which means it tries anyway (and may give unintended results). From the [documentation](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DateFormat.html#parse(java.lang.String,java.text.ParsePosition)): *"By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false)."* – Federico klez Culloca Jun 04 '19 at 12:14
  • 2
    Like @aran I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `OffsetDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 04 '19 at 14:57

2 Answers2

3

For 24h the pattern should be HH instead hh

Egeo
  • 140
  • 7
0

Try this:

Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));

It worked fine for me! :)

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95