简体   繁体   中英

get day month year from java.sql.date

My question is simple my SQL query from java returns a date and assign it to a java.sql.Date variable.

however i want to get each of the day, month and year as int. It seems that the methods getDay() , getMonth() are deprecated.

Are there any other way to achieve this?

what i tried for testing is:

String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);

now i want year, month and day in an int variable each.

You can do the following:

String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);
//create calander instance and get required params
Calendar cal = Calendar.getInstance();
cal.setTime(dat);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);

Since java.sql.Date extends java.util.Date you could use its inherited toLocalDate() method to get instance of LocalDate (available since Java 8) which supports many get...() methods like

String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);

LocalDate localDate = dat.toLocalDate();
System.out.println(localDate.getDayOfMonth());
System.out.println(localDate.getMonthValue());
System.out.println(localDate.getYear());

Output:

12
4
2015

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM