-1

I have the date of the following Format :

(java.util.Date) Wed Sep 05 12:30:00 IST 2018

and I need to convert this date to the dd-MMM-yy.

I used the below code:

public static String converToSqlDate(Date date) {
        String strDate = null;
        java.text.SimpleDateFormat sdf = new SimpleDateFormat(WSRDConstants.SQL_FORMAT); //dd-MMM-yy
        if (date != null) {
            strDate = sdf.format(date);
        } else {
            return null;
        }
        return strDate;
    }

But, when I try to persis the date in DB, its not doing so and saving it as a null params. I am using a JDBC for Persisting the data to the DB.

Ashfaque Rifaye
  • 1,041
  • 3
  • 13
  • 22
  • `strDate` is a String. How the database may get to take it as a date depends completely on your DML. Can you show your actual statement? – ernest_k Sep 05 '18 at 15:46

1 Answers1

2

tl;dr

Use objects, not text, to persist a date value to the database.

Convert your obsolete Date to a modern Instant. Send to database with JDBC 4.2.

myPreparedStmt.setObject( 
    … , 
    myJavaUtilDate         // Avoid the terrible legacy date-time classes. Use only java.time classes. 
    .toInstant()           // Convert from legacy class to modern. Both represent a moment in UTC. 
    .atZone(               // Adjust from UTC to the wall-clock time used by the people of a particular region, a time zone. 
        ZoneId.of( "Africa/Tunis" )
    )                      // Returns a `ZonedDateTime` object. 
    .toLocalDate()         // Extract only the date, without time-of-day and without time zone. Returns a `LocalDate` object. 
) ;

Smart objects, not dumb strings

When working with date-time values, use date-time types, not String.

As of JDBC 4.2, we can exchange java.time objects with the database. No need to use the terrible old legacy classes such as java.sql.Date and java.sql.Timestamp, and java.util.Date

If you have a java.util.Date object, immediately convert to its modern replacement, java.time.Instant. To convert, call new methods on the old classes.

Instant instant = myJavaUtilDate.toInstant() ; 

Both the legacy class and Instant represent a moment in UTC. To determine a date or a time-of-day for that moment, we must adjust into our desired/expected time zone. For any given moment, the date and time vary around the globe by zone.

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

Extract the date-only.

LocalDate ld = zdt.toLocalDate() ;

Send to the database.

myPreparedStmt.setObject( … , ld ) ;

Retrieval:

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

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
  • Hi, can you just brief me out what are the difference in using Date class and Instance Class for Date Persistence? Also can you please help me out on how to manage the persistence of the Date and Time so that it will be appropriate when the application is managed in another country (of various TimeZones). How to handle this kind of Scenarios? – Ashfaque Rifaye Sep 06 '18 at 04:35
  • @AshfaqueRifaye I have covered all that many many times already on Stack Overflow. Use a search engine to search Stack Overflow, as the built-in search feature is anemic and biased towards Questions over Answers. Search for the class names such as ["java jdbc instant"](https://duckduckgo.com/?q=site%3Astackoverflow.com+java+jdbc+Instant&t=hj&ia=web). Look for the *java.time* classes such as Instant, OffsetDateTime, ZonedDateTime, ZoneId, and ZoneOffset. Generally, just use Instant to exchange a moment with your database, as shown above. And, never use java.util.* or java.sql.*, just java.time. – Basil Bourque Sep 06 '18 at 05:14
  • https://stackoverflow.com/questions/6567923/timezone-conversion I have checked with this Link where you have provided your valuable suggestions. What I found is,for each and every timezone, we are intended to provide the Zone Name for eg. ZoneId zoneMontréal = ZoneId.of("America/Montreal"); (or) DateTimeZone timeZoneLondon = DateTimeZone.forID( "Europe/London" ); Is there anyway to get the Zone Name/ID directly based on where the User Logs the application instead of manually providing the Zone Name? – Ashfaque Rifaye Sep 06 '18 at 05:25
  • @AshfaqueRifaye Keep studying. You will learn to use UTC and the `Instant` class as I have already shown three times on this page. Search for my name and the word “parochial” to learn to think and work in UTC. – Basil Bourque Sep 06 '18 at 05:31
  • Ok sure. I have one more doubt in the above method. So, I have a Date of LocalDate format. The default format is the ISO format (yyyy-mm-dd). But, I need to return this LocalDate in the format of "dd-MMM-yyyy". How to achieve this without converting to String? Any suggestions. – Ashfaque Rifaye Sep 06 '18 at 07:14
  • @AshfaqueRifaye Date-time objects such as `java.util.Date` and `java.time.LocalDate` do not have a “format”. They can parse and generate text in `String` objects in a certain format. Again, this has been covered hundreds, perhaps thousands, of times on Stack Overflow. Search, read, study. – Basil Bourque Sep 06 '18 at 15:17