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);
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With