How to accept the time parameters passed in by the front-end date picker in the java backend

If the front end uses a date picker and passes the selected date to the Java backend, then the Java backend can use the following method to receive the date parameter:

  1. Declare a formal parameter in the back-end method, the type is java.util.Dateor java.time.LocalDate, and then the date parameter passed in the front-end request will be automatically encapsulated into the corresponding date object. For example:
public void handleDate(Date date) {
  // 处理日期对象
}
  1. Declare a formal parameter in the back-end method, the type is a string, and then the date parameter passed in in the front-end request is a string, and then use the corresponding conversion method in the back-end to convert the string into a date object. For example:
public void handleDate(String dateString) {
  // 使用SimpleDateFormat类将字符串转换成日期对象
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  Date date = format.parse(dateString);
  // 处理日期对象
}

Please note that if the format of the date string passed in by the front end does not match the format in the conversion method of the back end, then conversion errors may occur.

In addition, a new time and date API is also provided in Java8, which can use java.time.LocalDatetypes to represent dates. You can convert a string to LocalDatean object using the following methods:

```java public void handleDate(String dateString) { // Use LocalDate.parse method

Guess you like

Origin blog.csdn.net/weixin_35755562/article/details/128866294