java.sql.time 格式,如何将java.sql.date格式化为此格式:“MM-dd-yyyy”?

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 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); //

// 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值