从 java.sql.date 获取日月年

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29583936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:32:23  来源:igfitidea点击:

get day month year from java.sql.date

java

提问by Tarounen

My question is simple my SQLquery from java returns a date and assign it to a java.sql.Datevariable.

我的问题很简单,我的SQLjava 查询返回一个日期并将其分配给一个java.sql.Date变量。

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

但是我想将每一天、每一个月和每一年都作为整数。似乎方法getDay(),getMonth()已被弃用。

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.

现在我想要年、月和日在一个 int 变量中。

回答by karthik manchala

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

回答by Pshemo

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

由于java.sql.Date扩展,java.util.Date您可以使用其继承的toLocalDate()方法来获取LocalDate支持许多get...()方法的实例(自 Java 8 起可用),例如

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