david blaine
david blaine

Reputation: 5927

How to get particular parts of a DateTime object?

I have a DateTime object DT which stores current time. When I print DT, I want it to only print the time part, ie HH-MM-SS (H = hours, M = minutes, S = seconds) and ignore the date part.

How can I do this ? For that matter, is it even possible to create a date time object which will only contain HH-MM-SS and nothing related to date ? If that is true, then I can simply print it instead of extracting the HH-MM-SS part.

Thanks.

Upvotes: 0

Views: 216

Answers (3)

Vamsi Mohan Jayanti
Vamsi Mohan Jayanti

Reputation: 666

With Java you can do it like this

Date obj = new Date() ;
        System.out.println(new SimpleDateFormat("hh:mm:ss").format(obj)) ;

but it could be an expensive call. But jodatime gives LocalTime which you can try out.

Upvotes: 0

Munish Thakur
Munish Thakur

Reputation: 1006

You can use Java date formatter which is in java.util.Date package.

Like :

  Date todaysDate = new java.util.Date();

  1. // Formatting date into  yyyy-MM-dd HH:mm:ss e.g 2008-10-10 11:21:10
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     String formattedDate = formatter.format(todaysDate);

  2. // Formatting date into  yyyy-MM-dd e.g 2008-10-10 
     formatter = new SimpleDateFormat("yyyy-MM-dd");
     formattedDate = formatter.format(todaysDate);

  3. // Formatting date into  MM/dd/yyyy e.g 10/10/2008 
    formatter = new SimpleDateFormat("MM/dd/yyyy");
    formattedDate = formatter.format(todaysDate);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502096

If you only want the time, you should use a LocalTime instead of a DateTime. You can use DateTime.toLocalTime() to get the time part of an existing DateTime.

If you actually want to keep the DateTime but only reveal the time part when formatting, you can create a DateTimeFormatter with a pattern which only includes the time parts, but I'd usually consider this a design smell.

Upvotes: 3

Related Questions