如何正确将LocalTime格式化为HH:MM?

huangapple go评论51阅读模式
英文:

How to properly format LocalTime to HH:MM?

问题

我正在尝试使用getter方法在每次调用时获取HH:mm格式的LocalTime。目前的情况如下:

private LocalTime time;

public LocalTime getTime() {
    return time;
}

我希望它以HH:mm格式返回时间,因为目前的格式是HH:mm:SS.s。我正在尝试使用日期时间格式化程序进行调整,但我无法弄清楚。以下是我的代码:

private LocalTime time;

public LocalTime getTime() {
   DateTimeFormatter formatDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
   LocalTime localFormattedTime = LocalTime.parse(time, formatDateTime);
   return localFormattedTime;
}
英文:

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;
}

答案1

得分: 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

英文:

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

答案2

得分: 2

  1. LocalTime没有日期部分,只有时间部分。
  2. 你不能为LocalDateLocalTimeLocalDateTime指定特定的格式,它们使用标准格式,不能更改。
  3. 如果你想要特定的格式,那么你需要使用String而不是LocalDateLocalTimeLocalDateTime
英文:
  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.

答案3

得分: 1

尝试使用这个。我已经提取了代码部分,以下是翻译好的内容:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH.mm");

LocalTime today = LocalTime.now();

String timeString = today.format(formatter);    //12.38
英文:

Try with this. I d

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;HH.mm&quot;);
 
LocalTime today = LocalTime.now();
 
String timeString = today.format(formatter);    //12.38

<!-- end snippet -->

答案4

得分: 0

尝试类似以下方式:

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("无法解析本地时间字符串: [{}]", localTimeString, re);
}

请参考Java文档中关于DateTimeFormatter支持的模式的详细信息。

您还可以使用DateTimeFormatter将LocalTime格式化为字符串形式,如下所示:

String localTimeAsString = dtf.format(lt);
LOGGER.info("LocalTime as string: {}", localTimeAsString);
英文:

Try something like this:

String localTimeString = &quot;23:59:59&quot;;
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(&quot;HH:mm:ss&quot;);
try {
	TemporalAccessor ta = dtf.parse(localTimeString);
	LocalTime lt = LocalTime.from(ta);
	LOGGER.info(&quot;lt: {}&quot;, lt);
} catch (RuntimeException re) {
	LOGGER.error(&quot;Unable to parse local time string: [{}]&quot;, 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(&quot;LocalTime as string: {}&quot;, localTimeAsString);

huangapple
  • 本文由 发表于 2020年7月22日 04:08:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63022313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定