What is the purpose of this code? Is it just duplicate dates?

I came across an ancient piece of code for those who no longer work in the company.

I wonder what the purpose of this calendar magic is:

if (value instanceof Date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime((Date) value);
    return new Date(calendar.get(Calendar.YEAR) - 1900, calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
}

It seems to me that this will return a new object Datewith the same values ​​as the original one value. Is there some kind of calendar initialization I'm skipping? If the goal is to return a new object with the same value, I would assume that it value.clone()is doing the job:

(Date) originalDate.clone()
// or
new Date(originalDate.getTime())

Version control shows that the code has never changed. Are there any possible side effects when moving a date through a calendar?

+4
source share
2 answers

, , .

:

Date value = new Date();
System.out.printf("Before %s%n", value);
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
System.out.printf(
    "After %s%n", 
    new Date(
        calendar.get(Calendar.YEAR) - 1900, 
        calendar.get(Calendar.MONTH), 
        calendar.get(Calendar.DAY_OF_MONTH)
    )
);

:

Before Thu Oct 06 11:19:26 GMT 2016
After Thu Oct 06 00:00:00 GMT 2016
+3

Filotto .

00:00:00. , . , java.time.

, :

LocalDate

LocalDate .

. . , Paris France - , "" .

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

today.toString(): 2016-01-23

ZonedDateTime

LocalDate, . atStartOfDay, . , - 00:00:00. , (DST), , - 01:00:00. java.time .

ZonedDateTime todayStart = today.atStartOfDay( z );

today.toString(): 2016-01-23T00: 00: 00-05: 00 [/]

. . . "Half-Open" .

Instant

UTC. ZonedDateTime UTC, Instant. Instant UTC ( (9) ).

Instant instant = zdtStart.toInstant();

. - , java.time, / java.time. , .

java.util.GregorianCalendar gc = GregorianCalendar.from( zdtStart );
java.util.Date d = Date.from( instant );

java.time

java.time Java 8 . , java.util.Date, .Calendar java.text.SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru .

java.time Java 6 7 ThreeTen-Backport Android ThreeTenABP (. ...).

ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter .

+1

Source: https://habr.com/ru/post/1656921/


All Articles