0

I have a jCalendar which method jCalendar.getDate() returns a date in the following form: Mon Apr 06 11:10:00 PDT 2015 But I want it in the format yyyy-MM-dd to insert into a MySQL database I tried the following code but it throws a ParseException

Date fecha = jFecha.getDate(); //this returns Mon Apr 06 11:10:00 PDT 2015
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            fecha = format.parse(fecha.toString());

This code returns a Unparseable date: "Mon Apr 06 11:10:00 PDT 2015" error. I've tried setting the dateFormatString property of the jCalendar to yyyy-MM-dd but it still returns the same full date with seconds and everything.

Any idea of what I'm doing wrong?

Ces
  • 343
  • 3
  • 13
  • 2
    Dont't use `toString()`. Directly use `fecha` as the parameter. – user432 Apr 06 '15 at 18:21
  • You are trying to parse a date from its string representation using the date format specified. No wonder it doesn't work! I think what you want is format the date into a string? – Giovanni Botta Apr 06 '15 at 18:26
  • 2
    BTW a date does not have a format, you format a date to obtain a string, so your `fecha` object does not have any embedded format information, if that's what you're thinking. – Giovanni Botta Apr 06 '15 at 18:28
  • 1
    And I'ts better to use `java.sql.Date` to save dates, and not `java.util.Date`, which I think it's your case, you will need get the date as `util.Date` or `String` and convert into a `sql.Date` – Joao Evangelista Apr 06 '15 at 18:41
  • I haven't saved the date yet, but regardless of the format of my java Date using java.sql.Date will work? I also tried `fecha = format.parse(fecha);` but it marks an error of `Incompatible types: Date cannot be converted to String` – Ces Apr 06 '15 at 19:24
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 18 '17 at 00:50

3 Answers3

1

First of all, a Date object does not have a format by itself. You cannot have "a Date object in the format yyyy-MM-dd" - there's no such thing as a Date object in a certain format.

How are you inserting the Date in the database - are you using JDBC? If yes, then use a PreparedStatement and pass a java.sql.Date object as the parameter. Like this:

PreparedStatement ps = connection.prepareStatement(
        "insert into mytable (name, date) values (?, ?)");

ps.setParameter(1, "somename");
ps.setParameter(2, new java.sql.Date(fecha.getTime()));

ps.executeUpdate();
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • I'll try that. I was unsure of passing a java Date to the method where I insert statements on the database, but in that method I do use `java.sql.Date`, thanks! – Ces Apr 06 '15 at 19:28
0

tl;dr

I want it in the format yyyy-MM-dd to insert into a MySQL database

No need to generate or parse a String. With a Date object in hand, convert to a java.time.Instant, apply a time zone ZoneId to generate a ZonedDateTime, and extract a LocalDate. Pass the LocalDate via JDBC 4.2 and later.

myPreparedStatement.setObject( 
    … ,
    myJavaUtilDate.toInstant()
                  .atZone( ZoneId.of( "Pacific/Auckland" ) )
                  .toLocalDate() ,
    LocalDate.class
)

Details

jCalendar.getDate() returns a date in the following form: Mon Apr 06 11:10:00 PDT 2015

The old Date & Calendar classes have many flaws. One of the flaws is the poor design decision to have the Date::toString method apply a time zone during the process of generating the string. This creates the illusion of an assigned time zone when actually the Date value is always in UTC.

Avoid the troublesome old date-time classes. They are now legacy, supplanted by the java.time classes.

Convert that Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant() ;

For a date-only value, you must decide on time zone. For example, a few minutes after midnight in Paris France is a new day while in Montréal Québec is still “yesterday”. So you must specify the context of a zone to determine the intended date.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

For a date-only value, without time-of-day and without time zone, extract a LocalDate.

LocalDate ld = zdt.toLocalDate() ;

To exchange date-time values with a database, use date-time objects rather than mere strings. No need for you to generate or parse that problematic string.

If your JDBC driver complies with JDBC 4.2 and later, you can directly use the java.time types rather than the legacy java.sql types.

myPreparedStatement.setObject ( 1 , ld ); // Automatic detection and conversion of data type.

…and…

LocalDate ld = myResultSet.getObject ( "my_date_column_" , LocalDate.class ); 

For more discussion, see Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2.


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.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-1

Do this instead:

Date fecha = jFecha.getDate(); //this returns Mon Apr 06 11:10:00 PDT 2015
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        fecha = format.format(fecha);

Actually you are supposed to use format instead of parse

Bwire
  • 1,181
  • 1
  • 14
  • 25