IT

Java : Date 생성자가 더 이상 사용되지 않는 이유는 무엇입니까?

lottoking 2020. 5. 13. 08:28
반응형

Java : Date 생성자가 더 이상 사용되지 않는 이유는 무엇입니까?


나는 C # 세계에서 왔으므로 아직 Java에 익숙하지 않습니다. 나는 Date더 이상 사용되지 않는 Eclipse에 의해 들었다 .

Person p = new Person();
p.setDateOfBirth(new Date(1985, 1, 1));

왜? 그리고 대신 (특히 위와 같은 경우) 무엇을 사용해야합니까?


특정 Date생성자는 더 이상 사용되지 않으므로 Calendar대신 사용해야합니다. JavaDoc에 대한 날짜 생성자가 사용되지되는과를 사용하여 교체하는 방법에 대해 설명합니다 Calendar.


java.util.Date클래스는 실제로 다른 생성자 / 메소드가되지 않습니다 몇과 함께 그냥 생성자, 사용되지되지 않습니다. 국제화에서는 이러한 종류의 사용법이 제대로 작동하지 않기 때문에 사용되지 않습니다. Calendar클래스는 대신 사용해야합니다 :

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date dateRepresentation = cal.getTime();

Javadoc 날짜를 살펴보십시오.

http://download.oracle.com/javase/6/docs/api/java/util/Date.html


tl; dr

LocalDate.of( 1985 , 1 , 1 )

…또는…

LocalDate.of( 1985 , Month.JANUARY , 1 )

세부

java.util.Date, java.util.Calendar그리고 java.text.SimpleDateFormat자바가 처음 출시 진화 할 때 클래스는 너무 빨리 돌진했다. 수업은 잘 설계되거나 구현되지 않았습니다. 개선이 시도되었으므로 더 이상 사용되지 않습니다. 불행히도 개선 시도는 크게 실패했습니다. 당신은해야 이러한 클래스를 피하기 전부. 그것들은 새로운 클래스에 의해 Java 8에서 대체됩니다.

코드 문제

java.util.Date에는 날짜와 시간 부분이 있습니다. 코드에서 시간 부분을 무시했습니다. 따라서 Date 클래스는 JVM의 기본 시간대에 정의 된대로 하루의 시작 시간을 가져 와서 해당 시간을 Date 객체에 적용합니다. 따라서 코드 결과는 실행되는 시스템 또는 시간대에 따라 다릅니다. 아마 당신이 원하는 것이 아닙니다.

생년월일과 같이 시간 부분이없는 날짜 만 원하는 경우 Date개체 를 사용하지 않을 수 있습니다 . ISO 8601 형식의 날짜 문자열 만 저장할 수 있습니다 YYYY-MM-DD. 또는 LocalDateJoda-Time 객체를 사용 하십시오 (아래 참조).

조다 타임

Java에서 가장 먼저 배울 사항 : Java와 함께 번들로 제공되는 악명 높은 java.util.Date & java.util.Calendar 클래스는 피하십시오 .

로 올바르게에서 언급 user3277382으로 대답 , 사용 중 Joda 타임 또는 새로운 java.time. * 패키지를 자바 8.

Joda-Time 2.3의 예제 코드

DateTimeZone timeZoneNorway = DateTimeZone.forID( "Europe/Oslo" );
DateTime birthDateTime_InNorway = new DateTime( 1985, 1, 1, 3, 2, 1, timeZoneNorway );

DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime birthDateTime_InNewYork = birthDateTime_InNorway.toDateTime( timeZoneNewYork ); 

DateTime birthDateTime_UtcGmt = birthDateTime_InNorway.toDateTime( DateTimeZone.UTC );

LocalDate birthDate = new LocalDate( 1985, 1, 1 );

콘솔로 덤프…

System.out.println( "birthDateTime_InNorway: " + birthDateTime_InNorway );
System.out.println( "birthDateTime_InNewYork: " + birthDateTime_InNewYork );
System.out.println( "birthDateTime_UtcGmt: " + birthDateTime_UtcGmt );
System.out.println( "birthDate: " + birthDate );

달릴 때…

birthDateTime_InNorway: 1985-01-01T03:02:01.000+01:00
birthDateTime_InNewYork: 1984-12-31T21:02:01.000-05:00
birthDateTime_UtcGmt: 1985-01-01T02:02:01.000Z
birthDate: 1985-01-01

java.time

이 경우 java.time 의 코드 Joda-Time 의 코드와 거의 동일합니다 .

We get a time zone (ZoneId), and construct a date-time object assigned to that time zone (ZonedDateTime). Then using the Immutable Objects pattern, we create new date-times based on the old object’s same instant (count of nanoseconds since epoch) but assigned other time zone. Lastly we get a LocalDate which has no time-of-day nor time zone though notice the time zone applies when determining that date (a new day dawns earlier in Oslo than in New York for example).

ZoneId zoneId_Norway = ZoneId.of( "Europe/Oslo" );
ZonedDateTime zdt_Norway = ZonedDateTime.of( 1985 , 1 , 1 , 3 , 2 , 1 , 0 , zoneId_Norway );

ZoneId zoneId_NewYork = ZonedId.of( "America/New_York" );
ZonedDateTime zdt_NewYork = zdt_Norway.withZoneSameInstant( zoneId_NewYork );

ZonedDateTime zdt_Utc = zdt_Norway.withZoneSameInstant( ZoneOffset.UTC );  // Or, next line is similar.
Instant instant = zdt_Norway.toInstant();  // Instant is always in UTC.

LocalDate localDate_Norway = zdt_Norway.toLocalDate();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


One reason that the constructor is deprecated is that the meaning of the year parameter is not what you would expect. The javadoc says:

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date).

Notice that the year field is the number of years since 1900, so your sample code most likely won't do what you expect it to do. And that's the point.

In general, the Date API only supports the modern western calendar, has idiosyncratically specified components, and behaves inconsistently if you set fields.

The Calendar and GregorianCalendar APIs are better than Date, and the 3rd-party Joda-time APIs were generally thought to be the best. In Java 8, they introduced the java.time packages, and these are now the recommended alternative.


I came across this question as a duplicate of a newer question which asked what the non-deprecated way to get a Date at a specific year, month, and day was.

The answers here so far say to use the Calendar class, and that was true until Java 8 came out. But as of Java 8, the standard way to do this is:

LocalDate localDate = LocalDate.of(1985, 1, 1);

And then if you really really need a java.util.Date, you can use the suggestions in this question.

For more info, check out the API or the tutorials for Java 8.


Please note that Calendar.getTime() is nondeterministic in the sense that the day time part defaults to the current time.

To reproduce, try running following code a couple of times:

Calendar c = Calendar.getInstance();
c.set(2010, 2, 7); // NB: 2 means March, not February!
System.err.println(c.getTime());

Output eg.:

Sun Mar 07 10:46:21 CET 2010

Running the exact same code a couple of minutes later yields:

Sun Mar 07 10:57:51 CET 2010

So, while set() forces corresponding fields to correct values, it leaks system time for the other fields. (Tested above with Sun jdk6 & jdk7)


Date itself is not deprecated. It's just a lot of its methods are. See here for details.

Use java.util.Calendar instead.


Most Java developers currently use the third party package Joda-Time. It is widely regarded to be a much better implementation.

Java 8 however will have a new java.time.* package. See this article, Introducing the New Date and Time API for JDK 8.


Similar to what binnyb suggested, you might consider using the newer Calendar > GregorianCalendar method. See these more recent docs:

http://download.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html


You can make a method just like new Date(year,month,date) in your code by using Calendar class.

private Date getDate(int year,int month,int date){
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month-1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    return cal.getTime();
}

It will work just like the deprecated constructor of Date


new GregorianCalendar(1985, Calendar.JANUARY, 1).getTime();

(the pre-Java-8 way)


The Date constructor expects years in the format of years since 1900, zero-based months, and sets hours/minutes/seconds/milliseconds to zero.

Date result = new Date(year, month, day);

So using the Calendar replacement (zero-based years, zero-based months, one-based days) for the deprecated Date constructor, we need something like:

Calendar calendar = Calendar.getInstance();
calendar.clear(); // Sets hours/minutes/seconds/milliseconds to zero
calendar.set(year + 1900, month, day);
Date result = calendar.getTime();

Or using Java 1.8 (which has zero-based year, and one-based months and days):

Date result = Date.from(LocalDate.of(year + 1900, month + 1, day).atStartOfDay(ZoneId.systemDefault()).toInstant());

Here are equal versions of Date, Calendar, and Java 1.8:

int year = 1985; // 1985
int month = 1; // January
int day = 1; // 1st

// Original, 1900-based year, zero-based month, one-based day
Date date1 = new Date(year - 1900, month - 1, day);

// Calendar, zero-based year, zero-based month, one-based day
Calendar calendar = Calendar.getInstance();
calendar.clear(); // Sets hours/minutes/seconds/milliseconds to zero
calendar.set(year, month - 1, day);
Date date2 = calendar.getTime();

// Java-time back to Date, zero-based year, one-based month, one-based day
Date date3 = Date.from(LocalDate.of(year, month, day).atStartOfDay(ZoneId.systemDefault()).toInstant());

SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS");

// All 3 print "1985-Jan-01 00:00:00.000"
System.out.println(format.format(date1));
System.out.println(format.format(date2));
System.out.println(format.format(date3));

As the Date constructor is deprecated, you can try this code.

import java.util.Calendar;

  Calendar calendar = Calendar.getInstance();
     calendar.set(Calendar.HOUR_OF_DAY, 6);// for 6 hour
     calendar.set(Calendar.MINUTE, 0);// for 0 min
     calendar.set(Calendar.SECOND, 0);// for 0 sec
     calendar.set(1996,0,26);// for Date [year,month(0 to 11), date]

    Date date = new Date(calendar.getTimeInMillis());// calendar gives long value

    String mConvertedDate = date.toString();// Fri Jan 26 06:00:00 GMT+05:30 1996

참고URL : https://stackoverflow.com/questions/5677470/java-why-is-the-date-constructor-deprecated-and-what-do-i-use-instead

반응형