1

I am trying to use a getter to get the LocalTime in HH:mm anytime it is called. As it stands right now it is:

private LocalTime time;

public LocalTime getTime() {
    return time;
}

I would like for it to return the time in HH:mm, because as it stands right now it is HH:mm:SS.s. I am trying to mess with date time formatter, but I can't figure it out. Here is what I have:

private LocalTime time;

public LocalTime getTime() {
   DateTimeFormatter formatDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
   LocalTime localFormattedTime = LocalTime.parse(time, formatDateTime);
   return localFormattedTime;
}
bad_coder
  • 11,289
  • 20
  • 44
  • 72
JWingert
  • 111
  • 1
  • 8
  • 2
    Are you want to format LocalTime data into String ? – Eklavya Jul 21 '20 at 20:10
  • Does it need to be formatted into a String to work with DateTimeFormatter? I tried formatting it into a String originally and couldn't get that to work either. – JWingert Jul 21 '20 at 20:15
  • Does this answer your question? [Parsing timestamp as LocalDateTime](https://stackoverflow.com/questions/54941872/parsing-timestamp-as-localdatetime) – Ole V.V. Jul 22 '20 at 05:17

4 Answers4

3

The answer by YCF_L is correct and to-the-point. The reason why I have written this answer is I have seen similar kind of questions (why my date/time is not being printed in a custom way) being asked every now and then.

Note that LocalDate, LocalTime, LocalDateTime etc. each have their own toString()implementation and no matter what you do, whenever you print their object, their toString() method will be called and thus always their default representation will be printed. If you want these objects to be printed in a custom way, you have two options:

  1. You get their elements (e.g. year, month and day from an object of LocalDate) and print them by arranging in your custom way.
  2. Use a formatter class e.g. (the modern DateTimeFormatter or the legacy SimpleDateFormat) and get a string representing the date/time object in a custom way.

To make your code reusable and clean, you prefer the second approach.

The following example illustrates the same:

class Name {
    private String firstName;
    private String lastName;

    public Name() {
        firstName = "";
        lastName = "";
    }

    public Name(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public String toString() {
        return firstName + " " + lastName;
    }
}

class NameFormatter {
    // Returns a name (e.g. First Last) as F. Last
    public static String patternIntialsLast(Name name) {
        if (name.getFirstName().length() > 1) {
            return name.getFirstName().charAt(0) + ". " + name.getLastName();
        }
        return name.toString();
    }

    // Returns a name (e.g. First Last) as Last F.
    public static String patternLastInitials(Name name) {
        if (name.getFirstName().length() > 1) {
            return name.getLastName() + " " + name.getFirstName().charAt(0) + ".";
        }
        return name.toString();
    }

    // Returns a name (e.g. First Last) as Last First
    public static String patternLastIFirst(Name name) {
        return name.getLastName() + ", " + name.getFirstName();
    }
}

public class Main {
    public static void main(String[] args) {
        Name name = new Name("Foo", "Bar");
        System.out.println("Default format:");
        System.out.println(name);// It will always print what name.toString() returns

        // If you want to print name in different formats use NameFormatter e.g.
        System.out.println("\nIn custom formats:");
        String strName1 = NameFormatter.patternIntialsLast(name);
        System.out.println(strName1);

        String strName2 = NameFormatter.patternLastIFirst(name);
        System.out.println(strName2);

        String strName3 = NameFormatter.patternLastInitials(name);
        System.out.println(strName3);
    }
}

Output:

Default format:
Foo Bar

In custom formats:
F. Bar
Bar, Foo
Bar F.

Now, go through the answer by YCF_L again and this time, you know that you have to implement your method as follows:

public String getTime() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
    return formatter.format(ldt);
}

A quick demo:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main {
    // Now
    static LocalDateTime ldt = LocalDateTime.of(LocalDate.now(), LocalTime.now());

    public static void main(String[] args) {
        System.out.println(getTime());
    }

    public static String getTime() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        return formatter.format(ldt);
    }
}

Output:

22:23
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2
  1. LocalTime not have date part it have only the time part
  2. You can't have a specific format for LocalDate, LocalTime, LocalDateTime, it use a standard format and you can't change it.
  3. If you want a specific format then you have to use String and not LocalDate, LocalTime, LocalDateTime.
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

Try with this. I d

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH.mm");
 
LocalTime today = LocalTime.now();
 
String timeString = today.format(formatter);    //12.38
Hang Pham
  • 11
  • 1
0

Try something like this:

String localTimeString = "23:59:59";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
try {
    TemporalAccessor ta = dtf.parse(localTimeString);
    LocalTime lt = LocalTime.from(ta);
    LOGGER.info("lt: {}", lt);
} catch (RuntimeException re) {
    LOGGER.error("Unable to parse local time string: [{}]", localTimeString, re);
}

Consult the Java documentation on DateTimeFormatter for details on the patterns it supports.

You can also use the DateTimeFormatter to format a LocalTime back into string form, like this:

String localTimeAsString = dtf.format(lt)
LOGGER.info("LocalTime as string: {}", localTimeAsString);
Jim Tough
  • 14,843
  • 23
  • 75
  • 96