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