Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get day month year from java.sql.date

Tags:

java

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.

like image 673
Tarounen Avatar asked Apr 11 '15 22:04

Tarounen


2 Answers

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
like image 144
Pshemo Avatar answered Sep 23 '22 14:09

Pshemo


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);
like image 44
karthik manchala Avatar answered Sep 25 '22 14:09

karthik manchala