7
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
LocalTime localTime = fmt.parseLocalTime("02:51:20");
System.out.println("LocalTime:            "+localTime);

I need only 02:51:20 but it outputs as 02:51:20.000. Is there any way that I can remove the .000 (milliseconds) from the output?

Pang
  • 9,564
  • 146
  • 81
  • 122
souashokraj
  • 81
  • 1
  • 1
  • 4
  • Well, just reuse your formatter for printing instead of parsing – fge Jan 16 '15 at 17:32
  • Hi, Thanks for your answer and it works. Is there a way that I can get that in LocalTime instead of String. I need LocalTime as 02:51:20 and not 02:51:20.000. – souashokraj Jan 19 '15 at 10:27
  • No, the `.toString()` of `LocalTime` is fixed. You need to go through a formatter to have the format you want. – fge Jan 19 '15 at 10:32
  • Ok. How to remove the milliseconds from the LocalTime. I need LocalTime only HH:mm:ss format and not the milliseconds included. Is it possible ? – souashokraj Jan 19 '15 at 10:43
  • Hold on, I thought you said the provided solutions worked? – fge Jan 19 '15 at 10:54
  • Yes I do, when I print it removes the .000 from the localtime. But i need the response in LocalTime in the format HH:mm:ss without the milliseconds in it. Am trying to format a String of the format HH:mm:ss to LocalTime without milliseconds. Is it possible ? – souashokraj Jan 19 '15 at 11:38

3 Answers3

3

Yes - you just need to format when you print out. Currently you're just using the default toString() representation. If you're happy with the formatter you've already got, you can just use:

System.out.println("LocalTime:            " + fmt.print(localTime));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

You can easily use your DateTimeFormetter print() method. Try like this;

    DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
    LocalTime localTime = fmt.parseLocalTime("02:51:20");
    System.out.println("LocalTime                        :  " + localTime);
    System.out.println("LocalTime with DateTimeFormatter :  " + fmt.print(localTime));

And the output is;

LocalTime                        :  02:51:20.000
LocalTime with DateTimeFormatter :  02:51:20
Semih Eker
  • 2,389
  • 1
  • 20
  • 29
2

Fixed this using

DateTime time = new DateTime();
DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss");
String localTime = time != null ? format.print(new LocalTime(time.getHourOfDay(), 
time.getMinuteOfHour(), time.getSecondOfMinute())) : null;

DateTime and LocalTime are from joda

Jayani Sumudini
  • 1,409
  • 2
  • 22
  • 29