0

How can I store dates in this format 14-04-2017 in my entities?

But I have to parse it from a String.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
    today = dateFormat.parse("2017-04-14");
} catch (ParseException e) {
    //catch exception
}

And I get: Fri Apr 14 00:00:00 CEST 2017

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
user
  • 4,410
  • 16
  • 57
  • 83
  • and what you expected to get ? – Youcef LAIDANI Apr 14 '17 at 15:09
  • 1
    14-04-2017 or 2017-04-14 – user Apr 14 '17 at 15:11
  • Use the `SimpleDateFormatter.format` method. – Compass Apr 14 '17 at 15:14
  • You probably mean you got `Fri Apr 14 00:00:00 CEST 2017` when you printed `today`. That would be correct because you actually see `today.toString()` as created by the [`toString()`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toString--) method of `Date` class. – Thomas Fritsch Apr 14 '17 at 15:15
  • There are lot of questions about `SimpleDateFormat` in SO, for instance [here](http://stackoverflow.com/questions/1725578/parsing-a-date-in-java/1725595#1725595), may I advise to give them a look ? – danidemi Apr 14 '17 at 17:47
  • Or `LocalDate.toString()` (gives `2017-04-14`). – Ole V.V. Apr 14 '17 at 19:26
  • What I meant to say was, since you only want the date, not the time, if you can use Java 8, `LocalDate` fits your need better than the outdated `Date` class. You will also want to make sure that your database column holds a date only, not a date and time. – Ole V.V. Apr 15 '17 at 19:43
  • 1
    No idea what you mean by "this format". If you have a Date (field) then it can be stored as a DATE (column). If you want to store them as a String then that is the only place a "format" matters! So define your problem – Neil Stockton Apr 16 '17 at 10:28

2 Answers2

3

tl;dr

LocalDate.parse( "2017-04-14" )

Using java.time

You are using the wrong classes.

Avoid the troublesome old legacy classes such as Date, Calendar, and SimpleDateFormat. Now supplanted by the java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

ISO 8601

Your input happens to comply with the ISO 8601 standard. The java.time classes use those standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate ld = LocalDate.parse( "2017-04-14" );

To generate a string in the same format, call toString.

String output = ld.toString() ;

Do not conflate strings with date-time objects. Date-time objects can be created by parsing a string. Date-time objects can generate strings to represent their value. But the string and the date-time are always separate and distinct.

Your first line in the Question uses a different format. I hope that was a mistake. You should stick with the ISO 8601 formats whenever possible, especially when serializing for data exchange.

If you really want other formats, search for DateTimeFormatter. Already covered many many times on Stack Overflow.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

Try below code

  1. import

    import com.mysql.jdbc.StringUtils;
    import java.sql.Timestamp;    
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    
  2. yourObjectModel and yourObjectTO Object

    @Column(name = "date")
    private Timestamp date;
    
    private String date;
    
  3. parse the input

    if (!StringUtils.isNullOrEmpty(yourObjectTO.getDate())) {
        yourObjectModel.setDate(convertStringToTimestamp(yourObjectTO.getDate()));
    }
    
  4. util method for conversion

    public static Timestamp convertStringToTimestamp(String strDate) {      
        String format = "dd/MM/yyyy";
        if(strDate.contains("-")) {
            format = "yyyy-MM-dd";
        }
        DateTimeFormatter DATE_TME_FORMATTER =  
            new DateTimeFormatterBuilder().appendPattern(format)
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter();
        LocalDate dt = LocalDate.parse(strDate.substring(0, 10), DATE_TME_FORMATTER);
        Timestamp timestamp = Timestamp.valueOf(dt.atStartOfDay());
        return timestamp;
    }
    
Yusuf Kapasi
  • 577
  • 2
  • 9