0

This is a silly question, but I can't see what I am doing wrong. I want to parse a string like 24:00 to a date object. I am aware that if we use kk:mm as the date format the times would be from 01:00 to 24:00 (from the API). But I can't get the below code working.

String test = "24:00";
System.out.println("TEST: " + new SimpleDateFormat("kk:mm").parse(test));

Output:

TEST: Thu Jan 01 00:00:00 GMT 1970

Expected output:

TEST: Thu Jan 01 24:00:00 GMT 1970

Edit:

System.out.println("TEST: " + new SimpleDateFormat("k:mm:ss").format(new SimpleDateFormat("k:mm:ss").parse(test)));

this prints TEST: Thu Jan 01 24:00:00 GMT 1970

But why not while parsing?

Any help is greatly appreciated

5
  • Try to output "Thu Jan 01 00:00:00 GMT 1970" via "kk:mm" and you will see :) Commented Sep 28, 2012 at 11:13
  • @Fildor ofcourse, it works that way. but why not while parsing? Commented Sep 28, 2012 at 11:15
  • It does actually work. But the DateTime object cannot hold "24:00". It is 00:00 - 23:59. It will output 00:00 as 24:00 when formated with "k" but internally still be 00:00. It's a bit like using AM/PM or 24-hour. Internally represented the same - different output. Commented Sep 28, 2012 at 11:18
  • @Fildor ahh, now i understand.. tahnsk :) Commented Sep 28, 2012 at 11:21
  • I was actually a bit sloppy, +1 for @jalynn2's precise explanation. Commented Sep 28, 2012 at 11:23

1 Answer 1

5

The Date.toString() method is defaulting to hh:mm. Use SimpleDateFormat to output it as well as to parse it.

Sign up to request clarification or add additional context in comments.

3 Comments

i dont want a string i want a date object
@chaitanya10: They dates are the same, it's just a question of how you want the output formatted.
The Date object uses a long to represent the time: number of milliseconds since 1970-01-01. WHen you parse it you get a date object with that number. The formatting turns that number into a human-readable string. You may request that the string is formatted where midnight="00:00", "24:00", or "12:00 AM". They are all just different representations of the same thing. Since you are not supplying a date, 00:00 = 24:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.