【问题标题】:How to use LocalDateTime如何使用本地日期时间
【发布时间】:2020-06-19 15:12:20
【问题描述】:

解决 LocalDateTime 错误的正确方法是什么?

我是spring的新手,因此我试图在网上寻找解决这个问题的方法,但我无法解决。

这是我的实体

package com.reserve.entities;

import java.time.LocalDateTime;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

@Entity
public class Flight extends AbstractEntity {


    private String flightNumber;
    private String operatingAirlines;
    private String departureCity;
    private String arrivalCity;


    @DateTimeFormat(iso=ISO.DATE)
    private Date dateOfDeparture;


    @Column(name="estimatedDepartureTime",columnDefinition="TIMESTAMP")      
    private LocalDateTime estimatedDepartureTime;

    public String getFlightNumber() {
        return flightNumber;
    }
    public void setFlightNumber(String flightNumber) {
        this.flightNumber = flightNumber;
    }
    public String getOperatingAirlines() {
        return operatingAirlines;
    }
    public void setOperatingAirlines(String operatingAirlines) {
        this.operatingAirlines = operatingAirlines;
    }
    public String getDepartureCity() {
        return departureCity;
    }
    public void setDepartureCity(String departureCity) {
        this.departureCity = departureCity;
    }
    public String getArrivalCity() {
        return arrivalCity;
    }
    public void setArrivalCity(String arrivalCity) {
        this.arrivalCity = arrivalCity;
    }
    public Date getDateOfDeparture() {
        return dateOfDeparture;
    }
    public void setDateOfDeparture(Date dateOfDeparture) {
        this.dateOfDeparture = dateOfDeparture;
    }

    public LocalDateTime getEstimatedDepartureTime() {
        return estimatedDepartureTime;
    }
    public void setEstimatedDepartureTime(LocalDateTime estimatedDepartureTime) {
        this.estimatedDepartureTime = estimatedDepartureTime;
    }
    @Override
    public String toString() {
        return "Flight [flightNumber=" + flightNumber + ", operatingAirlines=" + operatingAirlines + ", departureCity="
                + departureCity + ", arrivalCity=" + arrivalCity + ", dateOfDeparture=" + dateOfDeparture
                + ", estimatedDepartureTime=" + estimatedDepartureTime + "]";
    }   

}

这是我的控制器。

我不确定需要哪些信息。

如果有更多信息可以提供帮助,请告诉我。


package com.reserve.controllers;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.reserve.entities.Flight;
import com.reserve.repository.FlightRepository;

@Controller
public class FlightController {

    @Autowired
    private FlightRepository flightRepository;

    @RequestMapping("findFlights")
    public String findFlights(
            @RequestParam("from")String from, 
            @RequestParam("to")String to, 
            @RequestParam("departureDate")
            @DateTimeFormat(pattern = "MM-dd-yyyy")
            Date departureDate,
            Model model) 
    {
        List<Flight> flights = flightRepository.findFlights(from,to,departureDate);

        model.addAttribute("flights", flights);
        return "displayFlights";
    }

    @RequestMapping("/ourFlights")
    public String ourFlights() {
        return "ourFlights";
    }

    @RequestMapping(value="/add", method=RequestMethod.POST)
    public String addFlights(@ModelAttribute("flight")Flight flight,Model model) {
        Flight save = flightRepository.save(flight);
        String msg = save.getFlightNumber() + " from " + save.getDepartureCity() + " to "
                + save.getArrivalCity() + " has been added.";
        model.addAttribute("msg", msg);
        return "ourFlights";
    }
}

这是我的 JSP 文件


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
     <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Money Wise</title>
<link rel="stylesheet" href="/reserve/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/reserve/css/custom.css"/>
</head>
<body>
<div class="container">
    <div id="body">
        <nav class="navbar navbar-expand-lg navbar-light bg-lights">
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
              <li class="nav-item active">
                <a class="nav-link" href="home">Home <span class="sr-only">(current)</span></a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Ideology</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Faq</a>
              </li>
               <li class="nav-item">
                <a class="nav-link" href="#">News</a>
              </li>
            </ul>
            <form class="form-inline my-2 my-lg-0 pull-right">
              <input class="form-control mr-sm-2" type="search" placeholder="Search">
              <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
          </div>
        </nav>
        <!-- Site Body -->
        <div  id="content" class="container">
            <div class="row">

                <div id="leftMain" class="col-sm-3">
                <img src="/reserve/images/jim.png"width=100%/>

                </div>
                <div id="mainBody" class="col-sm-9 ">
                    <h2>Add Flights</h2>

                    <form action="add" method="post">
                        <div class="form-group">
                            <label for="flightNumber">Flight number</label>
                            <input type="text" class="form-control" name="flightNumber" placeholder="Flight number"/>
                        </div>
                        <div class="form-group">
                            <label for="operatingAirlines">Operating airlines</label>
                            <input type="text" class="form-control" name="operatingAirlines" placeholder="Operating airlines"/>
                        </div>
                        <div class="form-group">
                            <label for="departureCity">Departure city</label>
                            <input type="text" class="form-control" name="departureCity" placeholder="Departure city"/>
                        </div>
                        <div class="form-group">
                            <label for="arrivalCity">Arrival city</label>
                            <input type="text" class="form-control" name="arrivalCity" placeholder="Arrival city"/>
                        </div>

                        <div class="form-group">
                            <label for="dateOfDeparture">Date of departure</label>
                            <input type="Date" class="form-control" name="dateOfDeparture" placeholder="Date of departure"/>
                        </div>

                        <div class="form-group">
                            <label for="estimatedDepartureTime">Estimated departure time</label>
                            <input type="datetime-local" class="form-control" name="estimatedDepartureTime" placeholder="Estimated departure time"/>
                        </div>
                        <button type="submit" class="btn btn-primary">Save</button>
                    </form>

                </div>
            </div>
        </div>
    </div>

</div>
    <!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="/reserve/js/bootstrap.min.js"></script>
</body>
</html>

这是我得到的错误


Field error in object 'flight' on field 'estimatedDepartureTime': rejected value [2020-06-20T17:35]; codes 

[typeMismatch.flight.estimatedDepartureTime,typeMismatch.estimatedDepartureTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 

codes [flight.estimatedDepartureTime,estimatedDepartureTime]; arguments []; default message [estimatedDepartureTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'estimatedDepartureTime'; 

nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type

 [java.lang.String] to type [@javax.persistence.Column java.time.LocalDateTime] for value '2020-06-20T17:35'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-06-20T17:35]]]

``````

【问题讨论】:

  • 我看不到错误?你有例外吗?如果是,请添加堆栈跟踪,否则请描述您得到的错误
  • 感谢您的快速回复。
  • 我现在添加了错误
  • 因为你可以使用java.time,LocalDateTime所属的现代Java日期和时间API,我建议你使用LocalDate作为出发日期,ZonedDateTime在时区预计出发时间的出发机场。

标签: spring-boot hibernate spring-mvc


【解决方案1】:

您可以尝试使用Spring The Formatter SPI 将表示为String 的日期转换为LocalDateTime,反之亦然。

public class DateTimeFormatters {

public static class LocalDateTimeFormatter implements Formatter<LocalDateTime> {

        @Override
        public LocalDateTime parse(String pattern, Locale locale) throws ParseException {
            return LocalDateTime.parse(pattern, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }

        @Override
        public String print(LocalDateTime object, Locale locale) {
            return object.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
    }
}

并注册您的格式化程序,例如

public class ApplicationConfig implements WebMvcConfigurer {
  ...
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new DateTimeFormatters.LocalDateTimeFormatter());
    }
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-25
    • 2016-05-23
    • 2022-11-14
    • 2011-06-01
    • 2014-05-31
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多