本文共 2439 字,大约阅读时间需要 8 分钟。
format() method is available in java.time package.
format()方法在java.time包中可用。
format() method is used to format this LocalDate object by using the given DateTimeFormatter object.
format()方法用于通过使用给定的DateTimeFormatter对象来格式化此LocalDate对象。
format() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
format()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
format() method may throw an exception at the time of formatting this object.
在格式化此对象时, format()方法可能会引发异常。
DateTimeException: This exception may throw when getting any error during formatting.
DateTimeException :格式化期间发生任何错误时,可能会引发此异常。
Syntax:
句法:
public String format(DateTimeFormatter dt_formatter);
Parameter(s):
参数:
DateTimeFormatter dt_formatter – represents the formatter to format this object.
DateTimeFormatter dt_formatter –表示用于格式化此对象的格式化程序。
Return value:
返回值:
The return type of this method is String, it returns date formatted by the given formatter of this LocalDate object.
此方法的返回类型为String ,它返回由此LocalDate对象的给定格式化程序格式化的日期。
Example:
例:
// Java program to demonstrate the example // of format(DateTimeFormatter dt_formatter)// method of LocalDateimport java.time.*;import java.time.format.*;public class FormatOfLocalDate { public static void main(String args[]) { // Instantiates two LocalDate LocalDate l_da1 = LocalDate.parse("2007-04-04"); LocalDate l_da2 = LocalDate.now(); // Display l_da1,l_da2 System.out.println("LocalDate l_da1 and l_da2: "); System.out.println("l_da1: " + l_da1); System.out.println("l_da2: " + l_da2); System.out.println(); // Here, this method formats this date // by using the pattern "dd-MMM-yyyy" DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy"); String format = l_da1.format(dtf); // Display format System.out.println("l_da1.format(dtf): " + format); // Here, this method formats this date by // using the pattern "dd/MM/yyyy" dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy"); format = l_da2.format(dtf); // Display format System.out.println("l_da2.format(dtf): " + format); }}
Output
输出量
LocalDate l_da1 and l_da2: l_da1: 2007-04-04l_da2: 2020-05-29l_da1.format(dtf): 04-Apr-2007l_da2.format(dtf): 29/05/2020
翻译自:
转载地址:http://bytzd.baihongyu.com/