0

When a user select a date/time, I need to store it in the DB as a timestamp. I would like to parse the string (date/time) to timestamp (if it is the best approach). However, I cannot figure it out!

Here's what I have so far:

Java

protected String startDate

@Column(name="start_date")
public String getStartDate() {
    return startDate;
}
public void setStartDate(String startDate) {
    this.startDate = startDate;
}

@Override
public boolean equals(Object obj) {

    if (startDate == null) {
        if (other.startDate != null)
            return false;
    } else if (!startDate.equals(other.startDate))
        return false;
}

JS

// date picker
$('.datepicker').datetimepicker({
    controlType: 'select',
    dateFormat: 'M d, yy',
    timeFormat: 'h:m:s TT'
});

HTML

<input id="project_start_date" class="datepicker" type="text" name="project.startDate" value="${project.startDate}"/>

Thank you in advance!

  • possible duplicate of [Java string to date conversion](http://stackoverflow.com/questions/4216745/java-string-to-date-conversion) and many many others. Please search StackOverflow before posting. – Basil Bourque Aug 04 '14 at 23:09

1 Answers1

0

In our current java projects we do this:

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="start_date")
    private Date startDate;

This stores dates as timestamps. It works perfectly with PostgreSQL, MySQL and H2, and I assume with other DB managers would be fine as well.

And by the way, if you need to parse a String containing a date to a Date, you can do the following:

    // Set your date format
    SimpleDateFormat formatter = new SimpleDateFormat("M d, yy h:m:s TT");

    String dateInString = <YOUR DATE>
    try {
        Date date = formatter.parse(dateInString);
    } catch (ParseException e) {
        // Handle the format exception
    }
ipinyol
  • 336
  • 2
  • 12