本文介绍了如何将java.sql.date格式化为此格式:“MM-dd-yyyy”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要以下列格式MM-dd-yyyy获取一个java.sql.date,但是我需要保留一个java.sql.date,所以我可以把它放在一个表中作为日期字段。所以在格式化之后它不能是一个String,它必须最终作为一个java.sql.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);
推荐答案
您可以按照(自是一个 java.util.Date
的子类,其中
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));
输出是预期的
这篇关于如何将java.sql.date格式化为此格式:“MM-dd-yyyy”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!