Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.sql.Date formatting

public static void main(String[] args) {
    java.util.Date utilDate = new java.util.Date();
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    System.out.println("utilDate:" + utilDate);
    System.out.println("sqlDate:" + sqlDate);
 }

I use this code part and output like this:

2013/06/14 12:06:11
2013-06-14

I want the output which has date and time data. The parameter of method needs java.sql.Date format. that's why I must convert or change format of sqlDate. How can I solve it?

NOTE

PreparedStatement insertStmt=null;
insertStmt.setDate(parIndex, java.sql.Date);

That's why I want java.sql.Date format

like image 284
kamal Avatar asked Jun 14 '13 07:06

kamal


People also ask

How do you format a date in Java?

Creating A Simple Date FormatString pattern = "yyyy-MM-dd" ; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The specified parameter “pattern” is the pattern used for formatting and parsing dates.

What is sql date in Java?

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE , the millisecond values wrapped by a java. sql.


2 Answers

java.sql.Date extends java.util.Date so it has the same information but displays it differently because of overridden toString() method.

If you do something like this you will see it is the same

System.out.println(new java.util.Date(sqlDate.getTime()));

It is advised to use DateFormat or SimpleDateFormat to display data, see the comments.

like image 94
Grzegorz Żur Avatar answered Oct 19 '22 05:10

Grzegorz Żur


Use time stamp

    Date updated_date=new Date();
    Timestamp timestamp = new Timestamp(updated_date.getTime());
    updated_date = timestamp;

and make sure Data type in Database should be Timestamp or Datetime

like image 42
KhAn SaAb Avatar answered Oct 19 '22 07:10

KhAn SaAb