Search code examples
javaspring-bootlocaldate

LocalDate.now() returns wrong date


I've written a REST Service using Spring Boot. The REST Service is running on a PaaS. I have an endpoint to create new items in a DB table. Every time a new item is created I assign it a created date by using:

LocalDate currentDate = LocalDate.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

sql = "INSERT INTO my_table (" +
                "code, " +
                "description, " +
                "created_date)" +
                "VALUES (?, ?, ?)";

        jdbcTemplate.update(
                sql,
                new Object[]{
                        code,
                        description,
                        currentDate.format(df)
                }
        );

The problem is that the currentDate.format(df) comes out as 17th of October 2017 while today is 24th of October 2017. The only connection I can see to the 17th of October is that it is the last time I restarted the JAR file on the PaaS. I've SSH into the environment where the service is running and run date. It returns Tue Oct 24 17:54:23 UTC 2017. Any ideas what I'm doing wrong?


Solution

  • From what you are saying I guess your problem is that the currentDate is initialized at the start of your program and then you keep saving that same date, you probably have something like this

    LocalDate currentDate = LocalDate.now();
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public void insert(String code, String description) {
      sql = "INSERT INTO my_table (" +
                    "code, " +
                    "description, " +
                    "created_date)" +
                    "VALUES (?, ?, ?)";
    
            jdbcTemplate.update(
                    sql,
                    new Object[]{
                            code,
                            description,
                            currentDate.format(df)
                    }
            );
    }
    

    You should move the instantiation of the date inside the method

    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public void insert(String code, String description) {
      LocalDate currentDate = LocalDate.now();
      sql = "INSERT INTO my_table (" +
                    "code, " +
                    "description, " +
                    "created_date)" +
                    "VALUES (?, ?, ?)";
    
            jdbcTemplate.update(
                    sql,
                    new Object[]{
                            code,
                            description,
                            currentDate.format(df)
                    }
            );
    }