什么是接受的方法来替换java.util.Date(年,月,日) [英] What is the accepted way to replace java.util.Date(year,month,day)

查看:458
本文介绍了什么是接受的方法来替换java.util.Date(年,月,日)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些非常简单的事情,但是开始意识到Java中的日期是一个雷区。所有我想要的是通过三个int(一年,一个月和一个日期)的组来创建一些 Date 对象,对它们进行一些简单的测试(沿着作为日期B之前的日期B和1990年1月1日之后的日期A),将它们转换为 java.sql.Date 对象,并通过JDBC将其传递到数据库。

I'm trying to do something really simple, but starting to realize that dates in Java are a bit of minefield. All I want is to get passed groups of three ints ( a year, a month and a date) create some Date objects, do some simple test on them (along the lines of as date A before date B and after January 1 1990), convert them to java.sql.Date objects and pass them off to the database via JDBC.

所有非常简单,使用 java.util.Date(int year,int month,int day)构造函数。当然,这个构造函数是折旧的,我想避免在我写的新代码中使用折旧的调用。然而,解决这个简单问题的所有其他选项似乎很复杂。是否真的没有简单的方法来做我想要的,而不使用折旧的构造函数?

All very simple and works fine using the java.util.Date(int year,int month,int day) constructor. Of course that constructor is depreciated, and I'd like to avoid using depreciated calls in new code I'm writing. However all the other options to solve this simple problem seem stupidly complicated. Is there really no simple way to do what I want without using depreciated constructors?

我知道所有Java日期相关问题的标准答案是使用joda时间,但我真的不想开始拉扯第三方图书馆这样一个看似琐碎的问题。

I know the standard answer to all Java date related questions is "use joda time", but I really don't want to start pulling in third party libraries for such a seemingly trivial problem.

推荐答案

这个想法是使用 日历 类,如下所示:

The idea is to use the Calendar class, like so:

Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
Date date = cal.getTime();

的确,如果你检查了构造函数建议:

Indeed, if you check the Javadoc of the constructor you are mentioning, it is exactly what is suggested:

Date(int year, int month, int date)
          Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

或...使用JodaTime: - )。

Or ... use JodaTime :-).

这篇关于什么是接受的方法来替换java.util.Date(年,月,日)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆