Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

Tags:

java

date

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.

This is what I have tried so far:

java.util.Date 
today=new Date();
String date = formatter.format(today); 
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime()); 
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate); 
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate); 
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
like image 926
Pradeep Avatar asked Jun 20 '14 05:06

Pradeep


People also ask

How do I change the format of a date in SQL query?

You can specify the format of the dates in your statements using CONVERT and FORMAT. For example: select convert(varchar(max), DateColumn, 13), format(DateColumn, 'dd-MMM-yyyy')


1 Answers

You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat(
    "MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
                                    // at 0.
cal.set(Calendar.DAY_OF_MONTH, day);

java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));

Output is the expected

10-31-2014

like image 176
Elliott Frisch Avatar answered Oct 01 '22 12:10

Elliott Frisch