替换 java.util.Date(year,month,day) 的公认方法是什么

What is the accepted way to replace java.util.Date(year,month,day)(替换 java.util.Date(year,month,day) 的公认方法是什么)

本文介绍了替换 java.util.Date(year,month,day) 的公认方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些非常简单的事情,但开始意识到 Java 中的日期有点雷区.我想要的只是通过三个整数组(一年、一个月和一个日期)创建一些 Date 对象,对它们进行一些简单的测试(沿着日期 B 之前的日期 A并且在 1990 年 1 月 1 日之后),将它们转换为 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.

推荐答案

想法是使用 Calendar 类,像这样:

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

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

确实,如果您检查 constructor 您提到的,正是建议的内容:

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(year,month,day) 的公认方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:替换 java.util.Date(year,month,day) 的公认方法是什么

基础教程推荐