1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package build.tools.tzdb;
  63 
  64 import static build.tools.tzdb.Utils.*;
  65 import static build.tools.tzdb.LocalTime.HOURS_PER_DAY;
  66 import static build.tools.tzdb.LocalTime.MICROS_PER_DAY;
  67 import static build.tools.tzdb.LocalTime.MILLIS_PER_DAY;
  68 import static build.tools.tzdb.LocalTime.MINUTES_PER_DAY;
  69 import static build.tools.tzdb.LocalTime.SECONDS_PER_DAY;
  70 import static build.tools.tzdb.LocalTime.SECONDS_PER_MINUTE;
  71 import static build.tools.tzdb.LocalTime.SECONDS_PER_HOUR;
  72 
  73 import java.util.Objects;
  74 
  75 /**
  76  * A date-time without a time-zone in the ISO-8601 calendar system,
  77  * such as {@code 2007-12-03T10:15:30}.
  78  *
  79  * @since 1.8
  80  */
  81 final class LocalDateTime {
  82 
  83     /**
  84      * The minimum supported {@code LocalDateTime}, '-999999999-01-01T00:00:00'.
  85      * This is the local date-time of midnight at the start of the minimum date.
  86      * This combines {@link LocalDate#MIN} and {@link LocalTime#MIN}.
  87      * This could be used by an application as a "far past" date-time.
  88      */
  89     public static final LocalDateTime MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN);
  90     /**
  91      * The maximum supported {@code LocalDateTime}, '+999999999-12-31T23:59:59.999999999'.
  92      * This is the local date-time just before midnight at the end of the maximum date.
  93      * This combines {@link LocalDate#MAX} and {@link LocalTime#MAX}.
  94      * This could be used by an application as a "far future" date-time.
  95      */
  96     public static final LocalDateTime MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX);
  97 
  98     /**
  99      * The date part.
 100      */
 101     private final LocalDate date;
 102     /**
 103      * The time part.
 104      */
 105     private final LocalTime time;
 106 
 107     /**
 108      * Obtains an instance of {@code LocalDateTime} from year, month,
 109      * day, hour and minute, setting the second and nanosecond to zero.
 110      * <p>
 111      * The day must be valid for the year and month, otherwise an exception will be thrown.
 112      * The second and nanosecond fields will be set to zero.
 113      *
 114      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 115      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 116      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 117      * @param hour  the hour-of-day to represent, from 0 to 23
 118      * @param minute  the minute-of-hour to represent, from 0 to 59
 119      * @return the local date-time, not null
 120      * @throws DateTimeException if the value of any field is out of range
 121      * @throws DateTimeException if the day-of-month is invalid for the month-year
 122      */
 123     public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) {
 124         LocalDate date = LocalDate.of(year, month, dayOfMonth);
 125         LocalTime time = LocalTime.of(hour, minute);
 126         return new LocalDateTime(date, time);
 127     }
 128 
 129     /**
 130      * Obtains an instance of {@code LocalDateTime} from a date and time.
 131      *
 132      * @param date  the local date, not null
 133      * @param time  the local time, not null
 134      * @return the local date-time, not null
 135      */
 136     public static LocalDateTime of(LocalDate date, LocalTime time) {
 137         Objects.requireNonNull(date, "date");
 138         Objects.requireNonNull(time, "time");
 139         return new LocalDateTime(date, time);
 140     }
 141 
 142     /**
 143      * Obtains an instance of {@code LocalDateTime} using seconds from the
 144      * epoch of 1970-01-01T00:00:00Z.
 145      * <p>
 146      * This allows the {@link ChronoField#INSTANT_SECONDS epoch-second} field
 147      * to be converted to a local date-time. This is primarily intended for
 148      * low-level conversions rather than general application usage.
 149      *
 150      * @param epochSecond  the number of seconds from the epoch of 1970-01-01T00:00:00Z
 151      * @param nanoOfSecond  the nanosecond within the second, from 0 to 999,999,999
 152      * @param offset  the zone offset, not null
 153      * @return the local date-time, not null
 154      * @throws DateTimeException if the result exceeds the supported range
 155      */
 156     public static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) {
 157         Objects.requireNonNull(offset, "offset");
 158         long localSecond = epochSecond + offset.getTotalSeconds();  // overflow caught later
 159         long localEpochDay = floorDiv(localSecond, SECONDS_PER_DAY);
 160         int secsOfDay = (int)floorMod(localSecond, SECONDS_PER_DAY);
 161         LocalDate date = LocalDate.ofEpochDay(localEpochDay);
 162         LocalTime time = LocalTime.ofSecondOfDay(secsOfDay);  // ignore nano
 163         return new LocalDateTime(date, time);
 164     }
 165 
 166     /**
 167      * Constructor.
 168      *
 169      * @param date  the date part of the date-time, validated not null
 170      * @param time  the time part of the date-time, validated not null
 171      */
 172     private LocalDateTime(LocalDate date, LocalTime time) {
 173         this.date = date;
 174         this.time = time;
 175     }
 176 
 177     /**
 178      * Returns a copy of this date-time with the new date and time, checking
 179      * to see if a new object is in fact required.
 180      *
 181      * @param newDate  the date of the new date-time, not null
 182      * @param newTime  the time of the new date-time, not null
 183      * @return the date-time, not null
 184      */
 185     private LocalDateTime with(LocalDate newDate, LocalTime newTime) {
 186         if (date == newDate && time == newTime) {
 187             return this;
 188         }
 189         return new LocalDateTime(newDate, newTime);
 190     }
 191 
 192     /**
 193      * Gets the {@code LocalDate} part of this date-time.
 194      * <p>
 195      * This returns a {@code LocalDate} with the same year, month and day
 196      * as this date-time.
 197      *
 198      * @return the date part of this date-time, not null
 199      */
 200     public LocalDate getDate() {
 201         return date;
 202     }
 203 
 204     /**
 205      * Gets the year field.
 206      * <p>
 207      * This method returns the primitive {@code int} value for the year.
 208      * <p>
 209      * The year returned by this method is proleptic as per {@code get(YEAR)}.
 210      * To obtain the year-of-era, use {@code get(YEAR_OF_ERA}.
 211      *
 212      * @return the year, from MIN_YEAR to MAX_YEAR
 213      */
 214     public int getYear() {
 215         return date.getYear();
 216     }
 217 
 218     /**
 219      * Gets the month-of-year field as an int from 1 to 12.
 220      *
 221      * @return the month-of-year
 222      */
 223     public int getMonth() {
 224         return date.getMonth();
 225     }
 226 
 227     /**
 228      * Gets the day-of-month field.
 229      * <p>
 230      * This method returns the primitive {@code int} value for the day-of-month.
 231      *
 232      * @return the day-of-month, from 1 to 31
 233      */
 234     public int getDayOfMonth() {
 235         return date.getDayOfMonth();
 236     }
 237 
 238     /**
 239      * Gets the day-of-week field, which is an integer from 1 to 7.
 240      *
 241      * @return the day-of-week, from 1 to 7
 242      */
 243     public int getDayOfWeek() {
 244         return date.getDayOfWeek();
 245     }
 246 
 247     /**
 248      * Gets the {@code LocalTime} part of this date-time.
 249      * <p>
 250      * This returns a {@code LocalTime} with the same hour, minute, second and
 251      * nanosecond as this date-time.
 252      *
 253      * @return the time part of this date-time, not null
 254      */
 255     public LocalTime getTime() {
 256         return time;
 257     }
 258 
 259     /**
 260      * Gets the hour-of-day field.
 261      *
 262      * @return the hour-of-day, from 0 to 23
 263      */
 264     public int getHour() {
 265         return time.getHour();
 266     }
 267 
 268     /**
 269      * Gets the minute-of-hour field.
 270      *
 271      * @return the minute-of-hour, from 0 to 59
 272      */
 273     public int getMinute() {
 274         return time.getMinute();
 275     }
 276 
 277     /**
 278      * Gets the second-of-minute field.
 279      *
 280      * @return the second-of-minute, from 0 to 59
 281      */
 282     public int getSecond() {
 283         return time.getSecond();
 284     }
 285 
 286     /**
 287      * Converts this date-time to the number of seconds from the epoch
 288      * of 1970-01-01T00:00:00Z.
 289      * <p>
 290      * This combines this local date-time and the specified offset to calculate the
 291      * epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z.
 292      * Instants on the time-line after the epoch are positive, earlier are negative.
 293      * <p>
 294      * This default implementation calculates from the epoch-day of the date and the
 295      * second-of-day of the time.
 296      *
 297      * @param offset  the offset to use for the conversion, not null
 298      * @return the number of seconds from the epoch of 1970-01-01T00:00:00Z
 299      */
 300     public long toEpochSecond(ZoneOffset offset) {
 301         Objects.requireNonNull(offset, "offset");
 302         long epochDay = getDate().toEpochDay();
 303         long secs = epochDay * 86400 + getTime().toSecondOfDay();
 304         secs -= offset.getTotalSeconds();
 305         return secs;
 306     }
 307 
 308     /**
 309      * Returns a copy of this {@code LocalDateTime} with the specified period in days added.
 310      * <p>
 311      * This method adds the specified amount to the days field incrementing the
 312      * month and year fields as necessary to ensure the result remains valid.
 313      * The result is only invalid if the maximum/minimum year is exceeded.
 314      * <p>
 315      * For example, 2008-12-31 plus one day would result in 2009-01-01.
 316      * <p>
 317      * This instance is immutable and unaffected by this method call.
 318      *
 319      * @param days  the days to add, may be negative
 320      * @return a {@code LocalDateTime} based on this date-time with the days added, not null
 321      * @throws DateTimeException if the result exceeds the supported date range
 322      */
 323     public LocalDateTime plusDays(long days) {
 324         LocalDate newDate = date.plusDays(days);
 325         return with(newDate, time);
 326     }
 327 
 328     /**
 329      * Returns a copy of this {@code LocalDateTime} with the specified period in seconds added.
 330      * <p>
 331      * This instance is immutable and unaffected by this method call.
 332      *
 333      * @param seconds  the seconds to add, may be negative
 334      * @return a {@code LocalDateTime} based on this date-time with the seconds added, not null
 335      * @throws DateTimeException if the result exceeds the supported date range
 336      */
 337     public LocalDateTime plusSeconds(long seconds) {
 338         return plusWithOverflow(date, 0, 0, seconds, 1);
 339     }
 340 
 341     /**
 342      * Returns a copy of this {@code LocalDateTime} with the specified period added.
 343      * <p>
 344      * This instance is immutable and unaffected by this method call.
 345      *
 346      * @param newDate  the new date to base the calculation on, not null
 347      * @param hours  the hours to add, may be negative
 348      * @param minutes the minutes to add, may be negative
 349      * @param seconds the seconds to add, may be negative
 350      * @param nanos the nanos to add, may be negative
 351      * @param sign  the sign to determine add or subtract
 352      * @return the combined result, not null
 353      */
 354     private LocalDateTime plusWithOverflow(LocalDate newDate, long hours, long minutes, long seconds, int sign) {
 355         if ((hours | minutes | seconds) == 0) {
 356             return with(newDate, time);
 357         }
 358         long totDays = seconds / SECONDS_PER_DAY +                //   max/24*60*60
 359                        minutes / MINUTES_PER_DAY +                //   max/24*60
 360                        hours / HOURS_PER_DAY;                     //   max/24
 361         totDays *= sign;                                          // total max*0.4237...
 362         long totSecs = (seconds % SECONDS_PER_DAY) +
 363                        (minutes % MINUTES_PER_DAY) * SECONDS_PER_MINUTE +
 364                        (hours % HOURS_PER_DAY) * SECONDS_PER_HOUR;
 365         long curSoD = time.toSecondOfDay();
 366         totSecs = totSecs * sign + curSoD;                    // total 432000000000000
 367         totDays += floorDiv(totSecs, SECONDS_PER_DAY);
 368 
 369         int newSoD = (int)floorMod(totSecs, SECONDS_PER_DAY);
 370         LocalTime newTime = (newSoD == curSoD ? time : LocalTime.ofSecondOfDay(newSoD));
 371         return with(newDate.plusDays(totDays), newTime);
 372     }
 373 
 374     /**
 375      * Compares this date-time to another date-time.
 376      * <p>
 377      * The comparison is primarily based on the date-time, from earliest to latest.
 378      * It is "consistent with equals", as defined by {@link Comparable}.
 379      * <p>
 380      * If all the date-times being compared are instances of {@code LocalDateTime},
 381      * then the comparison will be entirely based on the date-time.
 382      * If some dates being compared are in different chronologies, then the
 383      * chronology is also considered, see {@link ChronoLocalDateTime#compareTo}.
 384      *
 385      * @param other  the other date-time to compare to, not null
 386      * @return the comparator value, negative if less, positive if greater
 387      */
 388     public int compareTo(LocalDateTime other) {
 389         int cmp = date.compareTo(other.getDate());
 390         if (cmp == 0) {
 391             cmp = time.compareTo(other.getTime());
 392         }
 393         return cmp;
 394     }
 395 
 396     /**
 397      * Checks if this date-time is equal to another date-time.
 398      * <p>
 399      * Compares this {@code LocalDateTime} with another ensuring that the date-time is the same.
 400      * Only objects of type {@code LocalDateTime} are compared, other types return false.
 401      *
 402      * @param obj  the object to check, null returns false
 403      * @return true if this is equal to the other date-time
 404      */
 405     @Override
 406     public boolean equals(Object obj) {
 407         if (this == obj) {
 408             return true;
 409         }
 410         if (obj instanceof LocalDateTime) {
 411             LocalDateTime other = (LocalDateTime) obj;
 412             return date.equals(other.date) && time.equals(other.time);
 413         }
 414         return false;
 415     }
 416 
 417     /**
 418      * A hash code for this date-time.
 419      *
 420      * @return a suitable hash code
 421      */
 422     @Override
 423     public int hashCode() {
 424         return date.hashCode() ^ time.hashCode();
 425     }
 426 
 427 }