📌  相关文章
📜  Java中的MonthDay解析(CharSequence,DateTimeFormatter)方法

📅  最后修改于: 2022-05-13 01:54:59.484000             🧑  作者: Mango

Java中的MonthDay解析(CharSequence,DateTimeFormatter)方法

Java中MonthDay类的parse(CharSequence text, DateTimeFormatter formatter)方法用于使用特定格式化程序从文本字符串中获取MonthDay的实例。
句法:

public static MonthDay parse(
    CharSequence text, 
    DateTimeFormatter formatter)

参数:此方法接受

  • 文本作为参数来解析和
  • formatter作为参数使用。

返回值:该方法返回解析后的month-day

异常:如果无法解析文本,此方法将引发DateTimeParseException

下面的程序说明了Java中 MonthDay 的 parse(CharSequence text, DateTimeFormatter formatter) 方法:

方案一:

// Java program to demonstrate
// MonthDay.parse(CharSequence text,
// DateTimeFormatter formatter) method
  
import java.time.*;
import java.time.temporal.*;
import java.time.format.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // apply ofpattern() method
        // of DateTimeFormatter class
        DateTimeFormatter datetimeformatter
            = DateTimeFormatter.ofPattern("--MM-dd");
  
        // apply parse(CharSequence text,
        // DateTimeFormatter formatter) method
        // of MonthDay class
        MonthDay monthday = MonthDay.parse(
            "--05-09", datetimeformatter);
  
        // print monthday
        // in mm-dd format
        System.out.println("MonthDay: "
                           + monthday);
    }
}
输出:
MonthDay: --05-09

方案二:

// Java program to demonstrate
// MonthDay.parse(CharSequence text,
// DateTimeFormatter formatter) method
  
import java.time.*;
import java.time.temporal.*;
import java.time.format.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // apply ofpattern() method
        // of DateTimeFormatter class
        DateTimeFormatter datetimeformatter
            = DateTimeFormatter.ofPattern("--dd-MM");
  
        // apply parse(CharSequence text,
        // DateTimeFormatter formatter) method
        // of MonthDay class
        MonthDay monthday = MonthDay.parse(
            "--05-09", datetimeformatter);
  
        // print monthday
        // in dd-mm format
        System.out.println("MonthDay: "
                           + monthday);
    }
}
输出:
MonthDay: --09-05

参考资料: https://docs.oracle.com/javase/10/docs/api/java Java .lang.CharSequence, Java Java)