joda-time-2.3/0000775000175000017500000000000012205344143012557 5ustar ebourgebourgjoda-time-2.3/LICENSE.txt0000644000175000017500000002645011564251353014416 0ustar ebourgebourg Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. joda-time-2.3/RELEASE-NOTES.txt0000644000175000017500000001175012203450536015272 0ustar ebourgebourgJoda-Time version 2.3 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This release contains enhancements, bug fixes and a time zone update. The release runs on JDK 5 or later. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** Enhancements since 2.2 ---------------------- - Interval/MutableInterval .isEqual() [#20] Add method to compare intervals ignoring the chronology https://github.com/JodaOrg/joda-time/issues/20 - Chronology classes now define equals methods [#36] Previously, the Chronology classes relied on caching in factory methods to guarantee instances were singletons Now, there are dedicated, normal, equals methods This will aid weird cases where deserialization or similar avoids the caches It will make no difference to most users - Maximum size for pattern cache [#49] Sets a maximum size for the cache to avoid memory issues - Add LocalDateTime.toDate(TimeZone) [#48] Provides an alternate way to create a java.util.Date that avoids some synchronization - Home page moved http://www.joda.org/joda-time Compatibility with 2.2 ---------------------- Build system - Yes Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2013d Semantic compatible - Yes, except - DateTimeZone is now limited to offsets from -23:59:59.999 to +23:59:59.999 - BasicChronology now defines an equals method This which would affect you if you subclassed it (unlikely) - GJChronology now has a minimum cutover instant of 0001-01-01 (Gregorian) Its unlikely you have it set earlier than this If you did your code was broken anyway Deprecations since 2.2 ---------------------- - DateMidnight [#41] This class is flawed in concept The time of midnight occasionally does not occur in some time-zones This is a result of a daylight savings time from 00:00 to 01:00 DateMidnight is essentially a DateTime with a time locked to midnight Such a concept is more generally a poor one to use, given LocalDate Replace DateMidnight with LocalDate Or replace it with DateTime, perhaps using the withTimeAtStartOfDay() method Bug fixes since 2.2 ------------------- - ZoneInfoCompiler and DateTimeZoneBuilder multi-threading [#18] A thread local variable was previously only initialised in one thread causing NPE https://github.com/JodaOrg/joda-time/issues/18 - Short time-zone name parsing failed to match the longest name This affected two short names where one is a short form of the second such as "UT" and "UTC" - Days.daysBetween fails for MonthDay [#22] Incorrect calculation around leap years - DateTimeZone failed to validate offsets [#43] Previously, there was little validation, resulting in the ability to create large offsets Those offsets could fail in other parts of the library Now, it is limited to -23:59:59.999 to +23:59:59.999 - DateTimeZone.forOffsetHoursMinutes failed to allow offsets from -00:01 to -00:59 [#42] The forOffsetHoursMinutes() method could not create an offset from -00:01 to -00:59 This was due to an inappropriate design A backwards compatible change to the input handling has been made forOffsetHoursMinutes(0, -15) now creates -00:15 - DateTimeFormatter.parseInto [#21] Fix parseInto() where it obtains the default year for parsing from the ReadWritableInstant Previously, the wrong year could be obtained at the start or end of the year in non UTC zones Now obtains the year from the ReadWritableInstant using the chronology of the ReadWritableInstant - Better thread-safety in ISODateTimeFormat [#45] - Fix GJChronology.plus/minus across cutover and year zero [#28] When subtracting a number of years from a date in the GJChronology there are two considerations The cutover date might be crossed, and year zero might be crossed (there is no year zero in GJ) Previously, each were handled separately, but not together. Now it is fixed As part of this change, the minimum cutover instant was set to 0001-01-01 (Gregorian) Scala -------- Joda-Time uses annotations from Joda-Convert. In the Java programming language, this dependency is optional, however in Scala it is not. Scala users must manually add the Joda-Convert v1.2 dependency. Feedback -------- Feedback is best received using GitHub issues and Pull Requests. https://github.com/JodaOrg/joda-time/ Feedback is also welcomed via the joda-interest mailing list. The Joda team http://joda-time.sourceforge.net joda-time-2.3/pom.xml0000644000175000017500000006111512203457272014104 0ustar ebourgebourg 4.0.0 joda-time joda-time jar Joda-Time 2.3 Date and time library to replace JDK date handling http://www.joda.org/joda-time/ GitHub https://github.com/JodaOrg/joda-time/issues 2002 Joda Interest list https://lists.sourceforge.net/lists/listinfo/joda-interest https://lists.sourceforge.net/lists/listinfo/joda-interest http://sourceforge.net/mailarchive/forum.php?forum_name=joda-interest scolebourne Stephen Colebourne Project Lead 0 https://github.com/jodastephen broneill Brian S O'Neill Senior Developer https://github.com/broneill Guy Allard Oren Benjamin https://github.com/oby1 Fredrik Borgh Dave Brosius https://github.com/mebigfatguy Luc Claes https://github.com/lucclaes Dan Cojocar https://github.com/dancojocar Christopher Elkins https://github.com/celkins Jeroen van Erp Gwyn Evans John Fletcher Sean Geoghegan mjunginger https://github.com/mjunginger Ashish Katyal Martin Kneissl https://github.com/mkneissl Vidar Larsen https://github.com/vlarsen Kasper Laudrup Jeff Lavallee https://github.com/jlavallee Antonio Leitao Kostas Maistrelis Al Major Blair Martin Julen Parra Michael Plump Ryan Propper Mike Schrag Hajime Senuma https://github.com/hajimes Kandarp Shah Francois Staes Ricardo Trindade Bram Van Dam https://github.com/codematters Maxim Zhao Apache 2 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:git:https://github.com/JodaOrg/joda-time.git scm:git:git@github.com:JodaOrg/joda-time.git https://github.com/JodaOrg/joda-time Joda.org http://www.joda.org META-INF ${project.basedir} LICENSE.txt NOTICE.txt ${project.basedir}/src/main/java **/*.properties org.codehaus.mojo exec-maven-plugin 1.2.1 compile java org.joda.time.tz.ZoneInfoCompiler compile true org.joda.time.DateTimeZone.Provider org.joda.time.tz.UTCProvider -src ${project.build.sourceDirectory}/org/joda/time/tz/src -dst ${project.build.outputDirectory}/org/joda/time/tz/data africa antarctica asia australasia europe northamerica southamerica pacificnew etcetera backward systemv org.apache.maven.plugins maven-surefire-plugin **/TestAllPackages.java org.apache.maven.plugins maven-jar-plugin src/conf/MANIFEST.MF true true org.apache.maven.plugins maven-javadoc-plugin User packages org.joda.time:org.joda.time.format:org.joda.time.chrono Implementation packages org.joda.time.base:org.joda.time.convert:org.joda.time.field:org.joda.time.tz attach-javadocs package jar org.apache.maven.plugins maven-source-plugin attach-sources package jar-no-fork **/*.properties org.apache.maven.plugins maven-assembly-plugin false src/main/assembly/dist.xml gnu make-assembly deploy single org.apache.maven.plugins maven-site-plugin true com.github.github site-maven-plugin 0.8 github-site site site-deploy Create website for ${project.artifactId} v${project.version} ${project.artifactId} true github JodaOrg jodaorg.github.io refs/heads/master org.codehaus.mojo clirr-maven-plugin 2.3 2.2 info true org.apache.maven.plugins maven-assembly-plugin ${maven-assembly-plugin.version} org.apache.maven.plugins maven-checkstyle-plugin ${maven-checkstyle-plugin.version} org.apache.maven.plugins maven-changes-plugin ${maven-changes-plugin.version} org.apache.maven.plugins maven-clean-plugin ${maven-clean-plugin.version} org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin.version} org.apache.maven.plugins maven-deploy-plugin ${maven-deploy-plugin.version} org.apache.maven.plugins maven-dependency-plugin ${maven-dependency-plugin.version} org.apache.maven.plugins maven-gpg-plugin ${maven-gpg-plugin.version} org.apache.maven.plugins maven-install-plugin ${maven-install-plugin.version} org.apache.maven.plugins maven-jar-plugin ${maven-jar-plugin.version} org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin.version} org.apache.maven.plugins maven-jxr-plugin ${maven-jxr-plugin.version} org.apache.maven.plugins maven-plugin-plugin ${maven-plugin-plugin.version} org.apache.maven.plugins maven-pmd-plugin ${maven-pmd-plugin.version} org.apache.maven.plugins maven-project-info-reports-plugin ${maven-project-info-reports-plugin.version} org.apache.maven.plugins maven-repository-plugin ${maven-repository-plugin.version} org.apache.maven.plugins maven-resources-plugin ${maven-resources-plugin.version} org.apache.maven.plugins maven-site-plugin ${maven-site-plugin.version} org.apache.maven.plugins maven-source-plugin ${maven-source-plugin.version} org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} org.apache.maven.plugins maven-surefire-report-plugin ${maven-surefire-report-plugin.version} org.apache.maven.plugins maven-toolchains-plugin ${maven-toolchains-plugin.version} org.eclipse.m2e lifecycle-mapping 1.0.0 org.codehaus.mojo exec-maven-plugin [1.2.1,) java 3.0.4 org.joda joda-convert 1.2 compile true junit junit 3.8.2 test org.apache.maven.plugins maven-project-info-reports-plugin ${maven-project-info-plugin.version} dependencies dependency-info issue-tracking license mailing-list project-team scm summary org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin.version} javadoc org.apache.maven.plugins maven-surefire-report-plugin ${maven-surefire-report-plugin.version} true org.apache.maven.plugins maven-jxr-plugin ${maven-jxr-plugin.version} jxr sonatype-joda-staging Sonatype OSS staging repository http://oss.sonatype.org/service/local/staging/deploy/maven2/ default false sonatype-joda-snapshot Sonatype OSS snapshot repository http://oss.sonatype.org/content/repositories/joda-snapshots default http://oss.sonatype.org/content/repositories/joda-releases repo-sign-artifacts oss.repo true org.apache.maven.plugins maven-toolchains-plugin validate toolchain 1.5 sun org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign 2.4 2.9 2.10 2.5 3.1 2.7 2.8 1.4 2.4 2.4 2.9.1 2.3 3.2 3.0.1 2.7 2.3.1 2.6 3.3 2.2.1 2.15 2.15 1.0 1.5 1.5 1.5 true true true true lines,source false true ${project.basedir}/src/main/checkstyle/checkstyle.xml UTF-8 UTF-8 joda-time-2.3/src/0000755000175000017500000000000012073523033013344 5ustar ebourgebourgjoda-time-2.3/src/example/0000755000175000017500000000000012073523032014776 5ustar ebourgebourgjoda-time-2.3/src/example/org/0000755000175000017500000000000012073523032015565 5ustar ebourgebourgjoda-time-2.3/src/example/org/joda/0000755000175000017500000000000012073523032016502 5ustar ebourgebourgjoda-time-2.3/src/example/org/joda/example/0000755000175000017500000000000012073523032020135 5ustar ebourgebourgjoda-time-2.3/src/example/org/joda/example/time/0000755000175000017500000000000012205344143021074 5ustar ebourgebourgjoda-time-2.3/src/example/org/joda/example/time/TimeZoneTable.java0000644000175000017500000001236011564251363024453 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.example.time; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; /** * Prints out all available time zones to standard out in an HTML table. * * @author Brian S O'Neill */ public class TimeZoneTable { static final long cNow = System.currentTimeMillis(); static final DateTimeFormatter cOffsetFormatter = new DateTimeFormatterBuilder() .appendTimeZoneOffset(null, true, 2, 4) .toFormatter(); public static void main(String[] args) throws Exception { Set idSet = DateTimeZone.getAvailableIDs(); ZoneData[] zones = new ZoneData[idSet.size()]; { Iterator it = idSet.iterator(); int i = 0; while (it.hasNext()) { String id = (String) it.next(); zones[i++] = new ZoneData(id, DateTimeZone.forID(id)); } Arrays.sort(zones); } PrintStream out = System.out; out.println(""); out.println("" + "" + "" + "" + ""); ZoneData canonical = null; List aliases = new ArrayList(); for (int i=0; i"); } private static void printRow(PrintStream out, ZoneData zone, List aliases) { out.print(""); out.print(""); out.print(""); out.print(""); out.println(""); } private static class ZoneData implements Comparable { private final String iID; private final DateTimeZone iZone; ZoneData(String id, DateTimeZone zone) { iID = id; iZone = zone; } public String getID() { return iID; } public String getCanonicalID() { return iZone.getID(); } public boolean isCanonical() { return getID().equals(getCanonicalID()); } public String getStandardOffsetStr() { long millis = cNow; while (iZone.getOffset(millis) != iZone.getStandardOffset(millis)) { long next = iZone.nextTransition(millis); if (next == millis) { break; } millis = next; } return cOffsetFormatter.withZone(iZone).print(millis); } public int compareTo(Object obj) { ZoneData other = (ZoneData) obj; int offsetA = iZone.getStandardOffset(cNow); int offsetB = other.iZone.getStandardOffset(cNow); if (offsetA < offsetB) { return -1; } if (offsetA > offsetB) { return 1; } int result = getCanonicalID().compareTo(other.getCanonicalID()); if (result != 0) { return result; } if (isCanonical()) { if (!other.isCanonical()) { return -1; } } else if (other.isCanonical()) { return 1; } return getID().compareTo(other.getID()); } } } joda-time-2.3/src/example/org/joda/example/time/Examples.java0000644000175000017500000001567611564251353023543 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.example.time; import java.util.Locale; import org.joda.time.DateTime; import org.joda.time.Instant; /** * Example code demonstrating how to use Joda-Time. * * @author Stephen Colebourne */ public class Examples { public static void main(String[] args) throws Exception { try { new Examples().run(); } catch (Throwable ex) { ex.printStackTrace(); } } private void run() { runInstant(); System.out.println(); runDateTime(); System.out.println(); } private void runInstant() { System.out.println("Instant"); System.out.println("======="); System.out.println("Instant stores a point in the datetime continuum as millisecs from 1970-01-01T00:00:00Z"); System.out.println("Instant is immutable and thread-safe"); System.out.println(" in = new Instant()"); Instant in = new Instant(); System.out.println("Millisecond time: in.getMillis(): " + in.getMillis()); System.out.println("ISO string version: in.toString(): " + in.toString()); System.out.println("ISO chronology: in.getChronology(): " + in.getChronology()); System.out.println("UTC time zone: in.getDateTimeZone(): " + in.getZone()); System.out.println("Change millis: in.withMillis(0): " + in.withMillis(0L)); System.out.println(""); System.out.println("Convert to Instant: in.toInstant(): " + in.toInstant()); System.out.println("Convert to DateTime: in.toDateTime(): " + in.toDateTime()); System.out.println("Convert to MutableDT: in.toMutableDateTime(): " + in.toMutableDateTime()); System.out.println("Convert to Date: in.toDate(): " + in.toDate()); System.out.println(""); System.out.println(" in2 = new Instant(in.getMillis() + 10)"); Instant in2 = new Instant(in.getMillis() + 10); System.out.println("Equals ms and chrono: in.equals(in2): " + in.equals(in2)); System.out.println("Compare millisecond: in.compareTo(in2): " + in.compareTo(in2)); System.out.println("Compare millisecond: in.isEqual(in2): " + in.isEqual(in2)); System.out.println("Compare millisecond: in.isAfter(in2): " + in.isAfter(in2)); System.out.println("Compare millisecond: in.isBefore(in2): " + in.isBefore(in2)); } private void runDateTime() { System.out.println("DateTime"); System.out.println("======="); System.out.println("DateTime stores a the date and time using millisecs from 1970-01-01T00:00:00Z internally"); System.out.println("DateTime is immutable and thread-safe"); System.out.println(" in = new DateTime()"); DateTime in = new DateTime(); System.out.println("Millisecond time: in.getMillis(): " + in.getMillis()); System.out.println("ISO string version: in.toString(): " + in.toString()); System.out.println("ISO chronology: in.getChronology(): " + in.getChronology()); System.out.println("Your time zone: in.getDateTimeZone(): " + in.getZone()); System.out.println("Change millis: in.withMillis(0): " + in.withMillis(0L)); System.out.println(""); System.out.println("Get year: in.getYear(): " + in.getYear()); System.out.println("Get monthOfYear: in.getMonthOfYear(): " + in.getMonthOfYear()); System.out.println("Get dayOfMonth: in.getDayOfMonth(): " + in.getDayOfMonth()); System.out.println("..."); System.out.println("Property access: in.dayOfWeek().get(): " + in.dayOfWeek().get()); System.out.println("Day of week as text: in.dayOfWeek().getAsText(): " + in.dayOfWeek().getAsText()); System.out.println("Day as short text: in.dayOfWeek().getAsShortText(): " + in.dayOfWeek().getAsShortText()); System.out.println("Day in french: in.dayOfWeek().getAsText(Locale.FRENCH):" + in.dayOfWeek().getAsText(Locale.FRENCH)); System.out.println("Max allowed value: in.dayOfWeek().getMaximumValue(): " + in.dayOfWeek().getMaximumValue()); System.out.println("Min allowed value: in.dayOfWeek().getMinimumValue(): " + in.dayOfWeek().getMinimumValue()); System.out.println("Copy & set to Jan: in.monthOfYear().setCopy(1): " + in.monthOfYear().setCopy(1)); System.out.println("Copy & add 14 months: in.monthOfYear().addCopy(14): " + in.monthOfYear().addToCopy(14)); System.out.println("Add 14 mnths in field:in.monthOfYear().addWrapFieldCopy(14): " + in.monthOfYear().addWrapFieldToCopy(14)); System.out.println("..."); System.out.println("Convert to Instant: in.toInstant(): " + in.toInstant()); System.out.println("Convert to DateTime: in.toDateTime(): " + in.toDateTime()); System.out.println("Convert to MutableDT: in.toMutableDateTime(): " + in.toMutableDateTime()); System.out.println("Convert to Date: in.toDate(): " + in.toDate()); System.out.println("Convert to Calendar: in.toCalendar(Locale.UK): " + in.toCalendar(Locale.UK).toString().substring(0, 46)); System.out.println("Convert to GregCal: in.toGregorianCalendar(): " + in.toGregorianCalendar().toString().substring(0, 46)); System.out.println(""); System.out.println(" in2 = new DateTime(in.getMillis() + 10)"); DateTime in2 = new DateTime(in.getMillis() + 10); System.out.println("Equals ms and chrono: in.equals(in2): " + in.equals(in2)); System.out.println("Compare millisecond: in.compareTo(in2): " + in.compareTo(in2)); System.out.println("Compare millisecond: in.isEqual(in2): " + in.isEqual(in2)); System.out.println("Compare millisecond: in.isAfter(in2): " + in.isAfter(in2)); System.out.println("Compare millisecond: in.isBefore(in2): " + in.isBefore(in2)); } } joda-time-2.3/src/example/org/joda/example/time/DateTimePerformance.java0000644000175000017500000007342111564251363025634 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.example.time; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.MutableDateTime; import org.joda.time.chrono.GJChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * DateTimePerformance provides various comparisons between the Java supplied * Date classes and the Joda ones. * * @author Stephen Colebourne */ public class DateTimePerformance { private static class Result { String object = null; String name = null; long time = 0; long avg = 0; int runs = 0; } private static int AVERAGE = 3; private static int COUNT_VERY_FAST = 5000000; private static int COUNT_FAST = 200000; private static int COUNT_SLOW = 20000; private Map results = new HashMap(); private List resultList = new ArrayList(); private Result result = null; private long start = 0; private long end = 0; /** * Constructor */ public static void main(String[] args) { try { new DateTimePerformance(); } catch (Throwable th) { th.printStackTrace(); } } /** * Constructor */ public DateTimePerformance() throws Exception { checkJodaConstructor1(); checkJISOConstructor1(); checkGCalConstructor1(); checkDateConstructor1(); checkJodaConstructor2(); checkJISOConstructor2(); checkGCalConstructor2(); checkDateConstructor2(); checkJodaConstructor3(); checkJISOConstructor3(); checkGCalConstructor3(); checkDateConstructor3(); checkJodaGetYear(); checkJISOGetYear(); checkGCalGetYear(); checkDateGetYear(); // checkJodaGetMonth(); // checkJISOGetMonth(); // checkGCalGetMonth(); // checkDateGetMonth(); // checkJodaGetDay(); // checkJISOGetDay(); // checkGCalGetDay(); // checkDateGetDay(); checkJodaGetHour(); checkJISOGetHour(); checkGCalGetHour(); checkDateGetHour(); checkJodaSetYear(); checkJISOSetYear(); checkGCalSetYear(); checkDateSetYear(); checkJodaSetGetYear(); checkJISOSetGetYear(); checkGCalSetGetYear(); checkDateSetGetYear(); checkJodaSetHour(); checkJISOSetHour(); checkGCalSetHour(); checkDateSetHour(); checkJodaSetGetHour(); checkJISOSetGetHour(); checkGCalSetGetHour(); checkDateSetGetHour(); checkJodaToString(); checkJISOToString(); checkGCalToString(); checkDateToString(); System.out.println(""); long jodaTotal = 0; long jisoTotal = 0; long gcalTotal = 0; long dateTotal = 0; for (Iterator it = resultList.iterator(); it.hasNext();) { Result res = (Result) it.next(); System.out.println(res.object + "." + res.name + ": " + res.avg + "ns"); if (res.object.equals("Joda")) { jodaTotal += res.avg; } else if (res.object.equals("JISO")) { jisoTotal += res.avg; } else if (res.object.equals("GCal")) { gcalTotal += res.avg; } else if (res.object.equals("Date")) { dateTotal += res.avg; System.out.println(""); } } System.out.println("Joda: " + jodaTotal); System.out.println("JISO: " + jisoTotal); System.out.println("GCal: " + gcalTotal); System.out.println("Date: " + dateTotal); } // Constructor using currentTimeMillis() //------------------------------------------------------------------------ private void checkJodaConstructor1() { int COUNT = COUNT_SLOW; DateTime dt = new DateTime(GJChronology.getInstance()); int count = 0; for (int i = 0; i < AVERAGE; i++) { start("Joda", "new()"); for (int j = 0; j < COUNT; j++) { dt = new DateTime(GJChronology.getInstance()); if (count++ < 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOConstructor1() { int COUNT = COUNT_SLOW; DateTime dt = new DateTime(); int count = 0; for (int i = 0; i < AVERAGE; i++) { start("JISO", "new()"); for (int j = 0; j < COUNT; j++) { dt = new DateTime(); if (count++ < 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalConstructor1() { int COUNT = COUNT_SLOW; GregorianCalendar dt = new GregorianCalendar(); int count = 0; for (int i = 0; i < AVERAGE; i++) { start("GCal", "new()"); for (int j = 0; j < COUNT; j++) { dt = new GregorianCalendar(); if (count++ < 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateConstructor1() { int COUNT = COUNT_SLOW; Date dt = new Date(); int count = 0; for (int i = 0; i < AVERAGE; i++) { start("Date", "new()"); for (int j = 0; j < COUNT; j++) { dt = new Date(); if (count++ < 0) {System.out.println("Anti optimise");} } end(COUNT); } } // Constructor using long millis //------------------------------------------------------------------------ private void checkJodaConstructor2() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(12345L, GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "new(millis)"); for (int j = 0; j < COUNT; j++) { dt = new DateTime(12345L, GJChronology.getInstance()); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOConstructor2() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(12345L); for (int i = 0; i < AVERAGE; i++) { start("JISO", "new(millis)"); for (int j = 0; j < COUNT; j++) { dt = new DateTime(12345L); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalConstructor2() { int COUNT = COUNT_SLOW; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "new(millis)"); for (int j = 0; j < COUNT; j++) { dt = new GregorianCalendar(); dt.setTime(new Date(12345L)); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateConstructor2() { int COUNT = COUNT_VERY_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "new(millis)"); for (int j = 0; j < COUNT; j++) { dt = new Date(12345L); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } // Constructor using year month and day //------------------------------------------------------------------------ private void checkJodaConstructor3() { int COUNT = COUNT_SLOW; DateTime dt = new DateTime(1972, 10, 1, 0, 0, 0, 0, GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "new(YMD)"); for (int j = 0; j < COUNT; j++) { dt = new DateTime(1972, 10, 1, 0, 0, 0, 0, GJChronology.getInstance()); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOConstructor3() { int COUNT = COUNT_SLOW; DateTime dt = new DateTime(1972, 10, 1, 0, 0, 0, 0); for (int i = 0; i < AVERAGE; i++) { start("JISO", "new(YMD)"); for (int j = 0; j < COUNT; j++) { dt = new DateTime(1972, 10, 1, 0, 0, 0, 0); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalConstructor3() { int COUNT = COUNT_SLOW; GregorianCalendar dt = new GregorianCalendar(1972, 10, 1); for (int i = 0; i < AVERAGE; i++) { start("GCal", "new(YMD)"); for (int j = 0; j < COUNT; j++) { dt = new GregorianCalendar(1972, 10, 1); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateConstructor3() { int COUNT = COUNT_SLOW; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "new(YMD)"); for (int j = 0; j < COUNT; j++) { dt = new Date(1972, 10, 1); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } // Get year //------------------------------------------------------------------------ private void checkJodaGetYear() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "getYear"); for (int j = 0; j < COUNT; j++) { int val = dt.getYear(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOGetYear() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "getYear"); for (int j = 0; j < COUNT; j++) { int val = dt.getYear(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalGetYear() { int COUNT = COUNT_VERY_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "getYear"); for (int j = 0; j < COUNT; j++) { int val = dt.get(GregorianCalendar.YEAR); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateGetYear() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "getYear"); for (int j = 0; j < COUNT; j++) { int val = dt.getYear(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } // Get month //------------------------------------------------------------------------ private void checkJodaGetMonth() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "getMonth"); for (int j = 0; j < COUNT; j++) { int val = dt.getMonthOfYear(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOGetMonth() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "getMonth"); for (int j = 0; j < COUNT; j++) { int val = dt.getMonthOfYear(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalGetMonth() { int COUNT = COUNT_VERY_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "getMonth"); for (int j = 0; j < COUNT; j++) { int val = dt.get(GregorianCalendar.MONTH); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateGetMonth() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "getMonth"); for (int j = 0; j < COUNT; j++) { int val = dt.getMonth(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } // Get day //------------------------------------------------------------------------ private void checkJodaGetDay() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "getDay"); for (int j = 0; j < COUNT; j++) { int val = dt.getDayOfMonth(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOGetDay() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "getDay"); for (int j = 0; j < COUNT; j++) { int val = dt.getDayOfMonth(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalGetDay() { int COUNT = COUNT_VERY_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "getDay"); for (int j = 0; j < COUNT; j++) { int val = dt.get(GregorianCalendar.DAY_OF_MONTH); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateGetDay() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "getDay"); for (int j = 0; j < COUNT; j++) { int val = dt.getDate(); if (val == 0) {System.out.println("Anti optimise");} } end(COUNT); } } // Get hour //------------------------------------------------------------------------ private void checkJodaGetHour() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "getHour"); for (int j = 0; j < COUNT; j++) { int val = dt.getHourOfDay(); if (val == -1) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOGetHour() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "getHour"); for (int j = 0; j < COUNT; j++) { int val = dt.getHourOfDay(); if (val == -1) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalGetHour() { int COUNT = COUNT_VERY_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "getHour"); for (int j = 0; j < COUNT; j++) { int val = dt.get(GregorianCalendar.HOUR_OF_DAY); if (val == -1) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateGetHour() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "getHour"); for (int j = 0; j < COUNT; j++) { int val = dt.getHours(); if (val == -1) {System.out.println("Anti optimise");} } end(COUNT); } } // Set year //------------------------------------------------------------------------ private void checkJodaSetYear() { int COUNT = COUNT_FAST; // Is it fair to use only MutableDateTime here? You decide. MutableDateTime dt = new MutableDateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "setYear"); for (int j = 0; j < COUNT; j++) { dt.setYear(1972); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOSetYear() { int COUNT = COUNT_FAST; // Is it fair to use only MutableDateTime here? You decide. MutableDateTime dt = new MutableDateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "setYear"); for (int j = 0; j < COUNT; j++) { dt.setYear(1972); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalSetYear() { int COUNT = COUNT_VERY_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "setYear"); for (int j = 0; j < COUNT; j++) { dt.set(GregorianCalendar.YEAR, 1972); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateSetYear() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "setYear"); for (int j = 0; j < COUNT; j++) { dt.setYear(1972); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } // Set then get year //------------------------------------------------------------------------ private void checkJodaSetGetYear() { int COUNT = COUNT_FAST; // Is it fair to use only MutableDateTime here? You decide. // MutableDateTime dt = new MutableDateTime(GJChronology.getInstance()); // for (int i = 0; i < AVERAGE; i++) { // start("Joda", "setGetYear"); // for (int j = 0; j < COUNT; j++) { // dt.setYear(1972); // int val = dt.getYear(); // if (val < 0) {System.out.println("Anti optimise");} // } // end(COUNT); // } DateTime dt = new DateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "setGetYear"); for (int j = 0; j < COUNT; j++) { dt = dt.year().setCopy(1972); int val = dt.getYear(); if (val < 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOSetGetYear() { int COUNT = COUNT_FAST; // Is it fair to use only MutableDateTime here? You decide. // MutableDateTime dt = new MutableDateTime(); // for (int i = 0; i < AVERAGE; i++) { // start("JISO", "setGetYear"); // for (int j = 0; j < COUNT; j++) { // dt.setYear(1972); // int val = dt.getYear(); // if (val < 0) {System.out.println("Anti optimise");} // } // end(COUNT); // } DateTime dt = new DateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "setGetYear"); for (int j = 0; j < COUNT; j++) { dt = dt.year().setCopy(1972); int val = dt.getYear(); if (val < 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalSetGetYear() { int COUNT = COUNT_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "setGetYear"); for (int j = 0; j < COUNT; j++) { dt.set(GregorianCalendar.YEAR, 1972); int val = dt.get(GregorianCalendar.YEAR); if (val < 0) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateSetGetYear() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "setGetYear"); for (int j = 0; j < COUNT; j++) { dt.setYear(1972); int val = dt.getYear(); if (val < 0) {System.out.println("Anti optimise");} } end(COUNT); } } // Set hour //------------------------------------------------------------------------ private void checkJodaSetHour() { int COUNT = COUNT_VERY_FAST; // Is it fair to use only MutableDateTime here? You decide. MutableDateTime dt = new MutableDateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "setHour"); for (int j = 0; j < COUNT; j++) { dt.setHourOfDay(13); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOSetHour() { int COUNT = COUNT_VERY_FAST; // Is it fair to use only MutableDateTime here? You decide. MutableDateTime dt = new MutableDateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "setHour"); for (int j = 0; j < COUNT; j++) { dt.setHourOfDay(13); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalSetHour() { int COUNT = COUNT_VERY_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "setHour"); for (int j = 0; j < COUNT; j++) { dt.set(GregorianCalendar.HOUR_OF_DAY, 13); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateSetHour() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "setHour"); for (int j = 0; j < COUNT; j++) { dt.setHours(13); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } // Set hour //------------------------------------------------------------------------ private void checkJodaSetGetHour() { int COUNT = COUNT_VERY_FAST; // Is it fair to use only MutableDateTime here? You decide. MutableDateTime dt = new MutableDateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "setGetHour"); for (int j = 0; j < COUNT; j++) { dt.setHourOfDay(13); int val = dt.getHourOfDay(); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOSetGetHour() { int COUNT = COUNT_VERY_FAST; // Is it fair to use only MutableDateTime here? You decide. MutableDateTime dt = new MutableDateTime(); for (int i = 0; i < AVERAGE; i++) { start("JISO", "setGetHour"); for (int j = 0; j < COUNT; j++) { dt.setHourOfDay(13); int val = dt.getHourOfDay(); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalSetGetHour() { int COUNT = COUNT_VERY_FAST; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "setGetHour"); for (int j = 0; j < COUNT; j++) { dt.set(GregorianCalendar.HOUR_OF_DAY, 13); int val = dt.get(GregorianCalendar.HOUR_OF_DAY); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateSetGetHour() { int COUNT = COUNT_FAST; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "setGetHour"); for (int j = 0; j < COUNT; j++) { dt.setHours(13); int val = dt.getHours(); if (dt == null) {System.out.println("Anti optimise");} } end(COUNT); } } // To formatted string //------------------------------------------------------------------------ private void checkJodaToString() { int COUNT = COUNT_SLOW; DateTime dt = new DateTime(GJChronology.getInstance()); DateTimeFormatter f = DateTimeFormat.forPattern("dd MMM yyyy"); for (int i = 0; i < AVERAGE; i++) { start("Joda", "toString"); for (int j = 0; j < COUNT; j++) { String str = dt.toString("dd MMM yyyy"); // String str = dt.toString(f); if (str == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkJISOToString() { int COUNT = COUNT_SLOW; DateTime dt = new DateTime(); DateTimeFormatter f = DateTimeFormat.forPattern("dd MMM yyyy"); for (int i = 0; i < AVERAGE; i++) { start("JISO", "toString"); for (int j = 0; j < COUNT; j++) { String str = dt.toString("dd MMM yyyy"); // String str = dt.toString(f); if (str == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkGCalToString() { int COUNT = COUNT_SLOW; GregorianCalendar dt = new GregorianCalendar(); for (int i = 0; i < AVERAGE; i++) { start("GCal", "toString"); for (int j = 0; j < COUNT; j++) { SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy"); String str = sdf.format(dt.getTime()); if (str == null) {System.out.println("Anti optimise");} } end(COUNT); } } private void checkDateToString() { int COUNT = COUNT_SLOW; Date dt = new Date(); for (int i = 0; i < AVERAGE; i++) { start("Date", "toString"); for (int j = 0; j < COUNT; j++) { SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy"); String str = sdf.format(dt); if (str == null) {System.out.println("Anti optimise");} } end(COUNT); } } //------------------------------------------------------------------------ /** * Start the stopwatch. */ private void start(String str1, String str2) { result = (Result) results.get(str1 + str2); if (result == null) { result = new Result(); result.object = str1; result.name = str2; results.put(str1 + str2, result); resultList.add(result); } start = System.currentTimeMillis(); } /** * End the stopwatch and print the result. */ private void end(int count) { end = System.currentTimeMillis(); long time = (end - start); result.time = result.time + time; result.runs = result.runs + count; result.avg = (result.time * 1000000) / result.runs; System.out.print("."); } } joda-time-2.3/src/example/org/joda/example/time/DateTimeFile.dat0000644000175000017500000000126411564251216024072 0ustar ebourgebourg1999-12-31T23:59:59 2000-01-01T00:00:00 1969-12-31T23:59:59 1970-01-01T00:00:00 1899-12-31T23:59:59 1900-01-01T00:00:00 # Comment test 1996-02-28T00:00:00 1996-02-29T00:00:00 1996-03-01T00:00:00 1996-12-31T00:00:00 1999-02-28T00:00:00 1999-02-29T00:00:00 1999-03-01T00:00:00 1999-12-31T00:00:00 2000-02-28T00:00:00 2000-02-29T00:00:00 2000-03-01T00:00:00 2000-12-31T00:00:00 # Dates at the Julian-to-Gregorian cutover 1582-10-04T00:00:00 1582-10-05T00:00:00 1582-10-06T00:00:00 1582-10-07T00:00:00 1582-10-08T00:00:00 1582-10-09T00:00:00 1582-10-10T00:00:00 1582-10-11T00:00:00 1582-10-12T00:00:00 1582-10-13T00:00:00 1582-10-14T00:00:00 1582-10-15T00:00:00 joda-time-2.3/src/example/org/joda/example/time/DateTimeBrowser.java0000644000175000017500000012075611564251353025021 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.example.time; /* * Import required Java packages. */ import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.WindowConstants; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.joda.time.DateTime; /** DateTimeBrowser is a Java Swing application which reads a file contining * strings and displays DateTime values in a JTable.

* The input strings must be suitable for instantiation * of DateTime objects. The file is read, and an attempt is made * to instantiate a DateTimeObject from the input string on each file * line.

* Comments (beginning with '#') and blank lines may appear in * the file.

* Error messages may result from invalid input.

* Values calculated from any resulting DateTime objects are placed * in a JTable and displayed in a JFrame.

* * @author Guy Allard * @version 1.0 */ public class DateTimeBrowser extends JFrame { // private String[] mainArgs = null; // Copy of args[] reference. // private LoadedFile currFile = null; // New ones possible at // runtime. private JScrollPane mainSP = null; // Swapped around at runtime // /** * The getter view menu item. */ JMenuItem jmiGetter = null; /** * The hexadecimal view menu item. */ JMenuItem jmiHex = null; /** * The Java Date view menu item. */ JMenuItem jmiDate = null; /** * The java calendar menu item. */ JMenuItem jmiCal = null; // // Done deals. // private final JFileChooser chooser = new JFileChooser(); private final boolean debugf = false; // debugging flag private final boolean debugt = true; // debugging flag /** * This is the main swing application method. It sets up and displays the * initial GUI, and controls execution thereafter. Everything else in * this class is 'private', please read the code. */ public static void main(String[] args) { /* * Developers Notes: * * -No corresponding Junit test class currently * provided. Test by eyeball of the output. * * -Add a menu with Help(About) * --> TBD. * * -Figure out some sane way to set initial default * column sizes. * * -Lots of inner classes here, done in order to keep * all the .class files easily identifiable. Some of * this code is pretty ugly, very procedural in nature. * Lots of very tight coupling between all the classes, * thinly disguised switch statements, etc ..... This * code written on the fly, with almost no thought given * to OO design. * * -Also, I'm not really a GUI guy, so forgive any * transgressions. * */ if ( args.length < 1 ) { System.err.println("File name is required!"); usage(); System.exit(1); } /* * Instantiate a DateTimeBrowser and invoke it's go method, * passing the input argument list. */ new DateTimeBrowser().go( args ); } // main /* * usage A private static method to display usage information to * the user before an error exit. */ private static void usage() { System.err.println("Usage:"); System.err.print("java "); System.err.print(DateTimeBrowser.class.getName()); System.err.println(" "); System.err.println(" contains a list of Strings"); System.err.println("\twhich are valid for DateTime instantiation."); System.err.println(""); System.err.println("\t-Duse.time.zone="); System.err.println("\t\tA valid timezone name. If not specified"); System.err.println("\t\tthe OS/user default is used. If sepcified"); System.err.println("\t\tincorrectly, GMT is quietly used."); System.err.println("\t-Duse.view="); System.err.println("\t\tAn initial view to be displayed."); System.err.println("\t\tValid names are: getter, hex, date, cal"); System.err.println("\t\tIf incorrectly specified, getter is used."); System.err.println("\t\tThis becomes the default view."); } // usage /* * go This method reads the file, creates the table to display, * the window to display it in, and displays the window. * @param fileName the name of the file to read. * @param tryLines An estimate of the number of lines in * the file. */ private void go(String[] args) { mainArgs = args; setDefaultTimeZone(); // let user override if needed // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // JMenuBar menuBar = new JMenuBar(); setJMenuBar( menuBar ); addMenus( menuBar ); /* * Add a fast close listener */ addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible( false ); dispose(); System.exit(0); } } ); // // Load current file, prime tables and JFrame. // currFile = new LoadedFile( mainArgs[0] ); TableView tView = getDefaultTableView(); resetDefaults( tView ); // // Set max size at start, and display the window. // Dimension screenMax = Toolkit.getDefaultToolkit().getScreenSize(); setSize ( screenMax ); setVisible(true); } // // --> Private implementation methods follow. // /* * getDefaultTableView */ private TableView getDefaultTableView() { // No user input. String viewStr = System.getProperty("use.view"); if ( viewStr == null ) { jmiGetter.setEnabled( false ); return new GetterTableView( currFile ); } // Valid user input. if ( viewStr.equalsIgnoreCase("hex") ) { jmiHex.setEnabled( false ); return new HexTableView( currFile ); } else if ( viewStr.equalsIgnoreCase("date") ) { jmiDate.setEnabled( false ); return new DateTableView( currFile ); } else if ( viewStr.equalsIgnoreCase("cal") ) { jmiCal.setEnabled( false ); return new CalTableView( currFile ); } else if ( viewStr.equalsIgnoreCase("getter") ) { jmiGetter.setEnabled( false ); return new GetterTableView( currFile ); } else { // error by user System.err.println("View name: " + viewStr + " invalid."); jmiGetter.setEnabled( false ); return new GetterTableView( currFile ); } } /* * setDefaultTableView */ private void setDefaultTableView(String newView) { System.setProperty( "use.view", newView ); } /* * setDefaultTimeZone */ private void setDefaultTimeZone() { String tzName = System.getProperty("use.time.zone"); if ( tzName == null ) return; // Use OS/user default. // // If tzName is bogus, not understood by the JRE, // 'getTimeZone' returns GMT. // TimeZone toSet = TimeZone.getTimeZone( tzName ); // // Set default to whatever was returned. // TimeZone.setDefault( toSet ); } /* * addMenus */ private void addMenus( JMenuBar menuBar) { // // Create all the menus. // JMenu fileMenu = new JMenu("File"); JMenu viewMenu = new JMenu("View"); // // Add them to the menubar in order. // menuBar.add( fileMenu ); menuBar.add( viewMenu ); // // Create action objects and menu items. // Action open = new OpenAction(); JMenuItem jmiOpen = new JMenuItem( open ); Action exit = new ExitAction(); JMenuItem jmiExit = new JMenuItem( exit ); // // Next Menu // Action getter = new GetterAction(); jmiGetter = new JMenuItem( getter ); getter.setEnabled( true ); // Action hex = new HexAction(); jmiHex = new JMenuItem( hex ); hex.setEnabled( true ); // Action date = new DateAction(); jmiDate = new JMenuItem( date ); date.setEnabled( true ); // Action cal = new CalAction(); jmiCal = new JMenuItem( cal ); cal.setEnabled( true ); // // Build the file menu. // fileMenu.add( jmiOpen ); fileMenu.addSeparator(); fileMenu.add( jmiExit ); // // Build the view menu. // viewMenu.add( jmiGetter ); viewMenu.add( jmiHex ); viewMenu.add( jmiDate ); viewMenu.add( jmiCal ); // // *temp Developer's code // // jmiGetter.setEnabled( false ); // // JMenuItem getter2 = new JMenuItem( "getter2" ); // getter2.addActionListener( new myMouseListener() ); // viewMenu.add( getter2 ); } // end of addMenus /* * A private method to dump the arrays of Object[][] * if desired by the developer * @param objs The array of arrays to be dumped. */ private void dumpObjs(Object[][] objs, PrintStream out ) { for (int i = 0; i < objs.length; ++i) { for (int j = 0; j < objs[i].length; ++j) { out.println(i + " " + j + " " + objs[i][j]); } // for j } // for i } /* * enableAll */ private void enableAllViews() { jmiGetter.setEnabled( true ); jmiHex.setEnabled( true ); jmiDate.setEnabled( true ); jmiCal.setEnabled( true ); } // end of enableAllViews /* * getADate Returns a new DateTime object reference if possible, * otherwise null. * @return retDT A DateTime object reference. */ private DateTime getADate(String s) { DateTime retDT = null; try { retDT = new DateTime( s ); } // the try catch(IllegalArgumentException pe) { // ignore it here, caller sees null } // the catch return retDT; } // getADate // private static final String PADCHARS = "00000000000000000000000000000000"; /* * LPad Return a String, left padded with '0's as specified * by the caller. */ private String LPad(String inStr, int maxLen) { if (inStr.length() >= maxLen) return inStr.toUpperCase(); String zeroes = PADCHARS.substring(0, maxLen - inStr.length()); String retVal = zeroes + inStr; return retVal.toUpperCase(); } /* * resetDefaults */ private void resetDefaults( TableView tView ) { Object[] colNames = tView.getColNames(); Object[][] tableValues = tView.getCalcdValues(); // dumpObjs( tableValues, System.out); JTable table = new JTable( tableValues, colNames ); tView.setViewColumnsWidth( table ); setTitle( tView.getViewTitle() ); // if ( mainSP != null ) getContentPane().remove( mainSP ); mainSP = new JScrollPane( table ); getContentPane().add( mainSP, "Center" ); validate(); } // end of resetDefaults // // ----> Private internal classes follow. // /* * LoadedFile This class represents a file that has been loaded * for viewing. */ private class LoadedFile { // Instance variables String fileName = null; ArrayList fileStrings = null; ArrayList dtObjects = null; int lineGuess = 0; /* * LoadedFile constructor. */ LoadedFile(String fileName) { validateFile( fileName ); this.fileName = fileName; // fileStrings = new ArrayList( lineGuess ); dtObjects = new ArrayList( lineGuess ); try { BufferedReader rdr = new BufferedReader( new FileReader( fileName ) ); String inputLine = null; DateTime calculatedDT = null; int currLine = 0; while( (inputLine = rdr.readLine()) != null ) { currLine++; inputLine = inputLine.trim(); // Ignore blank and comment lines if ( inputLine.length() == 0 ) continue; if ( inputLine.charAt(0) == '#' ) continue; // Ignore lines which fail DateTime construction if ( (calculatedDT = getADate(inputLine)) == null ) { System.err.println("Parse failed for: " + inputLine + " at line number " + currLine); continue; } // Add the input file string and DateTime to lists fileStrings.add( inputLine ); dtObjects.add( calculatedDT ); } rdr.close(); } catch(IOException ioe) { System.err.println("Load of file: " + fileName + " failed!"); ioe.printStackTrace(); System.exit(100); } // Try to be efficient (?really?) fileStrings.trimToSize(); dtObjects.trimToSize(); } // end of LoadedFile() constructor /* * General getters. */ public String getFileName() { return fileName; } public int getLineGuess() { return lineGuess; } public ArrayList getFileStrings() { return fileStrings; } public ArrayList getDtObjects() { return dtObjects; } public int getLoadedFileSize() { if ( dtObjects == null ) return 0; return dtObjects.size(); } /* * validateFile */ private void validateFile(String fileName) { /* * Verify the user specified file exists and can * be read. */ File f = new File( fileName ); if ( !f.exists() || !f.canRead() ) { System.err.println("File: " + mainArgs[0] + " does not exist or cannot be read!"); usage(); System.exit(2); } /* * Try to get a reasonable estimate of the number of lines * in the file. */ // Java does not do this right IMO. The number of bytes in a // file is a // long, but the length of a string is an int. Why? lineGuess = (int)(f.length() / (long)"YYYY-MM-DDTHH:MM:SS".length()); lineGuess += (lineGuess / 10); // // Debugging // if ( false ) { System.out.println("Line guess is: " + lineGuess); } } // end of validateFile(String) } // end of class LoadedFile class /* * TableView This abstract class defines the operations * necessary to create and access the Object arrays * required to create a JTable. */ private abstract class TableView { protected Object[] colNames = null; protected Object[][] calcdValues = null; protected LoadedFile lddFile = null; // TableView(LoadedFile lddFile) { this.lddFile = lddFile; } // public Object[] getColNames() { return colNames; } public Object[][] getCalcdValues() { return calcdValues; } // abstract Object[] genColNames(); abstract Object[][] genCalcdValues(); abstract String getViewTitle(); abstract void setViewColumnsWidth(JTable jt); // } // end of abstract class TableView /* * GetterTableView This class implements the operations * for the GetterView of the Jtable. */ private class GetterTableView extends TableView { // GetterTableView(LoadedFile lddFile) { super(lddFile); setDefaultTableView( "getter" ); colNames = genColNames(); calcdValues = genCalcdValues(); } /* * genCalcdValues is required by the base class. */ Object[][] genCalcdValues() { Object[][] retValues = null; /* * Create an array of Objects that will contain * other arrays of Objects. (This is the 'column' * array). */ ArrayList fileStrings = lddFile.getFileStrings(); ArrayList dtObjects = lddFile.getDtObjects(); int numRows = fileStrings.size(); retValues = new Object[numRows][]; int numCols = colNames.length; // System.err.println("NumCols : " + numCols); /* * Prime the array of arrays of Objects, allocating a new * secondary array for each of the primary array's * elements. */ for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) { retValues[nextStrNum] = new Object[numCols]; // get the 'col' array //**** //* This needs to be sync'd with the colNames array. //**** // Current row, 1st column int column = 0; // working row value String fileString = (String)fileStrings.get(nextStrNum); retValues[nextStrNum][column++] = fileString; // Current row, 2nd column DateTime adt = (DateTime)dtObjects.get(nextStrNum); String adtStr = adt.toString(); retValues[nextStrNum][column++] = adtStr; // Current row, other columns. // Order here must match that specified in the colNames // array. retValues[nextStrNum][column++] = new Integer( adt.getMillisOfSecond() ); retValues[nextStrNum][column++] = new Integer( adt.getSecondOfMinute() ); retValues[nextStrNum][column++] = new Integer( adt.getMinuteOfHour() ); retValues[nextStrNum][column++] = new Integer( adt.getHourOfDay() ); retValues[nextStrNum][column++] = new Integer( adt.getDayOfWeek() ); retValues[nextStrNum][column++] = new Integer( adt.getDayOfMonth() ); retValues[nextStrNum][column++] = new Integer( adt.getDayOfYear() ); retValues[nextStrNum][column++] = new Integer( adt.getWeekOfWeekyear() ); retValues[nextStrNum][column++] = new Integer( adt.getWeekyear() ); retValues[nextStrNum][column++] = new Integer( adt.getMonthOfYear() ); retValues[nextStrNum][column++] = new Integer( adt.getYear() ); // } // the for if ( debugf ) dumpObjs( retValues, System.err ); return retValues; } // end of genTBValues /* * genColNames is required by the base class. */ Object[] genColNames() { Object[] retVal = { "FileString", "toString()", "MillisOfSec", "SecOfMin", "MinOfHr", "HrOfDay", "DayOfWk", "DayOfMon", "DayOfYr", "WeekOfWY", "Weekyear", "MonOfYr", "Year" }; return retVal; } /* * getViewTitle */ String getViewTitle() { return "DateTime.getXXX() Method Calculations" + " : " + TimeZone.getDefault().getDisplayName() + " : " + " Record Count " + currFile.getLoadedFileSize(); } /* * setViewColumnLengths */ void setViewColumnsWidth(JTable jt) { /* * Resize column 0, 1 */ TableColumnModel colmodel = jt.getColumnModel(); TableColumn col0 = colmodel.getColumn(0); col0.setPreferredWidth(200); TableColumn col1 = colmodel.getColumn(1); col1.setPreferredWidth(200); return; } } // end of class getterTableView /* * HexView This class implements the operations for * the HexView of the file. */ private class HexTableView extends TableView { // HexTableView(LoadedFile lddFile) { super(lddFile); setDefaultTableView( "hex" ); colNames = genColNames(); calcdValues = genCalcdValues(); } /* * genCalcdValues is required by the base class. */ Object[][] genCalcdValues() { Object[][] retValues = null; /* * Create an array of Objects that will contain * other arrays of Objects. (This is the 'column' * array). */ ArrayList fileStrings = lddFile.getFileStrings(); ArrayList dtObjects = lddFile.getDtObjects(); int numRows = fileStrings.size(); retValues = new Object[numRows][]; int numCols = colNames.length; // System.err.println("NumCols : " + numCols); String fs = "yyyy-MM-dd'T'HH:mm:ss"; DateFormat df = new SimpleDateFormat( fs ); /* * Prime the array of arrays of Objects, allocating a new * secondary array for each of the primary array's * elements. */ for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) { retValues[nextStrNum] = new Object[numCols]; // get the 'col' array //**** //* This needs to be sync'd with the colNames array. //**** // Current row, 1st column int column = 0; String fileString = (String)fileStrings.get(nextStrNum); retValues[nextStrNum][column++] = fileString; // Current row, 2nd column DateTime adt = (DateTime)dtObjects.get(nextStrNum); String adtStr = adt.toString(); retValues[nextStrNum][column++] = adtStr; // Current row, other columns. // Order here must match that specified in the colNames // array. long lVal = adt.getMillis(); Long millis = new Long( lVal ); retValues[nextStrNum][column++] = millis; String hexVal = Long.toHexString( lVal ); String octalVal = Long.toOctalString( lVal ); retValues[nextStrNum][column++] = "0"+ LPad(octalVal,22); retValues[nextStrNum][column++] = "0x" + LPad(hexVal,16); // Date javaDate = null; try { javaDate = df.parse( fileString ); } catch(ParseException e) { System.err.println("Parse failed for : " + fileString); // pe.printStackTrace(); } // lVal = javaDate.getTime(); millis = new Long( lVal ); hexVal = Long.toHexString( lVal ); octalVal = Long.toOctalString( lVal ); retValues[nextStrNum][column++] = millis; retValues[nextStrNum][column++] = "0"+ LPad(octalVal,22); retValues[nextStrNum][column++] = "0x" + LPad(hexVal,16); // } // the for if ( debugf ) dumpObjs( retValues, System.err ); return retValues; } // end of genTBValues /* * genColNames is required by the base class. */ Object[] genColNames() { Object[] retVal = { "FileString", "toString()", "JDT-millis", "JDT-Oct", "JDT-Hex", "Date-millis", "Date-Oct", "Date-Hex" }; return retVal; } /* * getViewTitle */ String getViewTitle() { return "View the long values" + " : " + TimeZone.getDefault().getDisplayName() + " : " + " Record Count " + currFile.getLoadedFileSize(); } /* * setViewColumnLengths */ void setViewColumnsWidth(JTable jt) { return; } } // end of class HexTableView /* * DateTableView This class implements the operations for * the java.util.Date of the file. */ private class DateTableView extends TableView { // DateTableView(LoadedFile lddFile) { super(lddFile); setDefaultTableView( "date" ); colNames = genColNames(); calcdValues = genCalcdValues(); } /* * genCalcdValues is required by the base class. */ Object[][] genCalcdValues() { Object[][] retValues = null; /* * Create an array of Objects that will contain * other arrays of Objects. (This is the 'column' * array). */ ArrayList fileStrings = lddFile.getFileStrings(); ArrayList dtObjects = lddFile.getDtObjects(); int numRows = fileStrings.size(); retValues = new Object[numRows][]; int numCols = colNames.length; // System.err.println("NumCols : " + numCols); /* * Prime the array of arrays of Objects, allocating a new * secondary array for each of the primary array's * elements. */ for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) { retValues[nextStrNum] = new Object[numCols]; // get the 'col' array //**** //* This needs to be sync'd with the colNames array. //**** // Current row, 1st column int column = 0; String fileString = (String)fileStrings.get(nextStrNum); retValues[nextStrNum][column++] = fileString; // Current row, 2nd column DateTime adt = (DateTime)dtObjects.get(nextStrNum); String adtStr = adt.toString(); retValues[nextStrNum][column++] = adtStr; // Current row, other columns. // Order here must match that specified in the colNames // array. long lVal = adt.getMillis(); java.util.Date jDate = new java.util.Date( lVal ); retValues[nextStrNum][column++] = new Integer( jDate.getSeconds() ); retValues[nextStrNum][column++] = new Integer( jDate.getMinutes() ); retValues[nextStrNum][column++] = new Integer( jDate.getHours() ); retValues[nextStrNum][column++] = new Integer( jDate.getDay() ); retValues[nextStrNum][column++] = new Integer( jDate.getDate() ); retValues[nextStrNum][column++] = new Integer( jDate.getMonth() ); retValues[nextStrNum][column++] = new Integer( jDate.getYear() ); // } // the for if ( debugf ) dumpObjs( retValues, System.err ); return retValues; } // end of genTBValues /* * genColNames is required by the base class. */ Object[] genColNames() { Object[] retVal = { "FileString", // 0 "toString()", // 1 "Seconds", // 2 "Minutes", // 3 "Hours", // 4 "Day Of Week", // 5 "Day Of Month", // 6 "Month", // 7 "Year" // 8 }; return retVal; } /* * getViewTitle */ String getViewTitle() { return "java.util.Date getXXX" + " : " + TimeZone.getDefault().getDisplayName() + " : " + " Record Count " + currFile.getLoadedFileSize(); } /* * setViewColumnLengths */ void setViewColumnsWidth(JTable jt) { /* * Resize column 0, 1 */ TableColumnModel colmodel = jt.getColumnModel(); TableColumn col0 = colmodel.getColumn(0); col0.setPreferredWidth(150); TableColumn col1 = colmodel.getColumn(1); col1.setPreferredWidth(150); return; } } // end of class DateTableView /* * CalTableView This class implements the operations for * the java.util.Date of the file. */ private class CalTableView extends TableView { // CalTableView(LoadedFile lddFile) { super(lddFile); setDefaultTableView( "cal" ); colNames = genColNames(); calcdValues = genCalcdValues(); } /* * genCalcdValues is required by the base class. */ Object[][] genCalcdValues() { Object[][] retValues = null; /* * Create an array of Objects that will contain * other arrays of Objects. (This is the 'column' * array). */ ArrayList fileStrings = lddFile.getFileStrings(); ArrayList dtObjects = lddFile.getDtObjects(); int numRows = fileStrings.size(); retValues = new Object[numRows][]; int numCols = colNames.length; // System.err.println("NumCols : " + numCols); /* * Prime the array of arrays of Objects, allocating a new * secondary array for each of the primary array's * elements. */ for (int nextStrNum = 0; nextStrNum < fileStrings.size(); ++ nextStrNum) { retValues[nextStrNum] = new Object[numCols]; // get the 'col' array //**** //* This needs to be sync'd with the colNames array. //**** // Current row, 1st column int column = 0; String fileString = (String)fileStrings.get(nextStrNum); retValues[nextStrNum][column++] = fileString; // Current row, 2nd column DateTime adt = (DateTime)dtObjects.get(nextStrNum); String adtStr = adt.toString(); retValues[nextStrNum][column++] = adtStr; // Current row, other columns. // Order here must match that specified in the colNames // array. long lVal = adt.getMillis(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime( new Date( lVal ) ); cal.setMinimalDaysInFirstWeek(4); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.MILLISECOND ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.SECOND ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.MINUTE ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.HOUR_OF_DAY ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.DAY_OF_WEEK ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.DAY_OF_MONTH ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.DAY_OF_YEAR ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.WEEK_OF_YEAR ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.MONTH ) ); retValues[nextStrNum][column++] = new Integer( cal.get( Calendar.YEAR ) ); // } // the for if ( debugf ) dumpObjs( retValues, System.err ); return retValues; } // end of genTBValues /* * genColNames is required by the base class. */ Object[] genColNames() { Object[] retVal = { "FileString", // 0 "toString()", // 1 "Millis", // 2 "Sec", // 3 "Min", // 4 "HrOfDay", // 5 "DayOfWeek", // 6 "DayOfMon", // 7 "DayOfYr", // 8 "WkofYr", // 9 "MonOfYr", // 10 "Year" // 11 }; return retVal; } /* * getViewTitle */ String getViewTitle() { return "java.util.Calendar.get(int)" + " : " + TimeZone.getDefault().getDisplayName() + " : " + " Record Count " + currFile.getLoadedFileSize(); } /* * setViewColumnLengths */ void setViewColumnsWidth(JTable jt) { /* * Resize column 0, 1 */ TableColumnModel colmodel = jt.getColumnModel(); TableColumn col0 = colmodel.getColumn(0); col0.setPreferredWidth(175); TableColumn col1 = colmodel.getColumn(1); col1.setPreferredWidth(175); return; } } // end of class CalTableView /* * OpenAction */ private class OpenAction extends AbstractAction { /* * Constructor */ public OpenAction() { super("Open"); } // end of ctor /* * actionPerformed */ public void actionPerformed(ActionEvent e) { int result = chooser.showOpenDialog( DateTimeBrowser.this ); String canPath = null; if ( result == JFileChooser.APPROVE_OPTION ) { File chosenFile = chooser.getSelectedFile(); try { canPath = chosenFile.getCanonicalPath(); } catch(IOException ioe) { System.err.println( "I/O Error on file: " + chosenFile ); // Ignore it for now. } enableAllViews(); currFile = new LoadedFile( canPath ); TableView tView = getDefaultTableView(); resetDefaults( tView ); } // end of if a file actually chosen. } // end of actionPerformed } // end of class OpenAction /* * ExitAction */ private class ExitAction extends AbstractAction { /* * Constructor */ public ExitAction() { super("Exit"); } // end of ctor /* * actionPerformed */ public void actionPerformed(ActionEvent e) { DateTimeBrowser.this.setVisible( false ); DateTimeBrowser.this.dispose(); System.exit(0); } // end of actionPerformed } // end of class OpenAction /* * GetterAction */ private class GetterAction extends AbstractAction { /* * Constructor */ public GetterAction() { super("Getter"); } // end of ctor /* * actionPerformed */ public void actionPerformed(ActionEvent e) { TableView tView = new GetterTableView( currFile ); resetDefaults( tView ); enableAllViews(); jmiGetter.setEnabled( false ); } // end of actionPerformed } // end of class OpenAction /* * HexAction */ private class HexAction extends AbstractAction { /* * Constructor */ public HexAction() { super("Hex"); } // end of ctor /* * actionPerformed */ public void actionPerformed(ActionEvent e) { TableView tView = new HexTableView( currFile ); resetDefaults( tView ); enableAllViews(); jmiHex.setEnabled( false ); } // end of actionPerformed } // end of class OpenAction /* * DateAction */ private class DateAction extends AbstractAction { /* * Constructor */ public DateAction() { super("Date"); } // end of ctor /* * actionPerformed */ public void actionPerformed(ActionEvent e) { TableView tView = new DateTableView( currFile ); resetDefaults( tView ); enableAllViews(); jmiDate.setEnabled( false ); } // end of actionPerformed } // end of class DateAction /* * CalAction */ private class CalAction extends AbstractAction { /* * Constructor */ public CalAction() { super("Calendar"); } // end of ctor /* * actionPerformed */ public void actionPerformed(ActionEvent e) { TableView tView = new CalTableView( currFile ); resetDefaults( tView ); enableAllViews(); jmiCal.setEnabled( false ); } // end of actionPerformed } // end of class CalAction } // class DateTimeBrowser joda-time-2.3/src/example/org/joda/example/time/DateTimeBrowser.README.txt0000644000175000017500000000255311564251216025643 0ustar ebourgebourg- Joda jar(s) need to be in CLASSPATH. So does the path which leads to this program's class and inner class files. - Before running set the default time zone for your environment (whatever it is will be displayed in the window title). (See more on TimeZone control below.) - Once displayed, table columns can resized and rearranged by drag-n-drop. - Simple example command lines: # The default way - java org.joda.example.DateTimeBrowser DateTimeFile.dat # Start with the hex view of DateTimes - java org.joda.example.DateTimeBrowser -Duse.view=hex DateTimeFile.dat View Control: The initial view can be controlled from the command line with: -Duse.view= Valid values are: getter, hex, date, cal. Getter is used if not specified or an invalid value is specified. TimeZone Control: The TZ used can be controlled from the command line with: -Duse.time.zone=xxx If not specified, the OS/user default is used. 'xxx' should be a valid time zone (e.g. EST). If specified and 'xxx' is bogus/nonextant, GMT is used. Regards and Enjoy, Guy Allard 2002-04-18 Last Update: 2002-04-27 joda-time-2.3/src/example/org/joda/example/time/AgeCalculator.java0000644000175000017500000002755311564251363024471 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.example.time; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.chrono.ISOChronology; /** * AgeCalculator is a small Swing application that computes age from a specific * birthdate and time zone. Age is broken down into multiple fields, which can * be independently disabled. * * @author Brian S O'Neill */ public class AgeCalculator extends JFrame { static final int YEARS = 1, MONTHS = 2, DAYS = 3, WEEKYEARS = 4, WEEKS = 5, HOURS = 101, MINUTES = 102, SECONDS = 103; public static void main(String[] args) throws Exception { new AgeCalculator().show(); } static JComponent fixedSize(JComponent component) { component.setMaximumSize(component.getPreferredSize()); return component; } static JComponent fixedHeight(JComponent component) { Dimension dim = component.getMaximumSize(); dim.height = component.getPreferredSize().height; component.setMaximumSize(dim); return component; } Chronology iChronology; private String iBirthdateStr; private FieldSet[] iFieldSets; private Timer iTimer; public AgeCalculator() { super(); iChronology = ISOChronology.getInstance(); iBirthdateStr = "1970-01-01T00:00:00"; setTitle("Age Calculator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addMainArea(getContentPane()); addNotify(); Dimension size = getPreferredSize(); setSize(size); Dimension screenSize = getToolkit().getScreenSize(); setLocation(screenSize.width / 2 - size.width / 2, screenSize.height / 2 - size.height / 2); iTimer = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent e) { updateResults(); } }); iTimer.setInitialDelay(0); iTimer.start(); } private void addMainArea(Container container) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); addTopArea(panel); panel.add(Box.createVerticalStrut(10)); addBottomArea(panel); panel.add(Box.createVerticalGlue()); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); container.add(panel); } private void addTopArea(Container container) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(fixedHeight(new JLabel("Birthdate"))); panel.add(Box.createHorizontalStrut(10)); final JTextField birthdateField = new JTextField(iBirthdateStr + ' '); Document doc = birthdateField.getDocument(); doc.addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { update(e); } public void removeUpdate(DocumentEvent e) { update(e); } public void changedUpdate(DocumentEvent e) { update(e); } private void update(DocumentEvent e) { iBirthdateStr = birthdateField.getText(); updateResults(); } }); panel.add(fixedHeight(birthdateField)); panel.add(Box.createHorizontalStrut(10)); Object[] ids = DateTimeZone.getAvailableIDs().toArray(); final JComboBox zoneSelector = new JComboBox(ids); zoneSelector.setSelectedItem(DateTimeZone.getDefault().getID()); panel.add(fixedSize(zoneSelector)); zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String id = (String)zoneSelector.getSelectedItem(); iChronology = ISOChronology.getInstance(DateTimeZone.forID(id)); updateResults(); } }); container.add(fixedHeight(panel)); } private void addBottomArea(Container container) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); ItemListener listener = new ItemListener() { public void itemStateChanged(ItemEvent e) { updateResults(); } }; iFieldSets = new FieldSet[] { new FieldSet("Month Based", new FieldGroup[] { new FieldGroup(listener, "Years", YEARS), new FieldGroup(listener, "Months", MONTHS), new FieldGroup(listener, "Days", DAYS), new FieldGroup(listener, "Hours", HOURS), new FieldGroup(listener, "Minutes", MINUTES), new FieldGroup(listener, "Seconds", SECONDS) }) , new FieldSet("Week Based", new FieldGroup[] { new FieldGroup(listener, "Weekyears", WEEKYEARS), new FieldGroup(listener, "Weeks", WEEKS), new FieldGroup(listener, "Days", DAYS), new FieldGroup(listener, "Hours", HOURS), new FieldGroup(listener, "Minutes", MINUTES), new FieldGroup(listener, "Seconds", SECONDS) }) }; for (int i=0; i 0) { panel.add(Box.createHorizontalStrut(10)); } iFieldSets[i].addTo(panel); } panel.add(Box.createVerticalGlue()); container.add(fixedHeight(panel)); } private void updateResults() { try { DateTime dt = new DateTime(iBirthdateStr.trim(), iChronology); long minuend = System.currentTimeMillis(); long subtrahend = dt.getMillis(); for (int i=0; i Joda.org http://www.joda.org/ Joda-Time http://www.joda.org/joda-time/

joda-time-2.3/src/site/resources/0000755000175000017500000000000012205344143016322 5ustar ebourgebourgjoda-time-2.3/src/site/resources/css/0000755000175000017500000000000012205344143017112 5ustar ebourgebourgjoda-time-2.3/src/site/resources/css/site.css0000644000175000017500000000476611564251363020615 0ustar ebourgebourgbody, td, select, input, li{ font-family: Helvetica, Arial, sans-serif; font-size: 13px; background-color: #fff; } a { text-decoration: none; } a:link { color:#009; } a:visited { color:#009; } a:active, a:hover { text-decoration: underline; } a.externalLink, a.externalLink:link, a.externalLink:visited, a.externalLink:active, a.externalLink:hover { background: url(../images/external.png) right center no-repeat; padding-right: 15px; } a.newWindow, a.newWindow:link, a.newWindow:visited, a.newWindow:active, a.newWindow:hover { background: url(../images/newwindow.png) right center no-repeat; padding-right: 18px; } h2 { font-family: Verdana, Helvetica, Arial, sans-serif; padding: 4px 4px 4px 6px; border: 1px solid #999; color: #006; background-color: #eef; font-weight:bold; font-size: 16px; margin-top: 4px; margin-bottom: 6px; } h3 { padding: 4px 4px 4px 6px; border: 1px solid #aaa; color: #006; background-color: #eee; font-weight: normal; font-size: 14px; margin-top: 4px; margin-bottom: 6px; } p, ul { font-size: 13px; margin-top: 4px; margin-bottom: 6px; } #banner { background-color: #eef; border-bottom: 1px solid #aaa; padding: 8px; } #bannerLeft, #bannerRight { font-size: 30px; color:black; background-color:white; border: 1px solid #999; padding: 0px 5px; } #banner a:hover { text-decoration:none; } #breadcrumbs { padding-top: 1px; padding-bottom: 2px; border-bottom: 1px solid #aaa; background-color: #ddf; } #leftColumn { margin: 8px 0 8px 4px; border: 1px solid #999; background-color: #eef; } #navcolumn { padding: 6px 4px 0 6px; } #navcolumn h5 { font-size: 12px; border-bottom: 1px solid #aaaaaa; padding-top: 2px; font-weight: normal; } #navcolumn li { font-size: 12px; padding-left: 12px; background-color: #eef; } #navcolumn a:active, #navcolumn a:hover { text-decoration: none; } #lastPublished { font-size: 10px; } table.bodyTable th { color: white; background-color: #bbb; text-align: left; font-weight: bold; font-size: 13px; } table.bodyTable th, table.bodyTable td { font-size: 13px; } table.bodyTable tr.a { background-color: #ddd; } table.bodyTable tr.b { background-color: #eee; } .source { border: 1px solid #999; padding: 8px; margin: 6px; } #footer { background-color: #eef; border-top: 1px solid #999; } body { padding-bottom: 0px; } joda-time-2.3/src/site/resources/download.html0000644000175000017500000000025312203443356021023 0ustar ebourgebourg OpenGamma joda-time-2.3/src/site/xdoc/0000755000175000017500000000000012205344143015245 5ustar ebourgebourgjoda-time-2.3/src/site/xdoc/upgradeto140.xml0000644000175000017500000000542312203443564020217 0ustar ebourgebourg Java date and time API - Upgrade from 1.3 to 1.4 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.3 to version 1.4. Joda-Time version 1.4 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the fifth full release of Joda-Time. This release focuses on new features, but also include some bug fixes. We recommend JDK 1.3 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. * Please also check out our related projects * * http://www.joda.org/joda-time/related.html * Enhancements since 1.3 ---------------------- - Years/Months/Weeks/Days/Hours/Minutes/Seconds New group of single field period classes These allow applications to specify a specific field in method signatures and calculations Methods are provided to convert between most of these based on standard length periods - Period.ZERO Add zero-length constant to Period - PeriodFormatBuilder.append(PeriodPrinter,PeriodParser) This method completes the API of PeriodFormatBuilder in the style of DateTimeFormatBuilder Compatibility with 1.3 ---------------------- Binary compatible - Yes Source compatible - Yes, except If you subclassed AbstractReadableInstantFieldProperty (unlikely) then you now need to override getChronology() to re-enable the equals() and hashCode() methods. Serialization compatible - Yes Data compatible - Yes - DateTimeZone data updated to version 2006o Semantic compatible - Yes Deprecations since 1.3 ---------------------- Bug fixes since 1.3 ------------------- - GJChronology Text value of ReadablePartial fields was always a decimal number. - Comparisons of Chronology instances by identity [1576727] Some comparisons of Chronology instances were performed using == This worked fine in most cases due to agressive caching, however it failed when using LenientChronology and other wrapping chronologies which do not have caching Comparison is now via equals(), and involved adding equals() methods to a number of classes. In addition, subclasses of AbstractReadableInstantFieldProperty must now implement getChronology().

joda-time-2.3/src/site/xdoc/upgradeto162.xml0000644000175000017500000000567512203443641020230 0ustar ebourgebourg Java date and time API - Upgrade from 1.6.1 to 1.6.2 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.6.1 to version 1.6.2. Joda-Time version 1.6.2 ----------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is a patch release for Joda-Time 1.6 and 1.6.1. This release only contains bug fixes. We recommend all users of 1.6 upgrade to 1.6.2. We recommend JDK 1.4 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** Compatibility with 1.6.1 ------------------------ Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2010l Semantic compatible - Yes Bug fixes since 1.6.1 --------------------- - DateTimeZone.getDefault [3048468,3056104] Handle missing user.timezone system property on Android that resulted in stack overflow RELEASE NOTES for v1.6 to v1.6.1 ================================ Compatibility with 1.6 ---------------------- Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2010k (2010l in v1.6.2) Semantic compatible - Yes Deprecations since 1.6 ---------------------- - DateTimeFormatter.getChronolgy() [2783325] Incorrect spelling - new method DateTimeFormatter.getChronology() Bug fixes since 1.6 ------------------- - LocalTime.fromDateFields() Now handles times based on java.util.Date before 1970 - LocalDate.toInterval() [2487417] Now handles time zones which have no midnight at DST cutover - DateTimeZone.convertLocalToUTC [2903029] Now handles date after last ever DST change - Period formatting concurrency [2820871] Fix possible concurrency hole in PeriodFormatBuilder.Separator - Classloading CachedDateTimeZone could invalidate state [2935625] Default time zone now lazily loaded - DateTimeUtils shared static variable now volatile [2986043] - Time zone compiler now handles 24:00 [2804258] - Time zone compiler now handles non-UTC better - Assorted Javadoc clarifications, including [2721880] Enhancements since 1.6 ---------------------- - None

joda-time-2.3/src/site/xdoc/key_instant.xml0000644000175000017500000001007512116366117020330 0ustar ebourgebourg Java date and time API - Instant Stephen Colebourne

The most frequently used concept in Joda-Time is that of the instant. An Instant is defined as an instant in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z. This definition of milliseconds is consistent with that of the JDK in Date or Calendar. Interoperating between the two APIs is thus simple.

The millisecond instant can be converted to any date time field using a Chronology. To assist with this, methods are provided on DateTime that act as getters for the most common date and time fields. More powerful access to the field can be obtained via its property. DateTime dt = new DateTime(); // current time int month = dt.getMonth(); // gets the current month int month = dt.month().get(); // alternative way to get value String monthStr = dt.month().getAsText(); // gets the month name

To deal with local times (no time zone), or with date only or time only concepts, you should use the partial classes.

Within Joda-Time an instant is represented by the ReadableInstant interface. There are four implementations of the interface provided:

  • Instant - A simple immutable implementation which is restricted to the UTC time zone and is intended for time zone and calendar neutral data transfer
  • DateTime - The most commonly used class in the library, and an immutable representation of a date and time with calendar and time zone
  • DateMidnight - Similar to DateTime and also immutable but with the time component forced to be midnight (at the start of a day)
  • MutableDateTime - A mutable representation of date and time with calendar and time zone
We recommend the immutable implementations for general usage.

The code can be used in various ways: // setup date object for midday on Christmas 2004 (ISO year 2004) DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0); // get the year, 2004 int year = dt.getYear(); // get the day of week index 1 (Monday) to 7 (Sunday) int dow = dt.getDayOfWeek(); // get the text, such as 'Tuesday' String dowStr = dt.dayOfWeek().getAsText(); Compared to GregorianCalendar Joda-Time classes use 1-12 for months, and are immutable in the standard implementations. It is also easy to convert to and from the JDK classes. // construct DateTime from JDK Date Date jdkDate = new Date(); DateTime dt = new DateTime(jdkDate); // construct Calendar from DateTime (could also construct a Date) GregorianCalendar cal = dt.toGregorianCalendar();

Note that the interface ReadableInstant should not be used like the collections API. The interface only contains the core subset of the operations of DateTime. You should use the interface only when you feel the need to be flexible about future changes to the object passed into a method. You might also want to consider the ReadableDateTime interface which extends ReadableInstant to provide additional methods.

Joda-Time defines a null instant as the current time. Thus, when a method is defined as taking a ReadableInstant, passing null in will be the same as passing in an instant set to the current time.

joda-time-2.3/src/site/xdoc/upgradeto230.xml0000644000175000017500000001220212203457016020205 0ustar ebourgebourg Java date and time API - Upgrade from 2.2 to 2.3 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 2.2 to version 2.3. Joda-Time version 2.3 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This release contains enhancements, bug fixes and a time zone update. The release runs on JDK 5 or later. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** Enhancements since 2.2 ---------------------- - Interval/MutableInterval .isEqual() [#20] Add method to compare intervals ignoring the chronology https://github.com/JodaOrg/joda-time/issues/20 - Chronology classes now define equals methods [#36] Previously, the Chronology classes relied on caching in factory methods to guarantee instances were singletons Now, there are dedicated, normal, equals methods This will aid weird cases where deserialization or similar avoids the caches It will make no difference to most users - Maximum size for pattern cache [#49] Sets a maximum size for the cache to avoid memory issues - Add LocalDateTime.toDate(TimeZone) [#48] Provides an alternate way to create a java.util.Date that avoids some synchronization - Home page moved http://www.joda.org/joda-time Compatibility with 2.2 ---------------------- Build system - Yes Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2013d Semantic compatible - Yes, except - DateTimeZone is now limited to offsets from -23:59:59.999 to +23:59:59.999 - BasicChronology now defines an equals method This which would affect you if you subclassed it (unlikely) - GJChronology now has a minimum cutover instant of 0001-01-01 (Gregorian) Its unlikely you have it set earlier than this If you did your code was broken anyway Deprecations since 2.2 ---------------------- - DateMidnight [#41] This class is flawed in concept The time of midnight occasionally does not occur in some time-zones This is a result of a daylight savings time from 00:00 to 01:00 DateMidnight is essentially a DateTime with a time locked to midnight Such a concept is more generally a poor one to use, given LocalDate Replace DateMidnight with LocalDate Or replace it with DateTime, perhaps using the withTimeAtStartOfDay() method Bug fixes since 2.2 ------------------- - ZoneInfoCompiler and DateTimeZoneBuilder multi-threading [#18] A thread local variable was previously only initialised in one thread causing NPE https://github.com/JodaOrg/joda-time/issues/18 - Short time-zone name parsing failed to match the longest name This affected two short names where one is a short form of the second such as "UT" and "UTC" - Days.daysBetween fails for MonthDay [#22] Incorrect calculation around leap years - DateTimeZone failed to validate offsets [#43] Previously, there was little validation, resulting in the ability to create large offsets Those offsets could fail in other parts of the library Now, it is limited to -23:59:59.999 to +23:59:59.999 - DateTimeZone.forOffsetHoursMinutes failed to allow offsets from -00:01 to -00:59 [#42] The forOffsetHoursMinutes() method could not create an offset from -00:01 to -00:59 This was due to an inappropriate design A backwards compatible change to the input handling has been made forOffsetHoursMinutes(0, -15) now creates -00:15 - DateTimeFormatter.parseInto [#21] Fix parseInto() where it obtains the default year for parsing from the ReadWritableInstant Previously, the wrong year could be obtained at the start or end of the year in non UTC zones Now obtains the year from the ReadWritableInstant using the chronology of the ReadWritableInstant - Better thread-safety in ISODateTimeFormat [#45] - Fix GJChronology.plus/minus across cutover and year zero [#28] When subtracting a number of years from a date in the GJChronology there are two considerations The cutover date might be crossed, and year zero might be crossed (there is no year zero in GJ) Previously, each were handled separately, but not together. Now it is fixed As part of this change, the minimum cutover instant was set to 0001-01-01 (Gregorian) Scala -------- Joda-Time uses annotations from Joda-Convert. In the Java programming language, this dependency is optional, however in Scala it is not. Scala users must manually add the Joda-Convert v1.2 dependency.

joda-time-2.3/src/site/xdoc/upgradeto161.xml0000644000175000017500000000464412203443635020225 0ustar ebourgebourg Java date and time API - Upgrade from 1.6 to 1.6.1 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.6 to version 1.6.1. Joda-Time version 1.6.1 ----------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is a patch release for Joda-Time 1.6. This release only contains bug fixes. We recommend all users of 1.6 upgrade to 1.6.1. We recommend JDK 1.4 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** Compatibility with 1.6 ---------------------- Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2010k Semantic compatible - Yes Deprecations since 1.6 ---------------------- - DateTimeFormatter.getChronolgy() [2783325] Incorrect spelling - new method DateTimeFormatter.getChronology() Bug fixes since 1.6 ------------------- - LocalTime.fromDateFields() Now handles times based on java.util.Date before 1970 - LocalDate.toInterval() [2487417] Now handles time zones which have no midnight at DST cutover - DateTimeZone.convertLocalToUTC [2903029] Now handles date after last ever DST change - Period formatting concurrency [2820871] Fix possible concurrency hole in PeriodFormatBuilder.Separator - Classloading CachedDateTimeZone could invalidate state [2935625] Default time zone now lazily loaded - DateTimeUtils shared static variable now volatile [2986043] - Time zone compiler now handles 24:00 [2804258] - Time zone compiler now handles non-UTC better - Assorted Javadoc clarifications, including [2721880] Enhancements since 1.6 ---------------------- - None

joda-time-2.3/src/site/xdoc/cal_gj.xml0000644000175000017500000000465411564251363017227 0ustar ebourgebourg Java date and time API - GregorianJulian (GJ) calendar system Stephen Colebourne

The GregorianJulian calendar system is the fusion of the two calendar systems in the Christian or Roman tradition. This calendar system is widely used today throughout the world, and is especially useful for historical work.

The GregorianJulian calendar is a combination of two separate calendar systems, the Gregorian and the Julian. The switch from one to the other occurs at a configurable date. The default date is 1582-10-15, as defined by Pope Gregory XIII.

The two calendar systems differ mainly in their accuracy of recording leap years. The Julian calendar defines a leap year as being once every four years. The Gregorian calendar adds two extra rules to state that years divisible by 100 are not leap, but those divisible by 400 are.

Joda-Time defines this calendar system using the GJChronology. This is a replacement for the JDK GregorianCalendar. If you intend to only refer to modern dates (after 1583) then you should use the Joda-Time default of ISO chronology.

References

Within Joda-Time the GregorianJulian calendar system can be used by obtaining an instance of GJChronology. This is normally created using the factory method GJChronology.getInstance(). This is then passed into the constructors of the main date and time classes.

// setup date object for the Battle of Hastings in 1066 Chronology chrono = GJChronology.getInstance(); DateTime dt = new DateTime(1066, 10, 14, 10, 0, 0, 0, chrono);

If you want to change the cutover date between Julian and Gregorian, you will need to use the other factory methods on GJChronology.

joda-time-2.3/src/site/xdoc/cal_iso.xml0000644000175000017500000001153011564251363017410 0ustar ebourgebourg Java date and time API - ISO8601 calendar system Stephen Colebourne

The ISO 8601 calendar system is the default implementation within Joda-Time. The standard formalises the Gregorian calendar system used by the modern business world.

The ISO8601 standard was created by the International Organization for Standards based in Geneva. It aims to eliminate the risk of misinterpretting dates and times when representations are passed between systems and across national boundaries. We are unable to provide a direct link to the standard as it is a paid-for document. However some ISO8601 links may be useful.

The ISO8601 standard is based on the proleptic Gregorian calendar. This makes it fully compatible with the calendar system used in most countries today. The proleptic means that the Gregorian rules for leap years are applied for all time, thus the ISO8601 standard gives different results for dates before the year 1583 when the historic cutover from the Julian calendar occurred.

The standard sets out a framework within which dates and times can be represented. It offers many choices, however in reality there are three main date representations, year month day, year dayOfYear and year week dayOfWeek.

References

yyyy-mm-ddTHH:MM:SS.SSS
This is the most common format of ISO8601 and separates the fields by dashes. The fields are:

  • four digit year
  • two digit month, where 01 is Janurary and 12 is December
  • two digit day of month, from 01 to 31
  • two digit hour, from 00 to 23
  • two digit minute, from 00 to 59
  • two digit second, from 00 to 59
  • three decimal places for milliseconds if required
This format is used in XML standards for passing dates and times.

yyyy-dddTHH:MM:SS.SSS
This format of ISO8601 has the following fields:

  • four digit year
  • three digit day of year, from 001 to 366
  • two digit hour, from 00 to 23
  • two digit minute, from 00 to 59
  • two digit second, from 00 to 59
  • three decimal places for milliseconds if required

yyyy-Www-dTHH:MM:SS.SSS
This format of ISO8601 has the following fields:

  • four digit weekyear, see rules below
  • two digit week of year, from 01 to 53
  • one digit day of week, from 1 to 7 where 1 is Monday and 7 is Sunday
  • two digit hour, from 00 to 23
  • two digit minute, from 00 to 59
  • two digit second, from 00 to 59
  • three decimal places for milliseconds if required
Weeks are always complete, and the first week of a year is the one that includes the first Thursday of the year. This definition can mean that the first week of a year starts in the previous year, and the last week finishes in the next year. The weekyear field is defined to refer to the year that owns the week, which may differ from the actual year.

Within Joda-Time the ISO8601 calendar system is the default. As such, all methods that take a chronology as a parameter will use the ISO chronology if null is passed in. There is almost always a version of the method without the chronology parameter, and this will default to ISO chronology.

The actual chronology class is ISOChronology. This is normally created if required using the factory method ISOChronology.getInstance().

// setup date object for midday on Christmas 2004 (default time zone) DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0); // or specify the chronology explicitly Chronology chrono = ISOChronology.getInstance(); DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0, chrono); // or use the default null handling behaviour DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0, (Chronology) null);
joda-time-2.3/src/site/xdoc/upgradeto200.xml0000644000175000017500000003173012203443646020215 0ustar ebourgebourg Java date and time API - Upgrade from 1.6 to 2.0 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.6 to version 2.0. Joda-Time version 2.0 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the eighth release of Joda-Time. This release contains enhancements, bug fixes and a time zone update. We require JDK 1.5 or later as features such as generics are used. It may be possible to use retroweaver to compile this under an earlier JDK but we haven't tried. ****************************************************************************** Compatibility The change in major version indicates compatibility issues. Please read the detailed notes below. If your code just _used_ Joda-Time and had no deprecation warnings then you will _probably_ see no issues. ****************************************************************************** Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** Enhancements since 1.6 ---------------------- - Move to Java 5, with generics See compatability notes. - Appropriate Java Memory Model settings The fields in the Base* classes, such as BaseDateTime and BaseDuration have been made volatile/final. This was necessary to comply with the Java Memory Model to ensure correct immutable behaviour. There should be no adverse effect from this change. - Add YearMonth, useful for credit card dates [1863090] - Add MonthDay, useful for birth dates without year - System clock can now be controlled by applications DateTimeUtils.MillisProvider is now public - Word based period formatters available in multiple languages [1252708] PeriodFormat provides a resource bundle based language formatter Currently supported (via online translators) are English, German, Dutch, French, Spanish and Portuguese. Corrections and additional languages welcome. - Static now() methods available on all major types [3134566] These should be used instead of the constructors when creating the current date/time Unlike the constructors, these methods validate any argument to ensure it is non-null - Static parse() methods available on all major types These allow the formatter to be controlled They do not always parse the same formats as the constructor taking an object - Parsing of month and day without year now handles February 29th This is achieved by changing the default year from 1970 to 2000 when parsing a month or day without a year. This behaviour can be controlled using the new withDefaultYear() setting on the formatter (set to 1970 for the old behaviour). - Add static factory method millis() to Duration [2648777] This checks for and returns the singleton value for ZERO - Add methods to Duration to get standard minutes, hours and days [2862884] - Support pluggable locale text and additional locales in JDK 6 [2690370] Extra info accessed by reflection if JDK 6 used - Better error messages for invalid time zone ids [2781835] - Allow 'Z' and 'ZZ' in format patterns to parse 'Z' as '+00:00' [2827359] - Support parsing of date-time zone IDs like Europe/London - Support parsing of date-time zone names like "EST" and "British Summer Time" These names are not unique, so the new API methods on the builder require you to pass in a map listing all the names you want to be able to parse. The existing method is unaltered and does not permit parsing. - Add DateTimeFormatter.withZoneUTC() Provides easy way to set UTC, which is often required for parsing - Add DateTimeFormatter.parseLocalDate(), .parseLocalTime(), .parseLocalDateTime() These parse the input string in the expected manner handing time zones and offsets. For example, the LocalDate parse will parse any time or offset from the string, but will completely ignore them when returning the actual LocalDate. - Add DateTime.withEarlierOffsetAtOverlap() .withLaterOffsetAtOverlap() [3192457] Allow fine grained control of the offset during a DST overlap - Add DateTime.withTimeAtStartOfDay() [3304757] Provide a simple, reliable way to get the start of day from DateTime. - Add LocalDate.toDate() [2465359] - Add LocalDateTime.toDate() This provides a direct conversion to JDK Date which handles DST and time zone data differences - Cache hash code in LocalDate Enhances performance - DateTime constructors without seconds/millis [1982629] - DateTimeFormatter convenience methods taking an Appendable [2607923] - Add @FromString/@ToString annotations from joda-convert This does NOT require the inclusion of joda-convert at runtime! - Reduce logging from ZoneInfoCompiler by adding a verbose flag - Better Javadoc of DateTimeZone.default behaviour Compatibility with 1.6 ---------------------- Binary compatible - Not fully, see below: Source compatible - Not fully, see below: Where possible, changes are binary compatible and source compatible. The primary binary incompatible changes are the removal of the deprecated methods and the addition of Comparable to ReadablePartial. Testing has included clirr, javap and manual testing of old files with new code. Deprecated methods removed: - Chronology.getISO() - Chronology.getISOUTC() - Chronology.getISO(DateTimeZone) - Chronology.getGJ() - Chronology.getGJUTC() - Chronology.getGJ(DateTimeZone) - Chronology.getGregorian() - Chronology.getGregorianUTC() - Chronology.getGregorian(DateTimeZone) - Chronology.getJulian() - Chronology.getJulianUTC() - Chronology.getJulian(DateTimeZone) - Chronology.getBuddhist() - Chronology.getBuddhistUTC() - Chronology.getBuddhist(DateTimeZone) - Chronology.getCoptic() - Chronology.getCopticUTC() - Chronology.getCoptic(DateTimeZone) ReadablePartial has had the Comparable interface added (was previously just Javadoc). Any implementation that extended AbstractPartial should have no problems, however any implementation that extended ReadablePartial directly without implementing Comparable will be incompatible. Any direct implementations of ReadableInstant or ReadableDuration are not source compatible. This is because of the additional generics in Comparable. Your code will be source compatible if you extended AbstractInstant or AbstractDuration. This minor source incompatibility for a very few users was deemed to be the best balance of the various difficult options that generics offers. As mentioned above, erasure ensures that this source incompatibility is *not* a binary compatibility. Note that not all deprecated elements have been removed. Some methods and classes have been retained simply because the potential pain of binary incompatability is greater than the gain of removing the deprecations. Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2011h Semantic compatible - Yes, except Previously, DateTimeZone.forID matched time zone names case-insensitively, now it is case-sensitive Previously, parsing a string where only the month and/or day is present would use 1970 as the base year. This failed to handle February 29th. The new behaviour is as follows: If the parse includes a field with a duration between months and days inclusive and does not include any field larger than months, then the default year is changed to the value of getDefaultYear() on DateTimeFormatter, which is the year 2000 by default. In effect, this means that a pattern "ddMMM" which would previously have parsed to dates in 1970 will now parse to dates in 2000 unless further customised. The old behaviour can be simulated by calling withDefautYear(1970) on the formatter. Previously, calling various methods during a daylight savings overlap would change the offset. Now, most methods (such as withMillis/withSeconds/withMinutes/...) will retain the offset wherever possible. Previously, calling DateTimeZone.getOffsetFromLocal during a daylight savings overlap chose the earlier instant in the Western hemisphere and the later instant in the Eastern hemisphere. Now, it always returns the earlier instant (summer time) during an overlap. This affects the constructor of DateTime and other methods. Previously, DateTimeZone.getMillisKeepLocal used DateTimeZone.getOffsetFromLocal, now it uses DateTimeZone.convertUTCToLocal and DateTimeZone.convertLocalToUTC retaining the offset where possible Previously, the internals of DateTimeParserBucket linked the parsed offset and zone. This has now changed so that they are independent to allow the parsing of time-zone IDs. If you implemented the DateTimeParser interface (unlikely), you should re-test your logic. Previously, some parses of mixed weekyear and month formats would yield a result about a year out Now, most (but not all) of these give a more appropriate result Previously, java.util.TimeZone "MET" was incorrectly mapped to "Asia/Tehran". It is now mapped to "CET" (Central European Time). Previously, java.util.TimeZone "EET", "WET", "ECT" were mapped to European cities. They are now mapped to "EET", "WET" and "CET" respectively. Previously, java.util.TimeZone "IET", "AGT", "IST" and "VST" were mapped to old time-zone IDs. They are now mapped to the newer IDs "America/Indiana/Indianapolis", "America/Argentina/Buenos_Aires", "Asia/Kolkata" and "Asia/Ho_Chi_Minh". Deprecations since 1.6 ---------------------- - DateTimeFormatter.getChronolgy() [2783325] Incorrect spelling - new method DateTimeFormatter.getChronology() Bug fixes since 1.6 ------------------- - LocalTime.fromDateFields() Now handles times based on java.util.Date before 1970 - LocalDate.toInterval() [2487417] Now handles time zones which have no midnight at DST cutover - DateTimeZone.convertLocalToUTC [3102760,2182444,2553453] New method now retains the offset wherever possible during calculations This affects higher methods like withHourOfDay/withMinuteOfHour/withSecondOfMinute/withMillisOfSecond which now do not change offset when called within a DST overlap - DateTimeZone.convertLocalToUTC [2903029] Now handles date after last ever DST change - DateTimeZone.getOffsetFromLocal [2952991] The behaviour during DST overlaps is now defined to always return the earlier instant which is normally known as daylight or summer time. Previously, the result varied by hemisphere This affects the constructor of DateTime and other methods - DateTimeZone.getMillisKeepLocal The behaviour now retains the offset when changing zones where possible This affects DateTime.withZoneRetainFields and MutableDateTime.setZoneRetainFields - DateTimeZone.getDefault [3048468,3056104] Handle missing user.timezone system property on Android that resulted in stack overflow - DateTimeZone.forTimeZone [3216471] Time-zone ID "MET" from java.util.TimeZone is now mapped correctly. See compatibility notes above. - Duration.toString Fixed to work correctly for negative values - Duraton.toPeriod(), new Period(long), new MutablePeriod(long) [3264409] Fixed to obey Javadoc. Previously, they didn't obey the Javadoc if the default time-zone had no daylight savings. - Period formatting concurrency [2820871] Fix possible concurrency hole in PeriodFormatBuilder.Separator - Period formatter builder append(PeriodFormatter) did not handle some case [2495455] If the appended formatter contained a separator as the first element, it failed - Classloading CachedDateTimeZone could invalidate state [2935625] Default time zone now lazily loaded - DateTimeUtils shared static variable now volatile [2986043] - DateTimeZone.forID(String) now case-sensitive Previously, it was case-insensitive - Handle broken serialization in other tools [3117678] Some tools can't handle the joda-time stub serialization, kludge a fix for them - Standard DateTimeFieldType implements hashCode and equals for stability across serialization - Conversion from parsed values to a date-time handles weird sets of fields better [3161586] This change is mostly for combinations like weekyear-month-week The new code doesn't handle all combinations perfectly, but its better than it was - Time zone compiler now handles 24:00 [2804258] - Time zone compiler now handles non-UTC better - Remove OSGi BundleExecutionEnvironment [3175068,3175612] - Javadoc fix in Months [2721880] - Javadoc fix in PeriodFormatterBuilder [3100939]

joda-time-2.3/src/site/xdoc/upgradeto120.xml0000644000175000017500000001152611564251363020221 0ustar ebourgebourg Java date and time API - Upgrade from 1.1 to 1.2 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.1 to version 1.2. Joda-Time version 1.2 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the third full release of Joda-Time. This release focuses on bug fixes, with a few new features. We recommend JDK 1.3 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out the JSP and Hibernate contributed projects ** Incompatible changes since 1.1 ------------------------------ Binary compatible - Yes, except - The internal classes BaseGJChronology and CommonGJChronology have been removed They were implementation classes and you should not have been using them Please contact the mailing list if this causes you problems Source compatible - Yes - v1.1 and v1.2 are source compatible in their public and protected API Serialization compatible - Yes - Chronology serialization has changed, however the two formats are compatible - v1.1 did not serialize the Chronology minimum days in first week field properly, v1.2 does Data compatible - Yes - DateTimeZone data updated to version 2005q Deprecations since 1.1 ---------------------- - Chronology factory methods, such as getISO() and getCopticUTC() You should now use the chrono package directly: Chronology.getCoptic(zone) is replaced by CopticChronology.getInstance(zone) These factory methods have been removed as they were unable to scale suitably as more and more chronologies are added Bug fixes since 1.1 ------------------- - ZonedChronology getMaximumValue(ReadablePartial)/getMinimumValue(ReadablePartial) Methods returned incorrect result - ZonedChronology Better detection and handling of offset calculation overflow, throwing an ArithmeticException. - DateTimeZone Handles offset calculation overflow errors for instants near Long.MAX_VALUE, ending the offset transition sequence. - DateTimeFormatter Reverts to UTC if time zone offset calculation causes overflow. This allows at least the time of day fields to be printed for instants near Long.MIN_VALUE or Long.MAX_VALUE. - CopticChronology Fixed regression in month of year calculation which affected getMaximumValue on dayOfMonth field. - CopticChronology Fixed month duration field to handle short 13th month correctly. - ZonedChronology Fixed getting text values for fields from getAs[Short]Text(int value, Locale locale). - Gregorian, Julian, GJ and Coptic These Chronology classes did not correctly store the minimum days in first week during serialization - DateTimeFormatter Fixed printing of time zone name near DST transition - YearMonthDay Fixed addition where date starts on a leap day Fixed addition in the GJChronology - DateTimeFormat Pattern letter 'K' was using the wrong underlying implementation Enhancements since 1.1 ---------------------- - IslamicChronology - EthiopicChronology New Chronologies - DateTime.Property.withMaximumValue() (also DateMidnight/YearMonthDay etc) - DateTime.Property.withMinimumValue() Returns a copy of the base datetime with the specified field set to the maximum or minimum value. This is useful to get the last day of the month. - DateTime lastDayOfMonth = dt.dayOfMonth().withMaximumValue(); - DateTime.Property.toInterval() (also DateMidnight/MutableDateTime) New method to convert return an Interval object over the span of the property Thus dt.monthOfYear().toInterval() returns an interval from the start to the end of the month - MutableDateTime.property(DateTimeFieldType) Gets the property by type. Complements the method already on DateTime/DateMidnight. - YearMonthDay.fromCalendarFields() - YearMonthDay.fromDateFields() - TimeOfDay.fromCalendarFields() - TimeOfDay.fromDateFields() New factory methods to create a YearMonthDay/TimeOfDay using exactly the same field values as the JDK objects, thus ignoring time zone effects - FieldUtils Performance optimization when adding by scalars of one or negative one. The overflow detecting multiplication skips the multiply and divide check for these values.

joda-time-2.3/src/site/xdoc/key_duration.xml0000644000175000017500000000426012116366117020474 0ustar ebourgebourg Java date and time API - Duration Stephen Colebourne

A duration in Joda-Time represents a duration of time measured in milliseconds. The duration is often obtained from an interval.

Durations are a very simple concept, and the implementation is also simple. They have no chronology or time zone, and consist solely of the millisecond duration.

Durations can be added to an instant, or to either end of an interval to change those objects. In datetime maths you could say: instant + duration = instant

Durations implement Comparable which compares the lengths of the two durations.

Within Joda-Time a duration is represented by the ReadableDuration interface. There is one implementation of the interface provided:

  • Duration - An immutable implementation

The code can be used in various ways: DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0); DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0); // duration in ms between two instants Duration dur = new Duration(start, end); // calc will be the same as end DateTime calc = start.plus(dur);

Note that the interface ReadableDuration should not be used like the collections API. The interface only contains the core subset of the operations. Instead, you should usually refer directly to the implementation class in your APIs.

Joda-Time defines a null duration as zero length. Thus, when a method is defined as taking a ReadableDuration, passing null in will be the same as passing in a zero length duration.

joda-time-2.3/src/site/xdoc/upgradeto160.xml0000644000175000017500000001114212203443620020205 0ustar ebourgebourg Java date and time API - Upgrade from 1.5 to 1.6 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.5 to version 1.6. Joda-Time version 1.6 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the seventh release of Joda-Time. This release contains enhancements, bug fixes and a time zone update. We recommend JDK 1.4 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** ******************************************************************** The next release will probably be v2.0 This will be source and binary compatible with the exception that deprecated methods and classes will be removed. If you rely on the deprecated methods or classes please move to their replacements, or let us know why you can't move by writing in https://sourceforge.net/forum/forum.php?forum_id=337835 ******************************************************************** Enhancements since 1.5 ---------------------- - Add static factory methods to Duration [1909376] Duration now has four factory methods, standardDays(), standardHours(), standardMinutes() and standardSeconds(). These create durations of the length normally associated with a day/hour/minute/second - Added Duration.getStandardSeconds() and Duration.toStandardSeconds() These convert a duration in milliseconds to a number of seconds. - Added OSGi bundle information [1889787] Joda-Time should be usable directly as an OSGi bundle - Added stable Chronology hash code implementations [2018795] The hash codes of each Chronology implementation is now stable. This should aid large scale caching/distribution tools. - Added DateTimeZone.isLocalDateTimeGap Returns true/false depending on whether the time is in a time-zone gap Compatibility with 1.5 ---------------------- Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2008i Semantic compatible - Yes Deprecations since 1.5 ---------------------- Bug fixes since 1.5 ------------------- - ISODateTimeFormat millisecond parsing broken Millisecond parsing would parse 12:00:00.4 as 4 milliseconds rather than 400 milliseconds - ISODateTimeFormat basic field parsing too lenient The basic parsers in ISODateTimeFormat were too lenient They have been changed to only accept the correct number of digits as per the ISO-8601 standard. The non basic parsers are unaffected - DateTimeFormat.forFields(List) method can't handle immutable [1877843] Fix so that the method does not throw an exception when an unmodifiable list is passed in - Fixed offset time zones calculated incorrect periods ZonedChronology.ZonedDuration.isPrecise() did not take into account the decorated isPrecise() value. This meant that date fields for fixed offset time zones were always considered precise. The result was periods containing months and years when they should not have done. - ZonedChronology (regression from 1.4) [1887104] Fix to roundFloor/roundCeiling Bug affected DST cutover in Autumn for time fields (not date fields) - Clarify Javadoc time zone formats Time zone formats were incorrectly documented as 'Z' instead of 'ZZ' Javadoc only change - Period formatting [2025928] Formatting option printZeroRarelyFirst() did not work unless years field was included. - DateTimeZone (regression from 1.4) [fix also available in v1.5.2] Fix getOffsetFromLocal DST gap adjustment Bug affected parsing of DST cutover in Autumn - Parsing (regression from 1.4) [1839440] [fix also available in v1.5.1] Support parsing all upper-case and all lower-case text - Javadoc clarity enhancements [fix also available in v1.5.1] - Constants in Years/Months/Weeks/Days/Hours/Minutes/Seconds etc. - Period/Interval Object constructors

joda-time-2.3/src/site/xdoc/upgradeto121.xml0000644000175000017500000000424011564251363020215 0ustar ebourgebourg Java date and time API - Upgrade from 1.2 to 1.2.1 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.2 to version 1.2.1. Joda-Time version 1.2.1 ----------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is a patch release for Joda-Time 1.2. This release only contains bug fixes. We recommend all users of 1.2 upgrade to 1.2.1. We recommend JDK 1.3 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out the JSP and Hibernate contributed projects ** Incompatible changes since 1.2 ------------------------------ Binary compatible - Yes Source compatible - Yes - A bug fix has changed the effect of some toXxx() methods if you use time zones Serialization compatible - Yes Data compatible - Yes - DateTimeZone data updated to version 2006a Deprecations since 1.2 ---------------------- - None Bug fixes since 1.2 ------------------- - DateTime/DateMidnight/MutableDateTime/AbstractInstant Conversion methods toDateTime, toDateTimeISO, toMutableDateTime, and toMutableDateTimeISO now preserve the time zone. Previously calling any of these four methods would convert the result to the default time zone. This was incorrect. The methods have been changed to preserve the time zone. The similarly named methods on Instant have not changed behaviour. - DateTimeFormatterBuilder.MatchingParser Previously didn't estimate parsed length correctly Enhancements since 1.2 ---------------------- - None

joda-time-2.3/src/site/xdoc/privacy.xml0000644000175000017500000000414511564251363017460 0ustar ebourgebourg Privacy

Information about your use of this website is collected using cookies. The collected information consists of the following:
1. The IP address from which you access the website;
2. The type of browser and operating system you use to access our site;
3. The date and time you access our site;
4. The pages you visit; and
5. The addresses of pages from where you followed a link to our site.

Part of this information is gathered using a tracking cookie set by the Google Analytics service and handled by Google as described in their privacy policy. See your browser documentation for instructions on how to disable the cookie if you prefer not to share this data with Google.

We use the gathered information to help us make our site more useful to visitors and to better understand how and when our site is used. We do not track or collect personally identifiable information or associate gathered data with any personally identifying information from other sources.

By using this website, you consent to the collection of this data in the manner and for the purpose described above.

joda-time-2.3/src/site/xdoc/faq.xml0000644000175000017500000003713412116366117016554 0ustar ebourgebourg Java date and time API - FAQ Stephen Colebourne Brian S O'Neill

Some common questions about Joda-Time are answered here.

Question not answered? Suggest one via the mailing list.

Joda-Time only allows the key classes to store valid date-times. For example, 31st February is not a valid date so it can't be stored (except in Partial).

The same principle of valid date-times applies to daylight savings time (DST). In many places DST is used, where the local clock moves forward by an hour in spring and back by an hour in autumn/fall. This means that in spring, there is a "gap" where a local time does not exist.

The error "Illegal instant due to time zone offset transition" refers to this gap. It means that your application tried to create a date-time inside the gap - a time that did not exist. Since Joda-Time objects must be valid, this is not allowed.

Possible solutions may be as follows:
Use LocalDateTime, as all local date-times are valid.
When converting a LocalDate to a DateTime, then use toDateTimeAsStartOfDay() as this handles and manages any gaps.
When parsing, use parseLocalDateTime() if the string being parsed has no time-zone.

Not all cases of this error have a simple solution. Hopefully this FAQ has explained what the error means allowing you to work out what the correct solution will be.

Joda-Time releases only occur infrequently. But time-zone changes happen all the time. As such, it may well be that the rules are out of date.

Between the Joda-Time releases, it is your responsibility to update the jar file with the latest time-zone rules. You must update both the JDK and Joda-Time rules to the same version at the same time to avoid problems. See the update time-zone rules guide for more details.

The time zone rules occur in three key places, your operating system, the JDK and Joda-Time. To be sure of hitting no issues, you should ensure that all three of these have been updated.

Version 1.5 of Joda-Time contains all the daylight savings rule updates for the 2007 US change. For earlier versions of Joda-Time the situation is more complex:

If your application only uses the major time zones of the US, then you need Joda-Time 1.2 or later. If your application also uses the major time zones of the Canada, then you need Joda-Time 1.2.1 or later. If your application uses the minor time zones of the US or Canada, then you need Joda-Time 1.4 or later. For Bermuda (Atlantic/Bermuda) you need Joda-Time 1.4 or later. For the Bahamas (America/Nassau) you need Joda-Time 1.5.

For any future, or similar time zone change, you can upgrade your Joda-Time jar by following these instructions.

There are two main reasons for this.

The first reason is that both the JDK and Joda-Time have time-zone data files. It is important to keep both up to date and in sync if you want to compare the offset between the two.

The second reason affects date-times before the modern time-zone system was introduced. The time-zone data is obtained from the time-zone database. The database contains information on "Local Mean Time" (LMT) which is the local time that would have been observed at the location following the Sun's movements.

Joda-Time uses the LMT information for all times prior to the first time-zone offset being chosen in a location. By contrast, the JDK ignores the LMT information. As such, the time-zone offset returned by the JDK and Joda-Time are different for date-times before the modern time-zone system.

This question has more than one answer! If you just want the number of whole days between two dates, then you can use the new Days class in version 1.4 of Joda-Time. Days d = Days.daysBetween(startDate, endDate); int days = d.getDays(); This method, and other static methods on the Days class have been designed to operate well with the JDK5 static import facility.

If however you want to calculate the number of days, weeks, months and years between the two dates, then you need a Period By default, this will split the difference between the two datetimes into parts, such as "1 month, 2 weeks, 4 days and 7 hours". Period p = new Period(startDate, endDate); You can control which fields get extracted using a PeriodType. Period p = new Period(startDate, endDate, PeriodType.yearMonthDay()); This example will return not return any weeks or time fields, thus the previous example becomes "1 month and 18 days".

For more info, consult the period guide.

Historically, every country has found their own solution to measuring time. This has often been political and religious. To simplify the problem, especially in the realm of computer data transfer, the ISO-8601 standard was founded.

The ISO standard defines a framework for passing dates and times between computer systems in a standard way. The standard uses the proleptic Gregorian calendar. This makes it fully compatible with the calendar system used in most of the world after 1582. The standard warns that it may only be used to represent dates before 1582 'by mutual agreement'.

The standard defines twelve months January to December numbered 1 to 12 and seven days Monday to Sunday, numbered 1 to 7. In addition it defines the first week of the year as the first week to have most of its days in the new year. This can result in the first week of a year starting in the previous year and the last week ending in the following year.

The key point about ISO-8601 is that it is a framework for dates not an absolute single definition. The most common form is YYYY-MM-DDTHH:MM:SS.SSSZ, in other words year-month-day letter 'T' hour:minute:second and fractions.

Dates and times can be a localization nightmare (or should that be localisation...). Often political, geographic and religious factors have come into play. We wanted to avoid these factors if possible.

The ISO8601 standard is a good choice because it is a standard designed for computer data transfer and developed by a standards body. It is also a good choice because it is compatible with the calendar system used by most businesses worldwide today. Finally, it is a good choice as it forces API users to think about the decision they make if they require non-ISO or historically accurate calendar systems.

The main time interface is ReadableInstant. All classes that implement this interface, such as DateTime, store time as a single long value representing milliseconds. The epoch of the definition is 1970-01-01T00:00:00Z, which is the same as the JDK time definition and usage. Querying a field, such as year or hour, will calculate the value from the millisecond instant.

A secondary time interface is ReadablePartial. Classes implementing this interface store data in two ways. The 'local' classes, such as LocalDate and LocalTime store the number of milliseconds from 1970 without a time zone. All other implementations, such as YearMonthDay and TimeOfDay, store time as a one int value for each field.

There are three main reasons for using a single long value to store the time.

  1. Compatibility - being compatible with the JDK makes conversion simpler
  2. Performance - a primitive value enables fast calculations, whereas alternatives generally involve lots of expensive object creation
  3. Big enough - the range provided by a millisecond based solution is big enough for most needs

The range supported is -292,269,054 to 292,277,023. In other words, roughly +/- 290 million years to millisecond precision.

If you want a date outside this range, ask yourself if you really want millisecond precision. In reality, dates this far in the past or future should only be stored as years - anything else is meaningless.

Joda-Time does not support accuracy of times below millisecond. Physics defines time scales down to 5E-44 secs. The only way to accurately record these sorts of times is using the BigInteger class. This would severely compromise the performance of the whole API for a very limited use.

Joda-Time is designed for performance. Compared to java.util.Calendar, java.text.SimpleDateFormat, and java.util.TimeZone, nearly all equivalent operations in Joda-Time are faster. The significant exceptions are operations to get or set an individual field.

Calling "get" on java.util.Calendar is very fast because it doesn't do any work. Calendar calculates all fields in advance, even if many of those fields you won't need. Calendar's set method is fast because it defers calculations until later. Calling Calendar.get after calling Calendar.set forces all the field values to be re-calculated. Calling Joda's DateTime.get method after calling DateTime.set only performs the minimum amount of calculations, and the pair is faster than Calendar.

Joda-Time also allocates very few temporary objects during operations, and performs almost no thread synchronization. In systems that are heavily multi-threaded or use a lot of memory, Calendar, SimpleDateFormat, and TimeZone can become bottlenecks. When the Joda-Time classes are used instead, the bottlenecks go away.

Every public class in Joda-Time is documented as being thread-safe or not. Joda-Time makes heavy use of the immutability design pattern, and all immutable classes in Joda-Time are thread-safe. Many mutable classes whose instances are not likely to be shared are not thread-safe, and are documented as such.

The most common multi-threading mistake made by Java programmers is in the use of SimpleDateFormat. Calling its format method on a shared instance by concurrent threads can produce bizarre results. All of Joda-Time's formatting classes are thread-safe and immutable.

Joda-Time does not support leap seconds. Leap seconds can be supported by writing a new, specialized chronology, or by making a few enhancements to the existing ZonedChronology class. In either case, future versions of Joda-Time will not enable leap seconds by default. Most applications have no need for it, and it might have additional performance costs.

No, you only need to learn a small subset of the classes in the API. The javadoc clearly indicates which packages contain user classes, and which contain implementation classes. In addition, there are a large number of package scoped classes, which are hidden in the javadoc view anyway. Most applications will not need to directly import, extend or implement classes in the implementation packages. Basically, the API consists of the main package, plus the formatting package.

The JDK TimeZone class varies in the support it can provide from one JDK release to another. The rules for determining Daylight Saving Time also change frequently. The Joda solution uses the international standard format for time zone rule data, and allows it to be updated independently of the timing of JDK releases. With perhaps 8 releases of the time zone rules per year this can be quite significant.

'Joda' is a short, four letter name, beginning with 'j' whose domain name was free. It is not an acronym.

The 'J' in 'Joda' is pronounced the same as the 'J' in 'Java'. The project is not capable of wielding a light saber and is thus pronounced differently.


joda-time-2.3/src/site/xdoc/cal_gregorian.xml0000644000175000017500000000417511564251363020602 0ustar ebourgebourg Java date and time API - Gregorian calendar system Stephen Colebourne

The Gregorian calendar system is calendar system used by most of the modern business world. It was first introduced on 1582-10-15 replacing the Julian calendar. Gregorian rules define a leap year as once every four years, except every 100, but including every 400.

The Gregorian chronology in Joda-Time is equivalent* to the ISO chronology, and uses Gregorian rules for all time. Thus it is not historically accurate before 1583. This also means that the Gregorian chronology does not correspond to the java class GregorianCalendar. See GregorianJulian for a suitable replacement.

* The Gregorian and ISO chronologies do in fact differ slightly. The Gregorian chronology defines a century as it is spoken, thus 2005 is in the 21st century. The ISO chronology defines a century as the first two digits of the year, thus 2005 has a century field of 20.

References

Within Joda-Time the Gregorian calendar system can be used by obtaining an instance of GregorianChronology. This is normally created using the factory method GregorianChronology.getInstance(). This is then passed into the constructors of the main date and time classes.

// setup date object for midday on Christmas 2004 Chronology chrono = GregorianChronology.getInstance(); DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0, chrono);
joda-time-2.3/src/site/xdoc/key_partial.xml0000644000175000017500000001174112116366117020305 0ustar ebourgebourg Java date and time API - Partial Stephen Colebourne

A partial in Joda-Time is a partial date and time representation. All implementations represent local dates and times, and do not reference a time zone. As such, they only partially represent a date or time in the datetime continuum.

The main implementations changed in version 1.3. This was to address implementation issues with the original design. The previous classes - TimeofDay and YearMonthDay - are now effectively deprecated. The new implementations are LocalDate, LocalTime and LocalDateTime.

It is not possible to directly interoperate between a partial and an instant. A partial does not fully specify a single point in the datetime continuum, but instead may match multiple points. For example, a LocalTime occurs one per day on the datetime continuum.

A partial can be converted to a full instant by specifying the missing values. At a minimum the time zone must be specified. It may be necessary to specify other missing fields. For example, to convert a LocalDate to a DateTime requires filling in the time fields and the time zone.

In terms of datetime maths, you could write: partial + missing fields + time zone = instant

Two classes represent a date in Joda-Time - DateMidnight and LocalDate. These have different meanings. DateMidnight is a fully specified instant, with a time zone. It is defined as the milliseond instant at exactly mignight (00:00) at the start of a day. LocalDate defines a day using the year, monthOfYear and dayOfMonth fields and no time zone. It can be thought of as a local date that covers the whole of the day from 00:00 to 23:59.

Within Joda-Time a partial is represented by the ReadablePartial interface. There are six implementations of the interface provided:

  • LocalDate - An immutable implementation that represents a date without a time or time zone.
  • LocalTime - An immutable implementation that represents a time without a date or time zone.
  • LocalDateTime - An immutable implementation that represents a datetime without a time zone.
  • YearMonth - An immutable implementation that represents a year and month, useful for credit card expiry dates.
  • MonthDay - An immutable implementation that represents a month and day, useful for birthdays without years.
  • Partial - An immutable implementation that can store any combination of datetime fields. For example, using this class you could create a YearMonth or DayOfWeekDayOfMonth partial.
  • YearMonthDay - Effectively deprecated - only supports the year, monthOfYear and dayOfMonth fields.
  • TimeOfDay - Effectively deprecated - only supports the hour, minute, second and millisecond fields.

The code can be used in various ways: // setup objects LocalDate date = new LocalDate(2004, 12, 25); LocalTime time = new LocalTime(12, 20); int year = date.getYear(); // returns 2004 int hour = time.getHour(); // returns 12 String monthStr = date.month().getAsText(); // returns 'December' Conversion to and from instants is easy: LocalDate date = new LocalDate(2004, 12, 25); LocalTime time = new LocalTime(12, 20); // merge, resulting in 2004-25-12T12:20 (default time zone) DateTime dt = date.toDateTime(time); // extract the date fields from someDT DateTime someDT = ... LocalDate date = new LocalDate(someDT);

Note that the interface ReadablePartial should not be used like the collections API. The interface only contains the core subset of the operations. Instead, you should refer directly to the implementation classes in your APIs.

Joda-Time defines a null partial as the current time. Thus, when a method is defined as taking a ReadablePartial, passing null in will be the same as passing in a partial set to the current time.

joda-time-2.3/src/site/xdoc/upgradeto110.xml0000644000175000017500000001633611564251363020224 0ustar ebourgebourg Java date and time API - Upgrade from 1.0 to 1.1 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.0 to version 1.1. Joda-Time version 1.1 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the second full release of Joda-Time. We recommend JDK 1.3 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license cause you problems please contact the mailing list. Incompatible changes since 1.0 ------------------------------ Binary compatible - Yes - v1.0 and v1.1 are binary compatible in their public and protected API Source compatible - Yes - v1.0 and v1.1 are source compatible in their public and protected API Serialization compatible - Yes, except: - DateTime.Property, DateMidnight.Property and MutableDateTime.Property serialization formats have changed to fix a bug. Please note that this only affects the property classes, and not DateTime, DateMidnight or MutableDateTime themselves It is unlikely that you serialized one of these classes Data compatible - Yes, except: - Removed time zones Asia/Riyadh87, Asia/Riyadh88 and Asia/Riyadh89. These should not have been included in the 1.0 release, and do not represent genuine time zones. It is unlikely that you used them. If you do want to use them, please contact the joda-interest mailing list Warnings since 1.0 ------------------ ReadablePartial now has a comment recommending that all implementations should also implement Comparable. This is most easily achieved by extending AbstractPartial. Deprecations since 1.0 ---------------------- None Bug fixes since 1.0 ------------------- - Date and Time (ZoneInfoCompiler) Greek summer time was incorrect due to a comment parsing bug. This disabled DST (summer time) for Europe/Athens after 1980. - DateTimeFormat Parsing of two digit year by DateTimeFormat supports parsing of more or less than two digits, for compatibility with java.text.SimpleDateFormat. If not two digits or if sign character is present, then year is parsed as absolute. - GJChronology Range duration field of dayOfMonth was not consistent with monthOfYear. This bug manifested itself when adding/subtracting periods to partials. - DateTimeParserBucket Fixed parsing date where format includes era. Era must be set and rounded before any other fields. - PeriodFormatterBuilder Formatters that had fields which required a zero to be printed were not being parsed. - DateTime.Property, DateMidnight.Property and MutableDateTime.Property Could previously only be serialized in UTC. The serialization format has been changed to be simpler and more reliable. Unfortunately, this was an incompatible change to the serialization format. - DateTimeFormatterBuilder/PeriodFormatterBuilder Number parser would accept multiple sign characters as valid. - YearMonthDay/TimeOfDay.withChronologyRetainFields Previously, switching chronology did not validate the fields, so you could end up with an object in an invalid state, such as a YearMonthDay where dayOfMonth=31 with Coptic. This method can now throw an IllegalArgumentException - Chronologies Overflowed calculations involving year throw ArithmeticException rather than produce a bogus result. - DateTimeFormatterBuilder.canBuildFormatter() Previously this method always returned false. Enhancements since 1.0 ---------------------- - Partial New immutable implementation of ReadablePartial. This implementation is flexible as to the fields that it stores. Thus, if you want a partial holding just a year and monthOfYear (perhaps for a credit card expiry date), then this class can be used. Full support for almost all truncated and reduced precision ISO output formats is available via use of this class. - DateTime/DateMidnight/MutableDateTime/YearMonthDay/TimeOfDay Added convenience plusXxx() and minusXxx() methods to add/subtract a period For example, dt.plus(Period.days(6)) can now be replaced by dt.plusDays(6) - DateTime/DateMidnight/MutableDateTime/YearMonthDay/TimeOfDay Added convenience toString() method that takes a DateTimeFormatter For example, dt.toString(DateTimeFormat.shortDateTime()) - YearMonthDay/TimeOfDay/AbstractPartial Enabled comparisons using Comparable interface Added compareTo/isEqual/isAfter/isBefore methods These methods were added to AbstractPartial, and are thus available to all implementations of ReadablePartial - YearMonthDay/TimeOfDay Extra time zone constructor Allows current date and time to be accurately obtained - DateTime/DateMidnight/MutableDateTime/YearMonthDay/TimeOfDay Property Added new method to property class - getAsString() Gets the value as a string, not using text values like 'Monday' or 'January' - Period Added constructors to create a Period from two ReadablePartials, such as YearMonthDay or TimeOfDay - Period Added factory to create a Period from two ReadablePartials using an alternative, field-based, calculation - DateTimeUtils Added isContiguous(ReadablePartial) to test if a partial is contiguous (see the method for the definition) - PeriodType Added factory method forFields() to allow a PeriodType to be obtained from any set of DurationFieldType objects - PeriodType Added three new period types - YearMonthDay, YearWeekDay and YearDay These complement the existing ones but exclude the time fields. - DateTimeFormatter Method withPivotYear added to allow the two digit pivot year to be controlled. This is most useful after creating a format from a string pattern. - DateTimeFormatter Added lenient parse option to appendTwoDigitYear and appendTwoDigitWeekyear. - Interval Added overlap method that returns the actual overlap between two intervals. Added gap method that returns the gap between two intervals. Added abuts method that returns true if two intervals abut. - DateTimeUtils Added getReadableInterval(ReadableInterval) method to handle null intervals - IllegalFieldValueException Added new exception subclass of IllegalArgumentException to capture more context when a field is set to an illegal value. This can be helpful in interactive applications. - GJLocaleSymbols Supports parsing "CE" and "BCE" as era if locale language is English. - ISODateTimeFormat New method, forFields(), which gets an ISO format for a set of fields. This is useful for more unusual formats such as DayHour. - ISODateTimeFormat New methods to output ordinal style dates, such as 2005-161. - DateTimeZone classes updated to latest data from the Olson time zone database

joda-time-2.3/src/site/xdoc/cal_islamic.xml0000644000175000017500000000710511651504524020237 0ustar ebourgebourg Java date and time API - Islamic calendar system Stephen Colebourne

The Islamic, or Hijri, calendar system is a Lunar calendar used in many Muslim countries.

The Islamic calendar system is a lunar calendar based on observation. The observation aspect of the calendar means that a new month can only be declared based on human observations of the moon, something which can obviously vary and is unsuited to computer calculation.

Joda-Time implements the arithmetic Islamic calendar, which is an approximation of the actual calendar. There are 12 months, each of 29 or 30 days, making a year of 354 days, or 355 in a leap year. The days in the month alternate, with the first month having 30 days, the second 29 days and so on. In a leap year, the twelfth month has 30 days instead of the normal 29.

The definition of a leap year in the Islamic calendar varies. All agree on a 30 year cycle, however which years within the 30 are leap varies by the leap year pattern:

Standard OffsetCanonical IDAliases
"); out.print(zone.getStandardOffsetStr()); out.print(""); out.print(zone.getCanonicalID()); out.print(""); if (aliases.size() > 0) { for (int j=0; j 0) { out.print(", "); } out.print(((ZoneData) aliases.get(j)).getID()); } } out.print("
15-based 2, 5, 7, 10, 13, 15, 18, 21, 24, 26, 29
16-based 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, 29
Indian 2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29
Habash al-Hasib 2, 5, 8, 11, 13, 16, 19, 21, 24, 27, 30

Joda-Time allows you to choose between these leap year patterns. The 16-based algorithm is the most commonly used, and is the default. Note that Microsoft uses the 15-based pattern, and calls it the 'Kuwaiti algorithm'.

The epoch of the calendar system is 0622-07-16 (Julian) which is therefore 0001-01-01 (Islamic). The current (and only implemented) era is 'AH' (Anno Hegirae).

Days of the week are named 'the first day', 'the second day' and so on, where Sunday is the first day. The day of the week value (numeric) returned by Joda-Time however, is the same as the ISO day of week definition. Thus Sunday will return the numeric value 7, and Monday will return the numeric value 1.

A day in the Islamic calendar begins at sunset on the previous 'day'. Joda-Time does not model this, thus times and date rollover follow standard ISO definitions, in other words starting at midnight.

References

Within Joda-Time the Islamic calendar system can be used by obtaining an instance of IslamicChronology. This is normally created via the IslamicChronology.getInstance() factory. The chronology is then passed into the constructors of the main date and time classes.

// setup date object for midday on May Day 2004 (ISO year 2004) DateTime dtISO = new DateTime(2004, 5, 1, 12, 0, 0, 0); // find out what the same instant is using the Islamic Chronology DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance());
joda-time-2.3/src/site/xdoc/key_interval.xml0000644000175000017500000000557312116366117020503 0ustar ebourgebourg Java date and time API - Interval Stephen Colebourne

An interval in Joda-Time represents an interval of time from one millisecond instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.

Intervals are implemented as half-open, which is to say that the start instant is inclusive but the end instant is exclusive. The end is always greater than or equal to the start. The interval is also restricted to just one chronology and time zone.

Methods exist on intervals to obtain the start and end instants plus the chronology and time zone. There are also methods to obtain the duration and period of the interval.

You cannot compare intervals for order (ie. they do not implement Comparable. If you want to compare the length of intervals you must obtain the duration of each and compare those.

Within Joda-Time an interval is represented by the ReadableInterval interface. There are two implementations of the interface provided:

We recommend the immutable implementation for general usage.

The code can be used in various ways: // interval from start to end DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0); DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0); Interval interval = new Interval(start, end); Accessing other objects is easy: Interval interval = ... DateTime start = interval.getStart(); DateTime end = interval.getEnd(); Chronology chrono = interval.getChronology(); Duration duration = interval.toDuration(); Period period = interval.toPeriod();

Note that the interface ReadableInterval should not be used like the collections API. The interface only contains the core subset of the operations. Instead, you should usually refer directly to the implementation classes in your APIs.

Joda-Time defines a null interval as a zero length interval from now to now. Thus, when a method is defined as taking a ReadableInterval, passing null in will be the same as passing in a zero length interval at the current time.

joda-time-2.3/src/site/xdoc/quickstart.xml0000644000175000017500000001375412116366117020201 0ustar ebourgebourg Java date and time API - Quick start guide Stephen Colebourne

This is the quick introduction guide to Joda-Time and the features on offer. Its designed for those of you who are too impatient to read the full user guide.

Joda-Time includes these key datetime classes:

  • DateTime - Immutable replacement for JDK Calendar
  • DateMidnight - Immutable class representing a date where the time is forced to midnight
  • LocalDate - Immutable class representing a local date without a time (no time zone)
  • LocalTime - Immutable class representing a time without a date (no time zone)
  • LocalDateTime - Immutable class representing a local date and time (no time zone)

Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:

  • Date - a JDK instant
  • Calendar - a JDK calendar
  • String - in ISO8601 format
  • Long - in milliseconds
  • any Joda-Time datetime class
This list is extensible. In other words Joda-Time sacrifices a little type-safety for extensibility. It does mean however, that converting from a JDK Date or Calendar to a Joda-Time class is easy - simply pass the JDK class into the constructor.

Each datetime class provides simple easy methods to access the datetime fields. For example, to access the month you can use: DateTime dt = new DateTime(); int month = dt.getMonthOfYear();

All the main datetime classes are immutable (like String) and cannot be changed after creation. However, simple methods have been provided to alter field values in a newly created object. For example, to set the year, or add 2 hours you can use: DateTime dt = new DateTime(); DateTime year2000 = dt.withYear(2000); DateTime twoHoursLater = dt.plusHours(2);

In addition to the basic get methods, each datetime class provides property methods for each field. These provide access to the full wealth of Joda-Time functionality. For example, to access details about a month or year: DateTime dt = new DateTime(); String monthName = dt.monthOfYear().getAsText(); String frenchShortName = dt.monthOfYear().getAsShortText(Locale.FRENCH); boolean isLeapYear = dt.year().isLeap(); DateTime rounded = dt.dayOfMonth().roundFloorCopy();

Joda-Time provides support for multiple calendar systems and the full range of time zones. The Chronology and DateTimeZone classes provide this support.

Joda-Time defaults to using the ISO calendar system (the calendar used by most of the business world) and the default time zone of your machine. These default values can be overridden whenever necessary. Please note that the ISO calendar system is historically inaccurate before 1583.

Joda-Time uses a pluggable mechanism for calendars. (The JDK uses subclasses such as GregorianCalendar.) To obtain a Joda-Time calendar, use one of the factory methods on Chronology. Chronology coptic = CopticChronology.getInstance();

Time zones are implemented as part of the chronology. To obtain a Joda-Time chronology in the Tokyo time zone, you can use. DateTimeZone zone = DateTimeZone.forID("Asia/Tokyo"); Chronology gregorianJuian = GJChronology.getInstance(zone);

Joda-Time provides support for intervals and time periods.

An interval is represented by the Interval class. It holds a start and end datetime, and allows operations based around that range of time.

A time period is represented by the Period class. This holds a period such as 6 months, 3 days and 7 hours. You can create a Period directly, or derive it from an interval.

A time duration is represented by the Duration class. This holds an exact duration in milliseconds. You can create a Duration directly, or derive it from an interval.

Although a period and a duration may seem similar, they operate differently. For example, consider adding one day to a DateTime at the daylight savings cutover. DateTime dt = new DateTime(2005, 3, 26, 12, 0, 0, 0); DateTime plusPeriod = dt.plus(Period.days(1)); DateTime plusDuration = dt.plus(new Duration(24L*60L*60L*1000L)); Adding a period will add 23 hours in this case, not 24 because of the daylight savings change, thus the time of the result will still be midday. Adding a duration will add 24 hours no matter what, thus the time of the result will change to 13:00.

joda-time-2.3/src/site/xdoc/index.xml0000644000175000017500000002125512203456634017112 0ustar ebourgebourg Java date and time API - Home Stephen Colebourne Al Major

Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. The 'default' calendar is the ISO8601 standard which is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format and parsing.

As a flavour of Joda-Time, here's some example code: public boolean isAfterPayDay(DateTime datetime) { if (datetime.getMonthOfYear() == 2) { // February is month 2!! return datetime.getDayOfMonth() > 26; } return datetime.getDayOfMonth() > 28; } public Days daysToNewYear(LocalDate fromDate) { LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1); return Days.daysBetween(fromDate, newYear); } public boolean isRentalOverdue(DateTime datetimeRented) { Period rentalPeriod = new Period().withDays(2).withHours(12); return datetimeRented.plus(rentalPeriod).isBeforeNow(); } public String getBirthMonthText(LocalDate dateOfBirth) { return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH); } Version 2.3 was released on 2013-08-16 - Download now

Joda-Time has been created to radically change date and time handling in Java. The JDK classes Date and Calendar are very badly designed, have had numerous bugs and have odd performance effects. Here are some of our reasons for developing and using Joda-Time:

Various documentation is available:

Release 2.3 is the current latest release. This release is an evolution of the 1.x codebase, not a major rewrite. It is considered stable and worthy of the 2.x tag.

Version 2.3 is a bugfix release compatible with version 2.2. See the upgrade notes for full details.

Version 2.x is almost completely source and binary compatible with version 1.x. Key changes include the use of JDK 1.5 or later, generics, and the removal of some (but not all) deprecated methods. See the upgrade notes for full details including information on the corner cases that are not compatible.

We will support the 2.x product line using standard Java mechanisms. The main public API will remain backwards compatible for both source and binary in the 2.x stream. The version number will change to 3.0 to indicate a significant change in compatibility.

Available in Maven Central.

Release 1.6.2 is the last v1.x release. It is compatible with JDK 1.4. Given that v2.x is essentially compatible with v1.6.2, there are no current plans for further releases in the v1.x product line.

Support on bugs, library usage or enhancement requests is available on a best efforts basis.

To suggest enhancements or contribute, please fork the source code on GitHub. Alternatively, use GitHub issues.

The older mechanisms of the joda-interest mailing list and the joda-time forums do still exist, but are deprecated.




joda-time-2.3/src/site/xdoc/tz_update.xml0000644000175000017500000000350612203446575020004 0ustar ebourgebourg Java date and time API - Time zone update Stephen Colebourne

Time zones are a concept driven by the political situation in each country around the world. As such, they change frequently, and often at short notice. In order to manage this, Joda-Time uses the internationally recognised tz database, which is also used in most operating systems and the JDK itself.

Using JDK time zone data is a problem however, as the zones are only updated when the JDK is updated. This can cause issues if you are locked into an older version of the JDK.

Joda-Time also compiles the time zone data into our jar file. However, the key difference is that you can update the raw data and recompile the jar at any time.

Firstly, download the latest version of the data files from tz database. Ensure you select the "Data" download which comes as a tar.gz.

Secondly, you need a source code download of Joda-Time.

Thirdly, you must take the time zone data files from step one, and replace those in the Joda-Time download. They are located at {root}/src/main/java/org/joda/time/tz/src. Note that only some of the files need to be copied across.

Fourthly, change the version number in the pom.xml file to indicate that it is a non-standard release.

Finally, recompile the Joda-Time jar file using maven. Simply type mvn package in the root directory.

joda-time-2.3/src/site/xdoc/upgradeto130.xml0000644000175000017500000001256211564251363020223 0ustar ebourgebourg Java date and time API - Upgrade from 1.2 to 1.3 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.2 to version 1.3. Joda-Time version 1.3 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the fourth full release of Joda-Time. This release focuses on new features, but also include some bug fixes. We recommend JDK 1.3 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out the JSP and Hibernate contributed projects ** Enhancements since 1.2 ---------------------- - LocalDate/LocalTime/LocalDateTime New classes representing date, time and datetime without a time zone. LocalDate is the recommended replacement for YearMonthDay. LocalTime is the recommended replacement for TimeOfDay. These classes are implemented more flexibly than YearMonthDay and TimeOfDay and thus solve the problem where you couldn't query or format fields such as dayOfWeek on a YearMonthDay or millisOfDay on a TimeOfDay. Neither YearMonthDay or TimeOfDay will be immediately deprecated as they are in widespread use. The API of the new classes has been kept as similar to YearMonthDay/TimeOfDay as possible to aid migration, so this should be a search and replace change. - DateTime/DateMidnight/YearMonthDay/TimeOfDay - toLocalXxx() Added methods that allow conversion to the new classes, for example: LocalDate date = today.toLocalDate(); - DateTime/DateMidnight/YearMonthDay/TimeOfDay - withXxx() Added methods that allow an individul field to be changed, for example: DateTime firstOfMonth = today.withDayOfMonth(1); These methods are the immutable equivalent of set methods. These are convenince methods for the methods on the property API. - DateTimeFormatter/DateTimeParserBucket If a parsed datetime is illegal due to field range or time zone offset transition, thrown exception includes text of datetime being parsed. - DateTimeFormat - patternForStyle() Added method to retrieve the format pattern for a given style and locale. - ISODateTimeFormat - localDateParser() - localTimeParser() - localDateOptionalTimeParser() - dateOptionalTimeParser() New formats for parsing a datetime/date/time without a time zone, and for parsing a date (mandatory) with an optional time Compatibility with 1.2 ---------------------- Binary compatible - Yes, except - PartialConverter interface has had two new methods added. This is an internal interface and thus it is unlikely that you have implementations that will break. If you did create your own implementation and extended AbstractConverter then your code will not break. Source compatible - Yes, except - PartialConverter interface, see above Serialization compatible - Yes Data compatible - Yes - DateTimeZone data updated to version 2006g Semantic compatible - Yes, except - YearMonthDay constructor no longer accepts time only strings - TimeOfDay constructor no longer accepts strings including a date Deprecations since 1.2 ---------------------- - Instant.toDateTimeISO - Instant.toMutableDateTimeISO These were identical to the methods without the ISO suffix Bug fixes since 1.2 ------------------- - YearMonthDay Constructing with String value no longer accepts a time only string - TimeOfDay Constructing with String value no longer accepts date fields Constructing with String now treats 'T' prefix as optional - DateTime/DateMidnight/MutableDateTime/AbstractInstant Conversion methods toDateTime, toDateTimeISO, toMutableDateTime, and toMutableDateTimeISO now preserve the time zone. Previously calling any of these four methods would convert the result to the default time zone. This was incorrect. The methods have been changed to preserve the time zone. The similarly named methods on Instant have not changed behaviour. - Interval.overlap/Interval.gap Previously these methods returned intervals in the default time zone Now, they return intervals in the time zone of the original interval - Interval/MutableInterval.overlaps(ReadableInterval) Previously, these methods did not handle null correctly Now, if the current millisecond instant is at the start of the interval the method returns false (as defined, even if its a little unexpected) - DateTimeFormatterBuilder.MatchingParser Previously didn't estimate parsed length correctly - YearMonthDay/TimeOfDay/Partial.Property Hashcode was not defined - FixedDateTimeZone Hashcode was not defined - ISO/Gregorian/Julian/Coptic/EthiopicChronology Fixed overflow when getting year field from instants at Long.MAX_VALUE and LONG.MIN_VALUE - DayOfYear field Better error messages

joda-time-2.3/src/site/xdoc/timezones.xml0000644000175000017500000017021411564251363020021 0ustar ebourgebourg Java date and time API - Time Zones Brian S O'Neill

Time zone data is provided by the public tz database, otherwise known as the Olson database. The following table shows all the time zones supported by Joda-Time, using version 2010k of the tz database. It is also possible to update to a later version of the database. This table can be rebuilt by running org.joda.example.time.TimeZoneTable.

Standard OffsetCanonical IDAliases
-12:00Etc/GMT+12
-11:00Etc/GMT+11
-11:00Pacific/Apia
-11:00Pacific/Midway
-11:00Pacific/Niue
-11:00Pacific/Pago_PagoPacific/Samoa, US/Samoa
-10:00America/AdakAmerica/Atka, US/Aleutian
-10:00Etc/GMT+10
-10:00HST
-10:00Pacific/Fakaofo
-10:00Pacific/HonoluluUS/Hawaii
-10:00Pacific/Johnston
-10:00Pacific/Rarotonga
-10:00Pacific/Tahiti
-09:30Pacific/Marquesas
-09:00America/AnchorageUS/Alaska
-09:00America/Juneau
-09:00America/Nome
-09:00America/Yakutat
-09:00Etc/GMT+9
-09:00Pacific/Gambier
-08:00America/Dawson
-08:00America/Los_AngelesUS/Pacific, US/Pacific-New
-08:00America/Santa_Isabel
-08:00America/TijuanaAmerica/Ensenada, Mexico/BajaNorte
-08:00America/VancouverCanada/Pacific
-08:00America/WhitehorseCanada/Yukon
-08:00Etc/GMT+8
-08:00PST8PDT
-08:00Pacific/Pitcairn
-07:00America/Boise
-07:00America/Cambridge_Bay
-07:00America/Chihuahua
-07:00America/Dawson_Creek
-07:00America/DenverAmerica/Shiprock, Navajo, US/Mountain
-07:00America/EdmontonCanada/Mountain
-07:00America/Hermosillo
-07:00America/Inuvik
-07:00America/MazatlanMexico/BajaSur
-07:00America/Ojinaga
-07:00America/PhoenixUS/Arizona
-07:00America/Yellowknife
-07:00Etc/GMT+7
-07:00MST
-07:00MST7MDT
-06:00America/Bahia_Banderas
-06:00America/Belize
-06:00America/Cancun
-06:00America/ChicagoUS/Central
-06:00America/Costa_Rica
-06:00America/El_Salvador
-06:00America/Guatemala
-06:00America/Indiana/KnoxAmerica/Knox_IN, US/Indiana-Starke
-06:00America/Indiana/Tell_City
-06:00America/Managua
-06:00America/Matamoros
-06:00America/Menominee
-06:00America/Merida
-06:00America/Mexico_CityMexico/General
-06:00America/Monterrey
-06:00America/North_Dakota/Center
-06:00America/North_Dakota/New_Salem
-06:00America/Rainy_River
-06:00America/Rankin_Inlet
-06:00America/ReginaCanada/East-Saskatchewan, Canada/Saskatchewan
-06:00America/Swift_Current
-06:00America/Tegucigalpa
-06:00America/WinnipegCanada/Central
-06:00CST6CDT
-06:00Etc/GMT+6
-06:00Pacific/EasterChile/EasterIsland
-06:00Pacific/Galapagos
-05:00America/AtikokanAmerica/Coral_Harbour
-05:00America/Bogota
-05:00America/Cayman
-05:00America/DetroitUS/Michigan
-05:00America/Grand_Turk
-05:00America/Guayaquil
-05:00America/HavanaCuba
-05:00America/Indiana/IndianapolisAmerica/Fort_Wayne, America/Indianapolis, US/East-Indiana
-05:00America/Indiana/Marengo
-05:00America/Indiana/Petersburg
-05:00America/Indiana/Vevay
-05:00America/Indiana/Vincennes
-05:00America/Indiana/Winamac
-05:00America/Iqaluit
-05:00America/JamaicaJamaica
-05:00America/Kentucky/LouisvilleAmerica/Louisville
-05:00America/Kentucky/Monticello
-05:00America/Lima
-05:00America/Montreal
-05:00America/Nassau
-05:00America/New_YorkUS/Eastern
-05:00America/Nipigon
-05:00America/Panama
-05:00America/Pangnirtung
-05:00America/Port-au-Prince
-05:00America/Resolute
-05:00America/Thunder_Bay
-05:00America/TorontoCanada/Eastern
-05:00EST
-05:00EST5EDT
-05:00Etc/GMT+5
-04:30America/Caracas
-04:00America/Anguilla
-04:00America/Antigua
-03:00America/Argentina/San_Luis
-04:00America/Aruba
-04:00America/Asuncion
-04:00America/Barbados
-04:00America/Blanc-Sablon
-04:00America/Boa_Vista
-04:00America/Campo_Grande
-04:00America/Cuiaba
-04:00America/Curacao
-04:00America/Dominica
-04:00America/Eirunepe
-04:00America/Glace_Bay
-04:00America/Goose_Bay
-04:00America/Grenada
-04:00America/GuadeloupeAmerica/Marigot, America/St_Barthelemy
-04:00America/Guyana
-04:00America/HalifaxCanada/Atlantic
-04:00America/La_Paz
-04:00America/ManausBrazil/West
-04:00America/Martinique
-04:00America/Moncton
-04:00America/Montserrat
-04:00America/Port_of_Spain
-04:00America/Porto_Velho
-04:00America/Puerto_Rico
-04:00America/Rio_BrancoAmerica/Porto_Acre, Brazil/Acre
-04:00America/SantiagoChile/Continental
-04:00America/Santo_Domingo
-04:00America/St_Kitts
-04:00America/St_Lucia
-04:00America/St_ThomasAmerica/Virgin
-04:00America/St_Vincent
-04:00America/Thule
-04:00America/Tortola
-04:00Antarctica/Palmer
-04:00Atlantic/Bermuda
-04:00Atlantic/Stanley
-04:00Etc/GMT+4
-03:30America/St_JohnsCanada/Newfoundland
-03:00America/Araguaina
-03:00America/Argentina/Buenos_AiresAmerica/Buenos_Aires
-03:00America/Argentina/CatamarcaAmerica/Argentina/ComodRivadavia, America/Catamarca
-03:00America/Argentina/CordobaAmerica/Cordoba, America/Rosario
-03:00America/Argentina/JujuyAmerica/Jujuy
-03:00America/Argentina/La_Rioja
-03:00America/Argentina/MendozaAmerica/Mendoza
-03:00America/Argentina/Rio_Gallegos
-03:00America/Argentina/Salta
-03:00America/Argentina/San_Juan
-03:00America/Argentina/Tucuman
-03:00America/Argentina/Ushuaia
-03:00America/Bahia
-03:00America/Belem
-03:00America/Cayenne
-03:00America/Fortaleza
-03:00America/Godthab
-03:00America/Maceio
-03:00America/Miquelon
-03:00America/Montevideo
-03:00America/Paramaribo
-03:00America/Recife
-03:00America/Santarem
-03:00America/Sao_PauloBrazil/East
-03:00Antarctica/Rothera
-03:00Etc/GMT+3
-02:00America/NoronhaBrazil/DeNoronha
-02:00Atlantic/South_Georgia
-02:00Etc/GMT+2
-01:00America/Scoresbysund
-01:00Atlantic/Azores
-01:00Atlantic/Cape_Verde
-01:00Etc/GMT+1
+00:00Africa/Abidjan
+00:00Africa/Accra
+00:00Africa/BamakoAfrica/Timbuktu
+00:00Africa/Banjul
+00:00Africa/Bissau
+00:00Africa/Casablanca
+00:00Africa/Conakry
+00:00Africa/Dakar
+00:00Africa/El_Aaiun
+00:00Africa/Freetown
+00:00Africa/Lome
+00:00Africa/Monrovia
+00:00Africa/Nouakchott
+00:00Africa/Ouagadougou
+00:00Africa/Sao_Tome
+00:00America/Danmarkshavn
+00:00Atlantic/Canary
+00:00Atlantic/FaroeAtlantic/Faeroe
+00:00Atlantic/Madeira
+00:00Atlantic/ReykjavikIceland
+00:00Atlantic/St_Helena
+00:00Etc/GMTEtc/GMT+0, Etc/GMT-0, Etc/GMT0, Etc/Greenwich, GMT, GMT+0, GMT-0, GMT0, Greenwich
+00:00Etc/UCTUCT
+00:00Etc/UTCEtc/Universal, Etc/Zulu, Universal, Zulu
+00:00Europe/DublinEire
+00:00Europe/LisbonPortugal
+00:00Europe/LondonEurope/Belfast, Europe/Guernsey, Europe/Isle_of_Man, Europe/Jersey, GB, GB-Eire
+00:00UTC
+00:00WET
+01:00Africa/Algiers
+01:00Africa/Bangui
+01:00Africa/Brazzaville
+01:00Africa/Ceuta
+01:00Africa/Douala
+01:00Africa/Kinshasa
+01:00Africa/Lagos
+01:00Africa/Libreville
+01:00Africa/Luanda
+01:00Africa/Malabo
+01:00Africa/Ndjamena
+01:00Africa/Niamey
+01:00Africa/Porto-Novo
+01:00Africa/Tunis
+01:00Africa/Windhoek
+01:00CET
+01:00Etc/GMT-1
+01:00Europe/Amsterdam
+01:00Europe/Andorra
+01:00Europe/BelgradeEurope/Ljubljana, Europe/Podgorica, Europe/Sarajevo, Europe/Skopje, Europe/Zagreb
+01:00Europe/Berlin
+01:00Europe/Brussels
+01:00Europe/Budapest
+01:00Europe/Copenhagen
+01:00Europe/Gibraltar
+01:00Europe/Luxembourg
+01:00Europe/Madrid
+01:00Europe/Malta
+01:00Europe/Monaco
+01:00Europe/OsloArctic/Longyearbyen, Atlantic/Jan_Mayen
+01:00Europe/Paris
+01:00Europe/PragueEurope/Bratislava
+01:00Europe/RomeEurope/San_Marino, Europe/Vatican
+01:00Europe/Stockholm
+01:00Europe/Tirane
+01:00Europe/Vaduz
+01:00Europe/Vienna
+01:00Europe/WarsawPoland
+01:00Europe/Zurich
+01:00MET
+02:00Africa/Blantyre
+02:00Africa/Bujumbura
+02:00Africa/CairoEgypt
+02:00Africa/Gaborone
+02:00Africa/Harare
+02:00Africa/Johannesburg
+02:00Africa/Kigali
+02:00Africa/Lubumbashi
+02:00Africa/Lusaka
+02:00Africa/Maputo
+02:00Africa/Maseru
+02:00Africa/Mbabane
+02:00Africa/TripoliLibya
+02:00Asia/Amman
+02:00Asia/Beirut
+02:00Asia/Damascus
+02:00Asia/Gaza
+02:00Asia/JerusalemAsia/Tel_Aviv, Israel
+02:00Asia/NicosiaEurope/Nicosia
+02:00EET
+02:00Etc/GMT-2
+02:00Europe/Athens
+02:00Europe/Bucharest
+02:00Europe/ChisinauEurope/Tiraspol
+02:00Europe/HelsinkiEurope/Mariehamn
+02:00Europe/IstanbulAsia/Istanbul, Turkey
+02:00Europe/Kaliningrad
+02:00Europe/Kiev
+02:00Europe/Minsk
+02:00Europe/Riga
+02:00Europe/Simferopol
+02:00Europe/Sofia
+02:00Europe/Tallinn
+02:00Europe/Uzhgorod
+02:00Europe/Vilnius
+02:00Europe/Zaporozhye
+03:00Africa/Addis_Ababa
+03:00Africa/AsmaraAfrica/Asmera
+03:00Africa/Dar_es_Salaam
+03:00Africa/Djibouti
+03:00Africa/Kampala
+03:00Africa/Khartoum
+03:00Africa/Mogadishu
+03:00Africa/Nairobi
+03:00Antarctica/Syowa
+03:00Asia/Aden
+03:00Asia/Baghdad
+03:00Asia/Bahrain
+03:00Asia/Kuwait
+03:00Asia/Qatar
+03:00Asia/Riyadh
+03:00Etc/GMT-3
+03:00Europe/MoscowW-SU
+03:00Europe/Samara
+03:00Europe/Volgograd
+03:00Indian/Antananarivo
+03:00Indian/Comoro
+03:00Indian/Mayotte
+03:30Asia/TehranIran
+04:00Asia/Baku
+04:00Asia/Dubai
+04:00Asia/Muscat
+04:00Asia/Tbilisi
+04:00Asia/Yerevan
+04:00Etc/GMT-4
+04:00Indian/Mahe
+04:00Indian/Mauritius
+04:00Indian/Reunion
+04:30Asia/Kabul
+05:00Antarctica/Mawson
+05:00Asia/Aqtau
+05:00Asia/Aqtobe
+05:00Asia/AshgabatAsia/Ashkhabad
+05:00Asia/Dushanbe
+05:00Asia/Karachi
+05:00Asia/Oral
+05:00Asia/Samarkand
+05:00Asia/Tashkent
+05:00Asia/Yekaterinburg
+05:00Etc/GMT-5
+05:00Indian/Kerguelen
+05:00Indian/Maldives
+05:30Asia/Colombo
+05:30Asia/KolkataAsia/Calcutta
+05:45Asia/KathmanduAsia/Katmandu
+06:00Antarctica/Vostok
+06:00Asia/Almaty
+06:00Asia/Bishkek
+06:00Asia/DhakaAsia/Dacca
+06:00Asia/Novokuznetsk
+06:00Asia/Novosibirsk
+06:00Asia/Omsk
+06:00Asia/Qyzylorda
+06:00Asia/ThimphuAsia/Thimbu
+06:00Etc/GMT-6
+06:00Indian/Chagos
+06:30Asia/Rangoon
+06:30Indian/Cocos
+07:00Antarctica/Davis
+07:00Asia/Bangkok
+07:00Asia/Ho_Chi_MinhAsia/Saigon
+07:00Asia/Hovd
+07:00Asia/Jakarta
+07:00Asia/Krasnoyarsk
+07:00Asia/Phnom_Penh
+07:00Asia/Pontianak
+07:00Asia/Vientiane
+07:00Etc/GMT-7
+07:00Indian/Christmas
+08:00Antarctica/Casey
+08:00Asia/Brunei
+08:00Asia/Choibalsan
+08:00Asia/ChongqingAsia/Chungking
+08:00Asia/Harbin
+08:00Asia/Hong_KongHongkong
+08:00Asia/Irkutsk
+08:00Asia/Kashgar
+08:00Asia/Kuala_Lumpur
+08:00Asia/Kuching
+08:00Asia/MacauAsia/Macao
+08:00Asia/MakassarAsia/Ujung_Pandang
+08:00Asia/Manila
+08:00Asia/ShanghaiPRC
+08:00Asia/SingaporeSingapore
+08:00Asia/TaipeiROC
+08:00Asia/UlaanbaatarAsia/Ulan_Bator
+08:00Asia/Urumqi
+08:00Australia/PerthAustralia/West
+08:00Etc/GMT-8
+08:45Australia/Eucla
+09:00Asia/Dili
+09:00Asia/Jayapura
+09:00Asia/Pyongyang
+09:00Asia/SeoulROK
+09:00Asia/TokyoJapan
+09:00Asia/Yakutsk
+09:00Etc/GMT-9
+09:00Pacific/Palau
+09:30Australia/AdelaideAustralia/South
+09:30Australia/Broken_HillAustralia/Yancowinna
+09:30Australia/DarwinAustralia/North
+10:00Antarctica/DumontDUrville
+10:00Asia/Sakhalin
+10:00Asia/Vladivostok
+10:00Australia/BrisbaneAustralia/Queensland
+10:00Australia/Currie
+10:00Australia/HobartAustralia/Tasmania
+10:00Australia/Lindeman
+10:00Australia/MelbourneAustralia/Victoria
+10:00Australia/SydneyAustralia/ACT, Australia/Canberra, Australia/NSW
+10:00Etc/GMT-10
+10:00Pacific/ChuukPacific/Truk, Pacific/Yap
+10:00Pacific/Guam
+10:00Pacific/Port_Moresby
+10:00Pacific/Saipan
+10:30Australia/Lord_HoweAustralia/LHI
+11:00Antarctica/Macquarie
+11:00Asia/Anadyr
+11:00Asia/Kamchatka
+11:00Asia/Magadan
+11:00Etc/GMT-11
+11:00Pacific/Efate
+11:00Pacific/Guadalcanal
+11:00Pacific/Kosrae
+11:00Pacific/Noumea
+11:00Pacific/PohnpeiPacific/Ponape
+11:30Pacific/Norfolk
+12:00Antarctica/McMurdoAntarctica/South_Pole
+12:00Etc/GMT-12
+12:00Pacific/AucklandNZ
+12:00Pacific/Fiji
+12:00Pacific/Funafuti
+12:00Pacific/KwajaleinKwajalein
+12:00Pacific/Majuro
+12:00Pacific/Nauru
+12:00Pacific/Tarawa
+12:00Pacific/Wake
+12:00Pacific/Wallis
+12:45Pacific/ChathamNZ-CHAT
+13:00Etc/GMT-13
+13:00Pacific/Enderbury
+13:00Pacific/Tongatapu
+14:00Etc/GMT-14
+14:00Pacific/Kiritimati

joda-time-2.3/src/site/xdoc/upgradeto220.xml0000644000175000017500000001254012203443663020214 0ustar ebourgebourg Java date and time API - Upgrade from 2.1 to 2.2 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 2.1 to version 2.2. Joda-Time version 2.2 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the tenth release of Joda-Time. This release contains enhancements, bug fixes and a time zone update. JDK 1.5 or later is required. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** Enhancements since 2.1 ---------------------- - Change some StringBuffer uses to StringBuilder [3532330] - Add method to calculate the Julian Day See DateTimeUtils - Add Danish translation of word-based periods (Kasper Laudrup) - Add Japanese translation of word-based periods (Hajime Senuma) https://github.com/JodaOrg/joda-time/pull/9 - Parsing of US short time-zone names The time-zone names EST/EDT/CST/CDT/MST/MDT/PST/PDT/UT/UTC/GMT can now be parsed in a limited way. This is enabled for formatter patterns of "z" (and "zz" or "zzz"). The builder continues to offer a better way of manually managing this. - Add new exception, IllegalInstantException This allows applications to better capture problems with daylight savings gaps The exception is a subclass of IllegalArgumentException, so existing logic will still work Compatibility with 2.1 ---------------------- Build system - No - Ant build removed. Build only on Maven now. Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2012j Semantic compatible - Yes, except - DateTimeFormatter.parseInto() retains the year if only month parsed (as it did in v1.x) - If a formatter cannot print or parse, it will now throw an exception instead of ignoring it - Format pattern "z" now has limited parsing abilities Deprecations since 2.1 ---------------------- None Bug fixes since 2.1 ------------------- - DateTime.millisOfDay().withMaximumValue()/withMinimumValue() [159] Now handle daylight savings gaps https://sourceforge.net/p/joda-time/bugs/159/ - MonthDay add/subtract [3528941] Addition and subtraction in MonthDay was fixed. It previously didn't work when the start value was 29th February. - LocalDateTime.fromDateFields() This used to fail before 1970 when the input had a milli-of-second field Fixed to not throw an exception - LocalDateTime.fromCalendarFields()/LocalDateTime.fromDateFields() This used to fail before year 1 as the era was ignored Fixed to return the correct year https://github.com/JodaOrg/joda-time/pull/8 - MutableDateTime.setDate(ReadableInstant) [163] Fixed to handle cross-time-zone issues properly rather than always using UTC - BasicGJChronology.getDaysInMonthMaxForSet [165] Fixed calculate the correct maximum length if the input day-of-month value is less than 1 - DateTimeFormatter.parseInto() [3522138] The v2.0 changes to handle parsing of month/day on their own (for Feb 29th) cause parseInto() to lose the year. This fix reverts behaviour to v1.x so that parseInto() will use the supplied year, not the default year of the formatter. - DateTimeFormatter.isPrinter()/isParser() and related The Javadoc for DateTimeFormatterBuilder specified behaviour when the formatter could not print or could not parse, but the code didn't implement it Now it does, which means that DateTimeFormatter.isPrinter()/isParser() are now correct. The formatter will also now throw UnsupportedOperationException when unable to print/parse. - Period formatter [3564249] Formatting did not correctly output values for negative milliseconds between zero and -1 second - FieldUtils.safeMultiply(long,int) [3520651] Fix implementation to throw exception for (Long.MIN_VALUE, -1) - Fix TestReadableDurationConverter [3515086] Test case didn't work if deafult time zone was UTC - Fix Duration string parsing for small negative numbers Values between 0 and -1 exclusive previously parsed incorrectly https://github.com/JodaOrg/joda-time/pull/10 - Javadoc fix to BaseChronology [3513326] - Javadoc fix to Years [169] - Javadoc fix to LocalTime [171] - Javadoc clarify on formatter builder [mailing list email] - Fixed Spanish translation of day for periods - dia now has accented i https://github.com/JodaOrg/joda-time/pull/5 - Change maven build to use exec-maven-plugin [158] https://sourceforge.net/p/joda-time/bugs/158/ Scala -------- Joda-Time uses annotations from Joda-Convert. In the Java programming language, this dependency is optional, however in Scala it is not. Scala users must manually add the Joda-Convert v1.2 dependency.

joda-time-2.3/src/site/xdoc/cal_julian.xml0000644000175000017500000000344611564251363020107 0ustar ebourgebourg Java date and time API - Julian calendar system Stephen Colebourne

The Julian calendar system is calendar system that was widely used from about 4CE to 1582CE. It was replaced by the Gregorian calendar on 1582-10-15. The Julian calendar defines a leap year as once every four years. This becomes inaccurate over time, to such an extent that by 1582, 10 days had to be 'lost' to correct the calendar.

The Julian calendar is represented in Joda-Time by the Julian chronology. This chronology applies Julian rules for all time. Normally, a more accurate historic calendar is found by using the GregorianJulian chronology instead.

References

Within Joda-Time the Julian calendar system can be used by obtaining an instance of JulianChronology. This is normally created using the factory method JulianChronology.getInstance(). This is then passed into the constructors of the main date and time classes.

// setup date object for the Battle of Hastings in 1066 Chronology chrono = JulianChronology.getInstance(); DateTime dt = new DateTime(1066, 10, 14, 10, 0, 0, 0, chrono);
joda-time-2.3/src/site/xdoc/installation.xml0000644000175000017500000000436112203456655020506 0ustar ebourgebourg Java date and time API - Download and Installation Al Major

To use Joda-Time you need to download the latest version. The download will contain the joda-time jar file. Once you add this to your classpath you will be able to use Joda-Time.

The binary download also includes joda-time-sources.jar, which is a jar file of the source code suitable for linking to the jar file in IDEs such as Eclipse.

The release notes for upgraders can be found here:

If you want to build Joda-Time from source you will need Apache Ant or Apache Maven. Search to find out more about building using those tools.

joda-time-2.3/src/site/xdoc/upgradeto100.xml0000644000175000017500000000322112203443556020206 0ustar ebourgebourg Java date and time API - Upgrade from 0.99 to 1.0 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 0.99 to version 1.0. Joda-Time version 1.0 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the first full release of Joda-Time. There have been numerous beta releases over an extended period of time. We recommend JDK 1.3 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license cause you problems please contact the mailing list. Incompatible changes since 0.99 ------------------------------- Deprecated methods removed. See http://www.joda.org/joda-time/upgradeto099.html for 0.98 to 0.99 changes Deprecations since 0.99 ----------------------- None See http://www.joda.org/joda-time/upgradeto099.html for 0.98 to 0.99 changes Bug fixes since 0.99 -------------------- None See http://www.joda.org/joda-time/upgradeto099.html for 0.98 to 0.99 changes Enhancements since 0.99 ----------------------- None See http://www.joda.org/joda-time/upgradeto099.html for 0.98 to 0.99 changes

joda-time-2.3/src/site/xdoc/upgradeto099.xml0000644000175000017500000001665411564251363020247 0ustar ebourgebourg Java date and time API - Upgrade from 0.98 to 0.99 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 0.98 to version 0.99. Joda-Time version 0.99 ---------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the last pre-beta release of Joda-Time. We now recommend JDK 1.3 or later, and have performed no testing on earlier JDKs. ****************************************** * The license of Joda-Time has changed * * * * Previous license: BSD-style * * New license: Apache License v2 * ****************************************** This change should have no impact on users of the code, as the licenses both have the same intent - that is to make the code freely available with a minimum of restrictions. Incompatible changes since 0.98 ------------------------------- Please contact the joda-interest mailing list if you have difficulties upgrading This release is both source and binary incompatible with 0.98 - Formatting package reworked This mainly affects those doing low level formatting work. A deprecated interface has been added for 0.99 for some methods. DateTimeFormatter/PeriodFormatter changed from interface to class. These classes are now the main formatting API. You still create them via the same factory classes, such as DateTimeFormat. Most methods, and all functionality, have been retained, but some are deprecated (see below). DateTimePrinter/DateTimeParser/PeriodPrinter/PeriodParser are now internal classes. Applications will use DateTimeFormatter/PeriodFormatter. Any references to DateTimePrinter/DateTimeParser/PeriodPrinter/PeriodParser in your application should be changed to DateTimeFormatter/PeriodFormatter. (Unless you are implementing your own printer/parser) DateTimeFormatterBuilder usage changes DateTimeFormatterBuilder.toPrinter() --> DateTimeFormatterBuilder.toFormatter() DateTimeFormatterBuilder.toParser() --> DateTimeFormatterBuilder.toFormatter() The isPrinter() and isParser() methods on DateTimeFormatter tell you about the status of the formatter. Make similar changes for PeriodFormatterBuilder. Format factory classes now define static methods DateTimeFormat.getInstance().xxx() --> DateTimeFormat.xxx() DateTimeFormat.getInstance(locale).xxx() --> DateTimeFormat.xxx().withLocale() and so on for ISODateFormat, PeriodFormat and ISOPeriodFormat DateTimeFormat.appendPatternTo(formatter, pattern) --> f.appendPattern(pattern) DateTimeFormat.getPatternForStyle --> Removed, please contact mailing list BaseDateTimeFormatter/BasePeriodFormatter Classes removed, behaviour moved into DateTimeFormatter/PeriodFormatter - DateTimeFormat pattern change The time zone pattern 'ZZZZ' previously output a time zone offset like '+08:00'. Now you need a pattern of 'ZZ' to output the offset. The pattern 'ZZZZ' will now output the time zone id, such as 'Europe/London'. - ReadablePartial - removed methods toDateTime(), toDateTime(DateTimeZone zone), as their meaning was confused. Implementations on YearMonthDay/TimeOfDay are deprecated. - DateTime/DateMidnight/MutableDateTime - removed getReadableInstant() from the property classes On DateTime.Property, use getDateTime(). On DateMidnight.Property, use getDateMidnight(). On MutableDateTime.Property, use getMutableDateTime(). - ReadableInstant - added method isSupported(DateTimeFieldType field) Implemented in DateTime/DateMidnight/MutableDateTime - YearMonthDay/TimeOfDay - removed getReadablePartial() from the property classes On YearMonthDay.Property, use getYearMonthDay(). On TimeOfDay.Property, use getTimeOfDay(). - TimeOfDay - semantic change to TimeOfDay.Property.addToCopy() Previously, add threw an exception if the 23:59/00:00 boundary was broken. Now it wraps to the next 'day', as this is the more typical use case. Change to the method TimeOfDay.Property.addNoWrapToCopy() to restore the old behaviour. Deprecations since 0.98 ----------------------- ** ALL deprecated methods will be removed in 1.0 ** Please contact the joda-interest mailing list if you have difficulties upgrading - Formatting package reworked Factory classes now no longer have a static getInstance() method. DateTimeFormat.getInstance().xxx() --> DateTimeFormat.xxx() ISODateTimeFormat.getInstance().xxx() --> ISODateTimeFormat.xxx() PeriodFormat.getInstance().xxx() --> PeriodFormat.xxx() PeriodFormat.getInstance(locale).xxx() --> PeriodFormat.xxx().withLocale() ISOPeriodFormat.getInstance().xxx() --> ISOPeriodFormat.xxx() Some DateTimeFormatter methods deprecated. f.print(millis, DateTimeZone) --> f.withZone(zone).print(millis) f.print(millis, Chronology) --> f.withChronology(chrono).print(millis) f.parseMillis(str, Chronology) --> f.withChronology(chrono).parseMillis(str) f.parseDateTime(str, Chronology) --> f.withChronology(chrono).parseDateTime(str) f.parseMutableDateTime(str, Chronology) --> f.withChronology(chrono).parseMutableDateTime(str) Some PeriodFormatter methods deprecated. f.parsePeriod(type, str) --> f.withType(type).parsePeriod(str) f.parseMutablePeriod(type, str) --> f.withType(type).parseMutablePeriod(str) - DateTimeZone - factory methods changed: getInstance() -> forID/forOffsetHours/forOffsetHoursMinutes/forTimeZone Aim to clarify meaning of each method - YearMonthDay/TimeOfDay - deprecated methods toDateTime(), toDateTime(DateTimeZone zone), as their meaning was confused. On YearMonthDay, use toDateTimeAtCurrentTime() or toDateTimeAtMidnight(). On TimeOfDay, use toDateTimeToday(). Bug fixes since 0.98 -------------------- - Interval/MutableInterval isAfter(ReadableInterval) - fixed bug when intervals abutted - Parsing periods of the form PT... - fixed bug that prevented parsing - Period parsing now more strict - 'T' character required to separate date and time in ISO periods - Fixed parsing of fractional seconds in Periods - Default time zone based on offset was being interpreted as UTC - Fixed NullPointerException in DateTimeFormat - DateTimeFormat would use date style for time style - DateTimeFormatterBuilder was using wrong time zone for text fields - Avoid NPE in property(DateTimeFieldType) methods - Parsing two digit years using a pattern now follows JDK definition Enhancements since 0.98 ----------------------- - Formatting package much more powerful, and has potential to grow after 1.0 release - YearMonthDay/TimeOfDay - add toString variants that take a pattern - add withField(), withFieldAdded(), withPeriodAdded(), plus() and minus() - DateTimeField - Add methods getAsText(int, Locale) and getAsShortText(int, Locale) for simple access to text values - Period - Added support to create periods from a duration and an end instant - Periods can be converted to durations by end instant too - Duration - Durations can be converted to periods by end instant too - Durations can be converted to intervals by end instant too

joda-time-2.3/src/site/xdoc/upgradeto152.xml0000644000175000017500000000373112203443610020212 0ustar ebourgebourg Java date and time API - Upgrade from 1.5.1 to 1.5.2 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.5.1 to version 1.5.2. Joda-Time version 1.5.2 ----------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is a patch release for Joda-Time 1.5.1. This release contains one bug fix and a time zone update. We recommend all users of 1.5.1 upgrade to 1.5.2. We recommend JDK 1.4 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. * Please also check out our related projects * * http://www.joda.org/joda-time/related.html * Enhancements since 1.5 ---------------------- Compatibility with 1.5 ---------------------- Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2007k Semantic compatible - Yes Deprecations since 1.5 ---------------------- Bug fixes since 1.5.1 --------------------- - DateTimeZone (regression from 1.4) Fix getOffsetFromLocal DST gap adjustment. Bug fixes since 1.5 ------------------- - Parsing (regression) [1839440] Support parsing all upper-case and all lower-case text - Javadoc clarity enhancements - Constants in Years/Months/Weeks/Days/Hours/Minutes/Seconds etc. - Period/Interval Object constructors

joda-time-2.3/src/site/xdoc/key_chronology.xml0000644000175000017500000000621712116366117021036 0ustar ebourgebourg Java date and time API - Chronology Stephen Colebourne

A chronology in Joda-Time is a pluggable calendar system. The JDK supports multiple calendar systems via subclasses of Calendar. This is clunky, and in practice it is very difficult to write another calendar system. Joda-Time supports multiple calendar systems by designing a pluggable system.

The default chronology in Joda-Time is ISO. This calendar system is the same as that used by business in the majority of the world today. The ISO system is unsuitable for historical work before 1583 as it applies the leap year rules from today back in time (it is a proleptic calendar). As a result, users requiring a more historically accurate calendar system are forced to think about their actual requirements, which we believe is a Good Thing.

The actual calculations of the chronology are split between the Chronology class itself and the field classes - DateTimeField and DurationField. Together, the subclasses of these three classes form the bulk of the code in the library. However, most users will never need to use or refer directly to the subclasses. Instead, most applications will simply obtain the chronology and use it as a singleton.

The chronology class also supports the time zone functionality. This is applied to the underlying chronology via the decorator design pattern. The DateTimeZone class provides access to the zones via factories, and also supports a default zone concept. A full list of time zones can be found here. It is also possible to update the zone data yourself.

Internally, all the chronology, field and time zone classes are maintained as singletons. Thus there is an initial setup cost when using Joda-Time, but after that only the main API instance classes (DateTime, Interval, Period, etc.) have creation and garbage collector costs.

A Chronology is obtained and used in Joda-Time as a singleton: DateTimeZone zone = DateTimeZone.forID("Europe/London"); Chronology coptic = CopticChronology.getInstance(zone); // current time with coptic chronology DateTime dt = new DateTime(coptic); int year = dt.getYear(); // gets the current coptic year int month = dt.getMonthOfYear(); // gets the current coptic month

A null chronology always refers to ISO chronology in the default zone. Thus, when a method is defined as taking a Chronology, passing null in will be the same as passing in the ISO chronology in the default time zone.

joda-time-2.3/src/site/xdoc/upgradeto150.xml0000644000175000017500000001633612203443572020224 0ustar ebourgebourg Java date and time API - Upgrade from 1.4 to 1.5 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.4 to version 1.5. Joda-Time version 1.5 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the sixth full release of Joda-Time. This release focuses on new features, but also include some bug fixes. We recommend JDK 1.4 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. * Please also check out our related projects * * http://www.joda.org/joda-time/related.html * Enhancements since 1.4 ---------------------- - LocalDate - add toDateTimeAtStartOfDay(), toDateTimeAtStartOfDay(DateTimeZone) methods to replace toDateTimeAtMidnight() which avoid issues with time zones that do not have midnight at spring DST cutover - LocalDate - add toLocalDateTime() provide mechanism to create LocalDateTime from LocalDate and LocalTime - Performance enhancement for LocalDate, LocalTime and LocalDateTime - equals, compareTo, Period construction - Partial - add isMatch(ReadablePartial) provide mechanism to match a Partial, such as 'Friday the Thirteenth' to another partial, such as a LocalDate - Period - add toStandardDuration() - add toStandardWeeks(), toStandardDays(), toStandardHours(), toStandardMinutes(), toStandardSeconds() methods to convert a period to other types using the standard conversions (7 day week, 24 hour day, ...) - Period - add plus(ReadablePeriod), minus(ReadablePeriod) methods to add and subtract whole periods rather than just single fields - Period - add normalizedStandard(), normalizedStandard(PeriodType) methods to normalize the period back to standard field ranges, such as normalizing 1 year 15 months to 2 years 3 months - Period.toString(PeriodFormatter), MutablePeriod.toString(PeriodFormatter) - allow periods to be directly formatted, as with datetimes - DateTimeZone - add isStandardOffset() assists in determining if DST applies - Interval - add (long,long,DateTimeZone) constructor constructor emphasises that intervals include a time zone - DateTimeFormatterBuilder - add appendFixedDecimal(DateTimeFieldType,int), appendFixedSignedDecimal(DateTimeFieldType,int) methods for printing and parsing fields which must have a fixed number of digits Compatibility with 1.4 ---------------------- Binary compatible - Yes, except - Internal class LenientDateTimeField has an incompatible change to getInstance() and the constructor - Internal class DateTimeZoneBuilder has an incompatible change to toDateTime() and writeTo() Source compatible - Yes, except - Internal class LenientDateTimeField has an incompatible change to getInstance() and the constructor - Internal class DateTimeZoneBuilder has an incompatible change to toDateTime() and writeTo() Serialization compatible - Yes Data compatible - Yes, except - Format of time zone data files changed slightly to fix bug This mainly affects Australia - DateTimeZone data updated to version 2007h Semantic compatible - Yes Deprecations since 1.4 ---------------------- - YearMonthDay - use LocalDate - TimeOfDay - use LocalTime - LocalDate and LocalTime have a much better internal implementation and have been available since v1.3. Both have been effectively deprecated in the javadoc for over a year to enable a gentle transition. In this release, they are now formally deprecated, however they won't be removed until a v2.0 which won't occur until 2009 at the earliest. - LocalDate.toDateTimeAtMidnight() LocalDate.toDateTimeAtMidnight(DateTimeZone) - use toDateTimeAtStartOfDay() instead because it avoids exceptions Bug fixes since 1.4 ------------------- - Daylight savings cutover in Spring incorrect A problem with DST cutover in Spring meant that the result of many methods would be different depending on whether the time zone was in the Eastern or Western hemisphere. Now, the DST cutover is consistent, such that if a time is requested within the cutover, it will be pushed forwards into summer time. [1710316, 1747219, 1755158] - LenientChronology and time zones LenientChronology could throw exceptions when the time being created didn't exist dies to the time zone [1755161] - LocalDate/LocalTime constructors did not set internal state correctly This problem was exposed when Days.daysBetween() and similar methods failed to give the right results - Period.plusXxx(), minusXxx(), withXxx() Fix to throw correct exception as per javadoc (UnsupportedOperationException) when changing an unsupported field - ZoneInfoProvider now returns a copy of its internal state on getAvailableIDs This avoids race conditions on some JVMs - Period formating threw NegativeArraySizeException during formatting This happened for certain period values, notably zero - Period formatting could end up in an infinite loop on IBM JDK 1.4.2 This appears to be an IBM JDK issue, not a Joda-Time issue, but we should not have ended up in an infinite loop whatever happens - DateTimeZone did not properly convert fixed offset zones to java.util.TimeZone [1682152] - DateTimeZone names were incorrect when abbreviation is the same in winter and summer, notably in Australia [1716305] - Avoid compilation issue reported by Apache Harmony [1699760] - LenientChronology might incorrectly adjust a valid hour field near DST transition - DateTimeFormat javadoc now explains time zone parsing restriction better [OpenDiscussion 1721909] - Period javadoc now explains toDurationFrom() and toDurationTo() better - DateTime/Instant/LocalDateTime javadoc improved - DateTimeZone Clarify javadoc of forTimeZone to indicate that application created SimpleTimeZone rules are not parsed [1705180] - Defect in localized Gregorian/Julian symbol cache severely impacted formatting performance when using null (default) locale. - DateTimeFormatter specified with locale of null could produce mismatched symbols if default locale changed concurrently. - DateTime parsing of text failed when the text for the locale contained characters other than letters. [1788282] For French, the short text for months ends with '.'. For Korean, the text for months contains a number. The parser was also too greedy, and would absorb all letters it found, preventing parsing a format such as '23JunSat' (month followed by day of week, or any other text). The parser has been rewritten to only match the text that can be produced by the formatter.

joda-time-2.3/src/site/xdoc/related.xml0000644000175000017500000000404112203444007017404 0ustar ebourgebourg Java date and time API - Related projects Stephen Colebourne

A number of libraries and applications are now built using Joda-Time.

If your open source library provides a value added feature on top of Joda-Time, then let us know!

joda-time-2.3/src/site/xdoc/key_period.xml0000644000175000017500000001744312116366117020140 0ustar ebourgebourg Java date and time API - Period Stephen Colebourne

A period in Joda-Time represents a period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours. This differs from a duration in that it is inexact in terms of milliseconds. A period can only be resolved to an exact number of milliseconds by specifying the instant (including chronology and time zone) it is relative to.

Periods do not have a chronology or time zone. They can be added to an instant, or to either end of an interval to change those objects. In datetime maths you could say: instant + period = instant

For example, consider a period of 1 month. If you add this period to the 1st February (ISO) then you will get the 1st March. If you add the same period to the 1st March you will get the 1st April. But the duration added (in milliseconds) in these two cases is very different.

As a second example, consider adding 1 day at the daylight savings boundary. If you use a period to do the addition then either 23 or 25 hours will be added as appropriate. If you had created a duration equal to 24 hours, then you would end up with the wrong result.

The Joda-Time library defines two types of implementation of the period concept. The first type can only store a single-field, such as days or hours, but not both. The second type can store any-field, expressing a value such as 5 months 8 days and 7 hours.

The first type, single-field periods, is new to version 1.4 of Joda-Time. These classes - Years, Months, Weeks, Days, Hours, Minutes, Seconds - all follow a very similar design, and only store the single field as implied by their name. Thus a Days object can only store a number of days.

These classes can be useful when you want to write an API that must specifically take in a period measured in a particular unit. For example, a travel website where you are given the option of travelling ±1 days or ±3 days could store this information in a Days object.

These classes provide static factory methods rather than constructors. For Days these include daysBetween(startDate, endDate) to obtain the number of whole days between two dates or datetimes, and daysIn(interval) to obtain the number of whole days in an interval. In addition, there are a range of constants, such as Days.ZERO and Days.ONE. The factory method days(int) either returns a constant, or creates a new instance as appropriate.

The single-field classes include basic mathemaical operator support. For Days this includes plus(int), plus(Days), multipliedBy(int), dividedBy(int) and negated(). All operations return a new instance, as Days is immutable. The single-field classes are also comparable.

Converting between different types of period is a difficult problem. One day is not always equal to 24 hours. (It might be 23 or 25 at daylight savings time change.) However, many applications have business rules that assume a 24 hour day and so on. To support this, Days has methods named toStandardHours() and so on which convert the number of days to a number of hours assuming a 24 hour day. The word 'standard' is being specifically used in the method name to remind users of the assumption.

The second type of period is the any-field period. These are implemented by the Period and MutablePeriod classes. Internally, they store a set of int fields, one for each field. The standard set of fields in a period are years, months, weeks, days, hours, minutes, seconds and millis. The PeriodType class allows this set of fields to be restricted, for example to elimate weeks. This is significant when converting a duration or interval to a period, as the calculation needs to know which period fields it should populate.

The Period class is useful when you want to write an API that can take a period that probably contains more than one field. However, to be even more general, your API could define itself to accept a ReadablePeriod, and then the calling code could pass in either a Period or a single field period like Days.

Methods exist on Period to obtain each field value. There are also methods to change a field value, such as withDays(int). They are named 'with' as they return a new Period object, due to immutability.

You cannot compare any-field periods for order, as there is no sensible comparison strategy. Instead, you need to convert the period to a Duration based on a specific date and then compare the duration.

Within Joda-Time a period is represented by the ReadablePeriod interface. There are nine implementations of the interface provided:

We recommend the immutable implementation for general usage.

The code can be used in various ways: DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0); DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0); // period of 1 year and 7 days Period period = new Period(start, end); // calc will equal end DateTime calc = start.plus(period); // able to calculate whole days between two dates easily Days days = Days.daysBetween(start, end); // able to calculate whole months between two dates easily Months months = Months.monthsBetween(start, end);

Note that the interface ReadablePeriod should not be used like the collections API. The interface only contains the core subset of the operations. Instead, you should usually refer directly to the implementation classes in your APIs.

Joda-Time defines a null period as a zero length period. Thus, when a method is defined as taking a ReadablePeriod, passing null in will be the same as passing in a zero length period.

joda-time-2.3/src/site/xdoc/upgradeto151.xml0000644000175000017500000000327512203443577020230 0ustar ebourgebourg Java date and time API - Upgrade from 1.5 to 1.5.1 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 1.5 to version 1.5.1. Joda-Time version 1.5.1 ----------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is a patch release for Joda-Time 1.5. This release contains one bug fix and a time zone update. We recommend all users of 1.5 upgrade to 1.5.1. We recommend JDK 1.4 or later, and have performed no testing on earlier JDKs. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. * Please also check out our related projects * * http://www.joda.org/joda-time/related.html * Enhancements since 1.5 ---------------------- Compatibility with 1.5 ---------------------- Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2007j Semantic compatible - Yes Deprecations since 1.5 ---------------------- Bug fixes since 1.5 ------------------- - Parsing (regression) [1839440] Support parsing all upper-case and all lower-case text

joda-time-2.3/src/site/xdoc/cal_buddhist.xml0000644000175000017500000000415111564251363020425 0ustar ebourgebourg Java date and time API - Buddhist calendar system Stephen Colebourne

The Buddhist calendar system implemented in Joda-Time is based on that supplied in the private Sun packages of a typical JDK. It differs from the GregorianJulian calendar only in the year and era. The Buddhist calendar has one era (the current era), and has a year offset by 543 from the current Gregorian year.

It appears that Sun developed the Buddhist Calendar system to meet the needs of Thailand. However, the calendar is only accurate from 1941-01-01 (ISO). Before that date Thailand used three other calendar systems. The BuddhistChronology follows the design of the BuddhistCalendar. It is hoped that in the future an accurate Thai chronology can be developed.

References

Within Joda-Time the Buddhist calendar system can be used by obtaining an instance of BuddhistChronology. This is normally created using the factory method BuddhistChronology.getInstance(). This is then passed into the constructors of the main date and time classes.

// setup date object for midday on May Day 2004 (ISO year 2004) DateTime dtISO = new DateTime(2004, 5, 1, 12, 0, 0, 0); // find out what the same instant is using the Buddhist Chronology DateTime dtBudd = dtISO.withChronology(BuddhistChronology.getInstance());
joda-time-2.3/src/site/xdoc/upgradeto210.xml0000644000175000017500000001013512203443657020214 0ustar ebourgebourg Java date and time API - Upgrade from 2.0 to 2.1 Stephen Colebourne

These are the release notes and advice for upgrading Joda-Time from version 2.0 to version 2.1. Joda-Time version 2.1 --------------------- Joda-Time is a date and time handling library that seeks to replace the JDK Date and Calendar classes. This is the ninth release of Joda-Time. This release contains enhancements, bug fixes and a time zone update. We require JDK 1.5 or later as features such as generics are used. It may be possible to use retroweaver to compile this under an earlier JDK but we haven't tried. Joda-Time is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. The intent is to make the code available to the Java community with the minimum of restrictions. If the license causes you problems please contact the mailing list. ** Please also check out our related projects ** ** http://www.joda.org/joda-time/related.html ** Enhancements since 2.0 ---------------------- - Make DurationFieldType hash code deterministic - Add Period.multipliedBy(int) and Period.negated() Compatibility with 2.0 ---------------------- Binary compatible - Yes Source compatible - Yes Serialization compatible - Yes Data compatible - Yes, except - DateTimeZone data updated to version 2011n Semantic compatible - Yes, except - Date-time for time-zones with DST based on an offset of 00:00 now pick summer time when ambiguous - Time-zone names now return correct results on JDK1.6 for non-English locales - Interval/MutableInterval toString() now contains the time-zone offset Deprecations since 2.0 ---------------------- None Bug fixes since 2.0 ------------------- - Ambiguous date-time when in zone with offset of 00:00 [3424669] A date-time constructor with an ambiguous time due to DST should choose summer time but for a zone with an offset of 00:00 it chose winter time - Fix GJChronology to allow some leap year dates in JulianChronology to be created [3446915] Creating February 29th in Julian leap years was not always possible - Fix PeriodType caching The caching could go wrong if the DurationFieldType instances were in the wrong order - Time-zone names [3412910] Names now returned in locales other than English The names may differ between JDK1.5 and 1.6 due to the underlying JDK data - Time zone id parsing fixed for some longer time zones [3427389] Time zones like "America/Dawson_Creek" were not parsed as "America/Dawson" was matched first - Time zone later/earlier offset methods failed in Western hemisphere [3476684] Previously, withLaterOffset() failed in the Americas, Now rewritten - Time zone id parsing of GMT offsets failed on Dalvik This may be related to a JDK specification change between Java 1.6 and 1.7 - Enhance readResolve() from LocalDate/LocalTime/LocalDateTime [3461008] Handle even more weird deserialization problems with other tools - Tweaks to cached time-zone to try and avoid a NPE [3470276] - Fix multi-lingual period format for using English from another language default [3471414] Previously, the word-based methods on PeriodFormat ignored the argument of English if the default locale was non-English, now fixed - Interval/MutableInterval toString() now contains the time-zone offset [https://github.com/JodaOrg/joda-time/pull/2] - Fix multiplication of Long.MIN_VALUE by -1 in safeMultiply() - Fix validation in BasicChronology.getDateTimeMillis Previously this allowed a millisOfDay value one too large - Javadoc fix to MutablePeriod [3413869] Scala -------- Joda-Time uses annotations from Joda-Convert. In the Java programming language, this dependency is optional, however in Scala it is not. Scala users must manually add the Joda-Convert v1.2 dependency.

joda-time-2.3/src/site/xdoc/field.xml0000644000175000017500000003255011564251363017067 0ustar ebourgebourg Java date and time API - Fields Stephen Colebourne

The library breaks up the date and time into a number of fields. This document defines what those fields mean.

A naming convention is used to define the fields. These correspond to the common names given to date and time concepts in the Gregorian calendar.

Most fields are a view over part of the total time. These fields are expressed as XxxOfYyy where Xxx and Yyy are two date time units. Yyy will always be larger than Xxx. For example, DayOfWeek or SecondOfMinute. A side effect of this is that these field values cannot be negative.

Certain fields extend over all time, and do not include the word 'Of' in their names. For example, year and weekyear. These fields can have negative values (see the table for details).

The fields are explained in more detail below (for the GJChronology):

Name Min value (GJ) Max value (GJ) Notes
millisOfSecond 0 999
millisOfDay 0 86 399 999
secondOfMinute 0 59
secondOfDay 0 86 399
minuteOfHour 0 59
minuteOfDay 0 1439
hourOfDay 0 23
hourOfHalfday 0 11
clockhourOfDay 1 24
clockhourOfHalfday 1 12
halfdayOfDay 0 (AM) 1 (PM)
dayOfWeek 1 (Monday) 7 (Sunday)
weekOfWeekyear 1 53
weekyear -292 000 000 292 000 000
dayOfMonth 1 31
dayOfYear 1 366
monthOfYear 1 (January) 12 (December)
year -292 000 000 292 000 000
yearOfCentury 1 100 [1]
yearOfEra 1 292 000 000
centuryOfEra 1 2 920 000 [2]
era 0 (BC/BCE) 1 (AD/CE)

[1] For the ISOChronology, the year of century range is from 0 to 99.
[2] For the ISOChronology, the century of era range is from 0.

The number of milliseconds in the specified time once the second and larger parts are removed.

The number of milliseconds in the specified time once the day and larger parts are removed.

The number of seconds in the specified time once the minute and larger parts are removed.

The number of seconds in the specified time once the day and larger parts are removed.

The number of minutes in the specified time once the hour and larger parts are removed.

The number of minutes in the specified time once the day and larger parts are removed.

The number of hours in the specified time once the day and larger parts are removed. The clockhour value represents midnight of the current day as 24 instead of 0.

The number of hours within the half day. The clockhour value represents midnight or noon of the current day as 12 instead of 0.

The AM/PM value of the day.

The day of week is defined by constants in DateTimeConstants. The values used are from the ISO8601 standard. Monday is defined as 1, through to Sunday as 7.

A week based year is one where dates are expressed as a day of week, week number and year (week based). The following description is of the ISO8601 standard used by implementations of this method in this library.

Weeks run from 1 to 52-53 in a week based year. The first day of the week is defined as Monday and given the value 1.

The first week of a year is defined as the first week that has at least four days in the year. As a result of this definition, week 1 may extend into the previous year, and week 52/53 may extend into the following year. Hence the need for the year of weekyear field.

For example, 2003-01-01 was a Wednesday. This means that five days, Wednesday to Sunday, of that week are in 2003. Thus the whole week is considered to be the first week of 2003. Since all weeks start on Monday, the first week of 2003 started on 2002-12-30, ie. in 2002.

The week based year has a specific text format.
2002-12-30 (Monday 30th December 2002) would be represented as 2003-W01-1.
2003-01-01 (Wednesday 1st January 2003) would be represented as 2003-W01-3.

The day of the month. For the GJ and ISO chronologies, this will run from 1 through to 28 or 29 in February, 30 in April, June, September and November and 31 otherwise.

The day of the year. This runs from 1 to 365, or 366 in leap years. The exception is when a Julian to Gregorian cutover has occurred. In that case, the count is from 1 to 355 (typically) and is unbroken.

The month of year defined by constants in DateTimeConstants. The values used are from the ISO8601 standard. January is defined as 1, through to December as 12.

The year, using negative values to represent years in the previous era. For the GJ chronology, year zero is not included, unless the cutover to Gregorian is specified at or before 1 BCE. The ISO chronology always includes the year zero.

The definition of these varies by chronology:

GJ ISO
year of era year century of era year of century year century of era year of century
101 BCE -101 2 1 -100 1 0
100 BCE -100 1 100 -99 0 99
99 BCE -99 1 99 -98 0 98
... ... ... ... ... ... ...
2 BCE -2 1 2 -1 0 1
1 BCE -1 1 1 0 0 0
1 CE 1 1 1 1 0 1
2 CE 2 1 2 2 0 2
... ... ... ... ... ... ...
99 CE 99 1 99 99 0 99
100 CE 100 1 100 100 1 0
101 CE 101 2 1 101 1 1
... ... ... ... ... ... ...
1999 CE 1999 20 99 1999 19 99
2000 CE 2000 20 100 2000 20 0
2001 CE 2001 21 1 2001 20 1

For GJ this is consistent with phrases such '2003 is in the 21st century'.
For ISO this represents a straight split of a textual ISO8601 year.

The year as generally known (always positive). Both the GJ and ISO chronologies return 1 for 1BC/BCE, 2 for 2BC/BCE etc. In other words there is no year zero and no negative value for this field.

The era expressed as a constant, zero for BC/BCE, one for AD/CE.

Other chronologies should respect the convention that one is the current era and zero is the previous era. If more eras are required the values should increase numerically over time.

joda-time-2.3/src/site/xdoc/userguide.xml0000644000175000017500000011110211712473255017770 0ustar ebourgebourg Java date and time API - User Guide Stephen Colebourne Al Major

Joda Time is like an iceberg, 9/10ths of it is invisible to user-code. Many, perhaps most, applications will never need to see what's below the surface. This document provides an introduction to the Joda-Time API for the average user, not for the would-be API developer.

The bulk of the text is devoted to code snippets that display the most common usage scenarios in which the library classes are used. In particular, we cover the usage of the key DateTime, Interval, Duration and Period classes.

We finish with a look at the important topic of formatting and parsing and a few more advanced topics.

The major building blocks of joda time are introduced below. These are the concepts of instant, interval, duration, period, chronology and timezones. We then say a few words about the role of interfaces in the library design, which is a little different than the norm. We end with a few words on package structure. Usage examples for instant are delayed until the following sections of the guide. Examples for interval, duration and period may be found in the appropriate section in the "Key Concepts" part of the documentation.

The most frequently used concept in Joda-Time is that of the instant. An Instant is defined as a moment in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z. This definition of milliseconds is consistent with that of the JDK in Date or Calendar. Interoperating between the two APIs is thus simple.

Within Joda-Time an instant is represented by the ReadableInstant interface. The main implementation of this interface, and the class that the average API user needs to be most familiar with, is DateTime. DateTime is immutable - and once created the values do not change. Thus, this class can safely be passed around and used in multiple threads without synchronization.

The millisecond instant can be converted to any date time field using a Chronology. To assist with this, methods are provided on DateTime that act as getters for the most common date and time fields.

We discuss the chronology concept a litte further on in this overview.

A companion mutable class to DateTime is MutableDateTime. Objects of this class can be modified and are not thread-safe.

Other implementations of ReadableInstant include Instant and DateMidnight.

The main API of DateTime has been kept small, limited to just get methods for each calendar field. So, for instance, the 'day-of-year' calendar field would be retrieved by calling the getDayOfYear() method. For a complete list of fields and their descriptions, see the field reference.

There is much more power available, however, through the use of what is termed a property. Each calendar field is associated with such a property. Thus, 'day-of-year', whose value is directly returned by the method getDayOfYear(), is also associated with the property returned by the dayOfYear() method. The property class associated with DateTime is DateTime.Property.

Knowing the methods on the property is the secret to making the most of the API. We have more to say on the usage of properties later in this document.

An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.

Intervals are implemented as half-open, which is to say that the start instant is inclusive but the end instant is exclusive. The end is always greater than or equal to the start. Both end-points are restricted to having the same chronology and the same time zone.

Two implementations are provided, Interval and MutableInterval, both are specializations of ReadableInterval.

A duration in Joda-Time represents a duration of time measured in milliseconds. The duration is often obtained from an interval.

Durations are a very simple concept, and the implementation is also simple. They have no chronology or time zone, and consist solely of the millisecond duration.

Durations can be added to an instant, or to either end of an interval to change those objects. In datetime maths you could say: instant + duration = instant

Currently, there is only one implementation of the ReadableDuration interface: Duration.

A period in Joda-Time represents a period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours. This differs from a duration in that it is inexact in terms of milliseconds. A period can only be resolved to an exact number of milliseconds by specifying the instant (including chronology and time zone) it is relative to.

For example, consider a period of 1 month. If you add this period to the 1st February (ISO) then you will get the 1st March. If you add the same period to the 1st March you will get the 1st April. But the duration added (in milliseconds) in these two cases is very different.

As a second example, consider adding 1 day at the daylight savings boundary. If you use a period to do the addition then either 23 or 25 hours will be added as appropriate. If you had created a duration equal to 24 hours, then you would end up with the wrong result.

Periods are implemented as a set of int fields. The standard set of fields in a period are years, months, weeks, days, hours, minutes, seconds and millis. The PeriodType class allows this set of fields to be restricted, for example to elimate weeks. This is significant when converting a duration or interval to a period, as the calculation needs to know which period fields it should populate.

Methods exist on periods to obtain each field value. Periods are not associated with either a chronology or a time zone.

Periods can be added to an instant, or to either end of an interval to change those objects. In datetime maths you could say: instant + period = instant

There are two implementations of the ReadablePeriod interface, Period and MutablePeriod.

The Joda-Time design is based around the Chronology. It is a calculation engine that supports the complex rules for a calendar system. It encapsulates the field objects, which are used on demand to split the absolute time instant into recognisable calendar fields like 'day-of-week'. It is effectively a pluggable calendar system.

The actual calculations of the chronology are split between the Chronology class itself and the field classes - DateTimeField and DurationField. Together, the subclasses of these three classes form the bulk of the code in the library. Most users will never need to use or refer directly to the subclasses. Instead, they will simply obtain the chronology and use it as a singleton, as follows: Chronology coptic = CopticChronology.getInstance();

Internally, all the chronology, field, etc. classes are maintained as singletons. Thus there is an initial setup cost when using Joda-Time, but after that only the main API instance classes (DateTime, Interval, Period, etc.) have creation and garbage collector costs.

Although the Chronology is key to the design, it is not key to using the API !!

For most applications, the Chronology can be ignored as it will default to the ISOChronology. This is suitable for most uses. You would change it if you need accurate dates before October 15, 1582, or whenever the Julian calendar ceased in the territory you're interested in). You'd also change it if you need a specific calendar like the Coptic calendar illustrated earlier.

The chronology class also supports the time zone functionality. This is applied to the underlying chronology via the decorator design pattern. The DateTimeZone class provides access to the zones primarily through one factory method, as follows: DateTimeZone zone = DateTimeZone.forID("Europe/London");

In addition to named time zones, Joda-Time also supports fixed time zones. The simplest of these is UTC, which is defined as a constant: DateTimeZone zoneUTC = DateTimeZone.UTC; Other fixed offset time zones can be obtained by a specialise factory method: DateTimeZone zoneUTC = DateTimeZone.forOffsetHours(hours);

The TimeZone implementation is based on data provided by the public tz database, otherwise known as the Olson database. A full list of timezone ids can be found here

Joda-Time provides a default time zone which is used in many operations when a time zone is not specified. This is similar in concept to the default time zone of the java.util.TimeZone class. The value can be accessed and updated via static methods: DateTimeZone defaultZone = DateTimeZone.getDefault(); DateTimeZone.setDefault(myZone);

As you have seen, Joda-Time defines a number of new interfaces which are visible throughout the javadocs. The most important is ReadableInstant which currently has 4 implementations. Other significant interfaces include ReadableInterval and ReadablePeriod. These are currently used as generalizations for a value-only and a mutable class, respectively.

An important point to mention here is that the Joda interfaces are used differently than, for instance, the JDK Collections Framework interfaces. When working with a Collections interface, such as List or Map you will normally hold your variable as a type of List or Map, only referencing the concrete class when you create the object. List list = new ArrayList(); Map map = new HashMap(); In Joda-Time, the interfaces exist to allow interoperation between similar date implementations, such as a mutable and immutable version of a class. As such, they only offer a subset of the methods of the concrete class. For most work, you will reference the concrete class, not the interface. This gives access to the full power of the library. DateTime dt = new DateTime();

For maximum flexibility however, you might choose to declare your method parameters using the Joda-Time interface. A method on the interface can obtain the concrete class for use within the method. public void process(ReadableDateTime dateTime) { DateTime dt = dateTime.toDateTime(); }

The package structure is designed to separate the methods in the public API from the private API. The public packages are the root package (under org.joda.time) and the format package. The private packages are the base, chrono, convert, field and tz packages. Most applications should not need to import classes from the private packages.

A datetime object is created by using a DateTime constructor. The default constructor is used as follows DateTime dt = new DateTime(); and creates a datetime object representing the current date and time in milliseconds as determined by the system clock. It is constructed using the ISO calendar in the default time zone.

To create a datetime object representing a specific date and time, you may use an initialization string: DateTime dt = new DateTime("2004-12-13T21:39:45.618-08:00"); The initialization string must be in a format that is compatible with the ISO8601 standard.

DateTime also provides other constructors to create a specific date and time using a variety of standard fields. This also permits the use of any calendar and timezone.

The DateTime class has a constructor which takes an Object as input. In particular this constructor can be passed a JDK Date, JDK Calendar or JDK GregorianCalendar (It also accepts an ISO8601 formatted String, or Long object representing milliseconds). This is one half of the interoperability with the JDK. The other half of interoperability with JDK is provided by DateTime methods which return JDK objects.

Thus inter-conversion between Joda DateTime and JDK Date can be performed as follows // from Joda to JDK DateTime dt = new DateTime(); Date jdkDate = dt.toDate(); // from JDK to Joda dt = new DateTime(jdkDate);

Similarly, for JDK Calendar: // from Joda to JDK DateTime dt = new DateTime(); Calendar jdkCal = dt.toCalendar(Locale.CHINESE); // from JDK to Joda dt = new DateTime(jdkCal);

and JDK GregorianCalendar: // from Joda to JDK DateTime dt = new DateTime(); GregorianCalendar jdkGCal = dt.toGregorianCalendar(); // from JDK to Joda dt = new DateTime(jdkGCal);

The separation of the calculation of calendar fields (DateTimeField) from the representation of the calendar instant (DateTime) makes for a powerful and flexible API. The connection between the two is maintained by the property (DateTime.Property) which provides access to the field.

For instance, the direct way to get the day of week for a particular DateTime, involves calling the method int iDoW = dt.getDayOfWeek(); where iDoW can take the values (from class DateTimeConstants). public static final int MONDAY = 1; public static final int TUESDAY = 2; public static final int WEDNESDAY = 3; public static final int THURSDAY = 4; public static final int FRIDAY = 5; public static final int SATURDAY = 6; public static final int SUNDAY = 7;

The direct methods are fine for simple usage, but more flexibility can be achieved via the property/field mechanism. The day of week property is obtained by DateTime.Property pDoW = dt.dayOfWeek(); which can be used to get richer information about the field, such as String strST = pDoW.getAsShortText(); // returns "Mon", "Tue", etc. String strT = pDoW.getAsText(); // returns "Monday", "Tuesday", etc. which return short and long name strings (based on the current locale) of the day-of-week. Localized versions of these methods are also available, thus String strTF = pDoW.getAsText(Locale.FRENCH); // returns "Lundi", etc. can be used to return the day-of-week name string in French.

Of course, the original integer value of the field is still accessible as iDoW = pDoW.get(); The property also provides access to other values associated with the field such as metadata on the minimum and maximum text size, leap status, related durations, etc. For a complete reference, see the documentation for the base class AbstractReadableInstantFieldProperty

In practice, one would not actually create the intermediate pDoW variable. The code is easier to read if the methods are called on anonymous intermediate objects. Thus, for example, strT = dt.dayOfWeek().getAsText(); iDoW = dt.dayOfWeek().get(); would be written instead of the more indirect code presented earlier.

Note: For the single case of getting the numerical value of a field, we recommend using the get method on the main DateTime object as it is more efficient. iDoW = dt.getDayOfWeek();

The DateTime implementation provides a complete list of standard calendar fields: dt.getEra(); dt.getYear(); dt.getWeekyear(); dt.getCenturyOfEra(); dt.getYearOfEra(); dt.getYearOfCentury(); dt.getMonthOfYear(); dt.getWeekOfWeekyear(); dt.getDayOfYear(); dt.getDayOfMonth(); dt.getDayOfWeek(); Each of these also has a corresponding property method, which returns a DateTime.Property binding to the appropriate field, such as year() or monthOfYear(). The fields represented by these properties behave pretty much as their names would suggest. The precise definitions are available in the field reference.

As you would expect, all the methods we showed above in the day-of-week example can be applied to any of these properties. For example, to extract the standard month, day and year fields from a datetime, we can write String month = dt.monthOfYear().getAsText(); int maxDay = dt.dayOfMonth().getMaximumValue(); boolean leapYear = dt.yearOfEra().isLeap();

Another set of properties access fields representing intra-day durations for time calculations. Thus to compute the hours, minutes and seconds of the instant represented by a DateTime, we would write int hour = dt.getHourOfDay(); int min = dt.getMinuteOfHour(); int sec = dt.getSecondOfMinute(); Again each of these has a corresponding property method for more complex manipulation. The complete list of time fields can be found in the field reference.

DateTime objects have value semantics, and cannot be modified after construction (they are immutable). Therefore, most simple manipulation of a datetime object involves construction of a new datetime as a modified copy of the original.

WARNING: A common mistake to make with immutable classes is to forget to assign the result to a variable. Remember that calling an add or set method on an immtable object has no effect on that object - only the result is updated.

One way to do this is to use methods on properties. To return to our prior example, if we wish to modify the dt object by changing its day-of-week field to Monday we can do so by using the setCopy method of the property: DateTime result = dt.dayOfWeek().setCopy(DateTimeConstants.MONDAY); Note: If the DateTime object is already set to Monday then the same object will be returned.

To add to a date you could use the addToCopy method. DateTime result = dt.dayOfWeek().addToCopy(3);

Another means of accomplishing similar calculations is to use methods on the DateTime object itself. Thus we could add 3 days to dt directly as follows: DateTime result = dt.plusDays(3);

The methods outlined above are suitable for simple calculations involving one or two fields. In situations where multiple fields need to be modified, it is more efficient to create a mutable copy of the datetime, modify the copy and finally create a new value datetime. MutableDateTime mdt = dt.toMutableDateTime(); // perform various calculations on mdt ... DateTime result = mdt.toDateTime(); MutableDateTime has a number of methods, including standard setters, for directly modifying the datetime.

DateTime comes with support for a couple of common timezone calculations. For instance, if you want to get the local time in London at this very moment, you would do the following // get current moment in default time zone DateTime dt = new DateTime(); // translate to London local time DateTime dtLondon = dt.withZone(DateTimeZone.forID("Europe/London")); where DateTimeZone.forID("Europe/London") returns the timezone value for London. The resulting value dtLondon has the same absolute millisecond time, but a different set of field values.

There is also support for the reverse operation, i.e. to get the datetime (absolute millisecond) corresponding to the moment when London has the same local time as exists in the default time zone now. This is done as follows // get current moment in default time zone DateTime dt = new DateTime(); // find the moment when London will have / had the same time dtLondonSameTime = dt.withZoneRetainFields(DateTimeZone.forID("Europe/London"));

A set of all TimeZone ID strings (such as "Europe/London") may be obtained by calling DateTimeZone.getAvailableIDs(). A full list of available time zones is provided here.

The DateTime class also has one method for changing calendars. This allows you to change the calendar for a given moment in time. Thus if you want to get the datetime for the current time, but in the Buddhist Calendar, you would do // get current moment in default time zone DateTime dt = new DateTime(); dt.getYear(); // returns 2004 // change to Buddhist chronology DateTime dtBuddhist = dt.withChronology(BuddhistChronology.getInstance()); dtBuddhist.getYear(); // returns 2547 where BuddhistChronology.getInstance is a factory method for obtaining a Buddhist chronology.

Reading date time information from external sources which have their own custom format is a frequent requirement for applications that have datetime computations. Writing to a custom format is also a common requirement.

Many custom formats can be represented by date-format strings which specify a sequence of calendar fields along with the representation (numeric, name string, etc) and the field length. For example the pattern "yyyy" would represent a 4 digit year. Other formats are not so easily represented. For example, the pattern "yy" for a two digit year does not uniquely identify the century it belongs to. On output, this will not cause problems, but there is a problem of interpretation on input.

In addition, there are several date/time serialization standards in common use today, in particular the ISO8601. These must also be supported by most datetime applications.

Joda time supports these different requirements through a flexible architecture. We will now describe the various elements of this architecture.

All printing and parsing is performed using a DateTimeFormatter object. Given such an object fmt, parsing is performed as follows String strInputDateTime; // string is populated with a date time string in some fashion ... DateTime dt = fmt.parseDateTime(strInputDateTime); Thus a DateTime object is returned from the parse method of the formatter. Similarly, output is performed as String strOutputDateTime = fmt.print(dt);

Support for standard formats based on ISO8601 is provided by the ISODateTimeFormat class. This provides a number of factory methods.

For example, if you wanted to use the ISO standard format for datetime, which is yyyy-MM-dd'T'HH:mm:ss.SSSZZ, you would initialize fmt as DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); You would then use fmt as described above, to read or write datetime objects in this format.

If you need a custom formatter which can be described in terms of a format pattern, you can use the factory method provided by the DateTimeFormat class. Thus to get a formatter for a 4 digit year, 2 digit month and 2 digit day of month, i.e. a format of yyyyMMdd you would do DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd"); The pattern string is compatible with JDK date patterns.

You may need to print or parse in a particular Locale. This is achieved by calling the withLocale method on a formatter, which returns another formatter based on the original. DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd"); DateTimeFormatter frenchFmt = fmt.withLocale(Locale.FRENCH); DateTimeFormatter germanFmt = fmt.withLocale(Locale.GERMAN); Formatters are immutable, so the original is not altered by the withLocale method.

Finally, if you have a format that is not easily represented by a pattern string, Joda Time architecture exposes a builder class that can be used to build a custom formatter which is programatically defined. Thus if you wanted a formatter to print and parse dates of the form "22-Jan-65", you could do the following: DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendDayOfMonth(2) .appendLiteral('-') .appendMonthOfYearShortText() .appendLiteral('-') .appendTwoDigitYear(1956) // pivot = 1956 .toFormatter(); Each append method appends a new field to be parsed/printed to the calling builder and returns a new builder. The final toFormatter method creates the actual formatter that will be used to print/parse.

What is particularly interesting about this format is the two digit year. Since the interpretation of a two digit year is ambiguous, the appendTwoDigitYear takes an extra parameter that defines the 100 year range of the two digits, by specifying the mid point of the range. In this example the range will be (1956 - 50) = 1906, to (1956 + 49) = 2005. Thus 04 will be 2004 but 07 will be 1907. This kind of conversion is not possible with ordinary format strings, highlighting the power of the Joda time formatting architecture.

To simplify the access to the formatter architecture, methods have been provided on the datetime classes such as DateTime. DateTime dt = new DateTime(); String a = dt.toString(); String b = dt.toString("dd:MM:yy"); String c = dt.toString("EEE", Locale.FRENCH); DateTimeFormatter fmt = ...; String d = dt.toString(fmt); Each of the four results demonstrates a different way to use the formatters. Result a is the standard ISO8601 string for the DateTime. Result b will output using the pattern 'dd:MM:yy' (note that patterns are cached internally). Result c will output using the pattern 'EEE' in French. Result d will output using the specified formatter, and is thus the same as fmt.print(dt).

Joda-Time allows you to change the current time. All methods that get the current time are indirected via DateTimeUtils. This allows the current time to be changed, which can be very useful for testing. // always return the same time when querying current time DateTimeUtils.setCurrentMillisFixed(millis); // offset the real time DateTimeUtils.setCurrentMillisOffset(millis); Note that changing the current time this way does not affect the system clock.

The constructors on each major concrete class in the API take an Object as a parameter. This is passed to the converter subsystem which is responsible for converting the object to one acceptable to Joda-Time. For example, the converters can convert a JDK Date object to a DateTime. If required, you can add your own converters to those supplied in Joda-Time.

Joda-Time includes hooks into the standard JDK security scheme for sensitive changes. These include changing the time zone handler, changing the current time and changing the converters. See JodaTimePermission for details.

joda-time-2.3/src/site/xdoc/cal_coptic.xml0000644000175000017500000000433311564251363020102 0ustar ebourgebourg Java date and time API - Coptic calendar system Stephen Colebourne

The Coptic calendar system is based on that used in ancient Egypt. It is sometimes referred to as the Alexandrian Calendar. The calendar system is in use today by the Coptic Orthodox Church and by farmers tracking the seasons in Egypt.

The Coptic calendar system consists of 12 months of exactly 30 days, followed by a 5 or 6 day intercalary month making a year of 365 or 366 days. Leap years (6 day intercalary month) occur every 4 years without exception (as per the Julian calendar). They occur when the remainder left after dividing the Coptic year by four is 3. The Coptic year starts on Septamber 11th/12th depending on leap years. The epoch date for the calendar is 0284-08-29 (Julian), which therefore is 0001-01-01 (Coptic). The current era is 'AM' (Anno Martyrum or Year of the Martyrs).

Joda-Time implements the rules described above. We model the 5 or 6 day intercalary month as month 13. We also prevent the entry of dates before year 1.

References

Within Joda-Time the Coptic calendar system can be used by obtaining an instance of CopticChronology. This is normally created using the factory method CopticChronology.getInstance(). This is then passed into the constructors of the main date and time classes.

// setup date object for midday on May Day 2004 (ISO year 2004) DateTime dtISO = new DateTime(2004, 5, 1, 12, 0, 0, 0); // find out what the same instant is using the Coptic Chronology DateTime dtCopt = dtISO.withChronology(CopticChronology.getInstance());
joda-time-2.3/src/site/xdoc/cal_ethiopic.xml0000644000175000017500000000426311564251363020427 0ustar ebourgebourg Java date and time API - Coptic calendar system Stephen Colebourne

The Ethiopic calendar system is similiar to the Coptic calendar and based on that used in ancient Egypt. The calendar system is in use today in Ethiopia.

The Ethiopic calendar system consists of 12 months of exactly 30 days, followed by a 5 or 6 day intercalary month making a year of 365 or 366 days. Leap years (6 day intercalary month) occur every 4 years without exception (as per the Julian calendar). They occur when the remainder left after dividing the Ethiopic year by four is 3. The Ethiopic year starts on Septamber 11th/12th depending on leap years. The epoch date for the calendar is 0008-08-29 (Julian), which therefore is 0001-01-01 (Ethiopic). The current era is 'EE' (Ethiopian Era).

Joda-Time implements the rules described above. We model the 5 or 6 day intercalary month as month 13. We also prevent the entry of dates before year 1.

References

Within Joda-Time the Ethiopic calendar system can be used by obtaining an instance of EthiopicChronology. This is normally created via the EthiopicChronology.getInstance() factory. The chronology is then passed into the constructors of the main date and time classes.

// setup date object for midday on May Day 2004 (ISO year 2004) DateTime dtISO = new DateTime(2004, 5, 1, 12, 0, 0, 0); // find out what the same instant is using the Ethiopic Chronology DateTime dtEthiopic = dtISO.withChronology(EthiopicChronology.getInstance());
joda-time-2.3/src/conf/0000755000175000017500000000000012205344143014271 5ustar ebourgebourgjoda-time-2.3/src/conf/MANIFEST.MF0000644000175000017500000000133712203456675015743 0ustar ebourgebourgPackage: org.joda.time Extension-Name: joda-time Specification-Title: Joda-Time Specification-Vendor: Joda.org Specification-Version: 2.3 Implementation-Vendor: Joda.org Implementation-Title: org.joda.time Implementation-Version: 2.3 Implementation-Vendor-Id: org.joda Bundle-ManifestVersion: 2 Bundle-Vendor: Joda.org Bundle-Name: Joda-Time Bundle-SymbolicName: joda-time Bundle-Version: 2.3 Export-Package: org.joda.time;version=2.3, org.joda.time.base;version=2.3, org.joda.time.chrono;version=2.3, org.joda.time.convert;version=2.3, org.joda.time.field;version=2.3, org.joda.time.format;version=2.3, org.joda.time.tz;version=2.3 Bundle-License: Apache 2.0 Bundle-DocURL: http://www.joda.org/joda-time/ joda-time-2.3/src/test/0000755000175000017500000000000012073523033014323 5ustar ebourgebourgjoda-time-2.3/src/test/resources/0000755000175000017500000000000012205344143016335 5ustar ebourgebourgjoda-time-2.3/src/test/resources/Duration.dat0000644000175000017500000000015311577612452020627 0ustar ebourgebourg¬ísrorg.joda.time.Duration?zQÎÖxrorg.joda.time.base.BaseDurationY:ôŽJiMillisxp09joda-time-2.3/src/test/resources/CopticChronology.dat0000644000175000017500000000127511564251364022332 0ustar ebourgebourg¬ísr%org.joda.time.chrono.CopticChronology­V,ñŠxr%org.joda.time.chrono.BaseGJChronologyróí ´/IiMinDaysInFirstWeekxr(org.joda.time.chrono.AssembledChronology¢Ÿ¯Ù¢·¸ùLiBasetLorg/joda/time/Chronology;LiParamtLjava/lang/Object;xr#org.joda.time.chrono.BaseChronologyšŠ–Pð dxpsr$org.joda.time.chrono.ZonedChronologyñ³Ëðy€xq~sq~sr$org.joda.time.chrono.LimitChronologyjtdy*ðöjL iLowerLimittLorg/joda/time/DateTime;L iUpperLimitq~ xq~sq~pppsrorg.joda.time.DateTime¸ 0); assertEquals(true, test1.property(DateTimeFieldType.hourOfDay()).compareTo(test1) == 0); try { test1.property(DateTimeFieldType.hourOfDay()).compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.property(DateTimeFieldType.hourOfDay()).compareTo(dt2) < 0); assertEquals(true, test2.property(DateTimeFieldType.hourOfDay()).compareTo(dt1) > 0); assertEquals(true, test1.property(DateTimeFieldType.hourOfDay()).compareTo(dt1) == 0); try { test1.property(DateTimeFieldType.hourOfDay()).compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMinute() { Partial test = new Partial(TYPES, VALUES); assertSame(test.getChronology().minuteOfHour(), test.property(DateTimeFieldType.minuteOfHour()).getField()); assertEquals("minuteOfHour", test.property(DateTimeFieldType.minuteOfHour()).getName()); assertEquals("Property[minuteOfHour]", test.property(DateTimeFieldType.minuteOfHour()).toString()); assertSame(test, test.property(DateTimeFieldType.minuteOfHour()).getReadablePartial()); assertSame(test, test.property(DateTimeFieldType.minuteOfHour()).getPartial()); assertEquals(20, test.property(DateTimeFieldType.minuteOfHour()).get()); assertEquals("20", test.property(DateTimeFieldType.minuteOfHour()).getAsString()); assertEquals("20", test.property(DateTimeFieldType.minuteOfHour()).getAsText()); assertEquals("20", test.property(DateTimeFieldType.minuteOfHour()).getAsText(Locale.FRENCH)); assertEquals("20", test.property(DateTimeFieldType.minuteOfHour()).getAsShortText()); assertEquals("20", test.property(DateTimeFieldType.minuteOfHour()).getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.property(DateTimeFieldType.minuteOfHour()).getDurationField()); assertEquals(test.getChronology().hours(), test.property(DateTimeFieldType.minuteOfHour()).getRangeDurationField()); assertEquals(2, test.property(DateTimeFieldType.minuteOfHour()).getMaximumTextLength(null)); assertEquals(2, test.property(DateTimeFieldType.minuteOfHour()).getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMinute() { Partial test = new Partial(TYPES, VALUES); assertEquals(0, test.property(DateTimeFieldType.minuteOfHour()).getMinimumValue()); assertEquals(0, test.property(DateTimeFieldType.minuteOfHour()).getMinimumValueOverall()); assertEquals(59, test.property(DateTimeFieldType.minuteOfHour()).getMaximumValue()); assertEquals(59, test.property(DateTimeFieldType.minuteOfHour()).getMaximumValueOverall()); } // public void testPropertyAddMinute() { // Partial test = new Partial(TYPES, VALUES); // Partial copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(9); // check(test, 10, 20, 30, 40); // check(copy, 10, 29, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(39); // check(copy, 10, 59, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(40); // check(copy, 11, 0, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(1 * 60 + 45); // check(copy, 12, 5, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(13 * 60 + 39); // check(copy, 23, 59, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(13 * 60 + 40); // check(copy, 0, 0, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-9); // check(copy, 10, 11, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-19); // check(copy, 10, 1, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-20); // check(copy, 10, 0, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-21); // check(copy, 9, 59, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-(10 * 60 + 20)); // check(copy, 0, 0, 30, 40); // // copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-(10 * 60 + 21)); // check(copy, 23, 59, 30, 40); // } public void testPropertyAddMinute() { Partial test = new Partial(TYPES, VALUES); Partial copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(39); check(copy, 10, 59, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(40); check(copy, 11, 0, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(1 * 60 + 45); check(copy, 12, 5, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(13 * 60 + 39); check(copy, 23, 59, 30, 40); try { test.property(DateTimeFieldType.minuteOfHour()).addToCopy(13 * 60 + 40); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-9); check(copy, 10, 11, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-19); check(copy, 10, 1, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-20); check(copy, 10, 0, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-21); check(copy, 9, 59, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-(10 * 60 + 20)); check(copy, 0, 0, 30, 40); try { test.property(DateTimeFieldType.minuteOfHour()).addToCopy(-(10 * 60 + 21)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyAddWrapFieldMinute() { Partial test = new Partial(TYPES, VALUES); Partial copy = test.property(DateTimeFieldType.minuteOfHour()).addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addWrapFieldToCopy(49); check(copy, 10, 9, 30, 40); copy = test.property(DateTimeFieldType.minuteOfHour()).addWrapFieldToCopy(-47); check(copy, 10, 33, 30, 40); } public void testPropertySetMinute() { Partial test = new Partial(TYPES, VALUES); Partial copy = test.property(DateTimeFieldType.minuteOfHour()).setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 12, 30, 40); try { test.property(DateTimeFieldType.minuteOfHour()).setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.property(DateTimeFieldType.minuteOfHour()).setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMinute() { Partial test = new Partial(TYPES, VALUES); Partial copy = test.property(DateTimeFieldType.minuteOfHour()).setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 10, 12, 30, 40); } public void testPropertyCompareToMinute() { Partial test1 = new Partial(TYPES, VALUES1); Partial test2 = new Partial(TYPES, VALUES2); assertEquals(true, test1.property(DateTimeFieldType.minuteOfHour()).compareTo(test2) < 0); assertEquals(true, test2.property(DateTimeFieldType.minuteOfHour()).compareTo(test1) > 0); assertEquals(true, test1.property(DateTimeFieldType.minuteOfHour()).compareTo(test1) == 0); try { test1.property(DateTimeFieldType.minuteOfHour()).compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.property(DateTimeFieldType.minuteOfHour()).compareTo(dt2) < 0); assertEquals(true, test2.property(DateTimeFieldType.minuteOfHour()).compareTo(dt1) > 0); assertEquals(true, test1.property(DateTimeFieldType.minuteOfHour()).compareTo(dt1) == 0); try { test1.property(DateTimeFieldType.minuteOfHour()).compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- private void check(Partial test, int hour, int min, int sec, int milli) { assertEquals(hour, test.get(DateTimeFieldType.hourOfDay())); assertEquals(min, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(sec, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(milli, test.get(DateTimeFieldType.millisOfSecond())); } } joda-time-2.3/src/test/java/org/joda/time/TestPartial_Match.java0000644000175000017500000001544111564251364024137 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for Partial. * * @author Stephen Colebourne */ public class TestPartial_Match extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final int OFFSET = 1; private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON); private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS); private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME1 = 1L * DateTimeConstants.MILLIS_PER_HOUR + 2L * DateTimeConstants.MILLIS_PER_MINUTE + 3L * DateTimeConstants.MILLIS_PER_SECOND + 4L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPartial_Match.class); } public TestPartial_Match(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testIsMatch_Instant() { // Year=2005, Month=7 (July), DayOfWeek=2 (Tuesday) Partial test = createYMDwPartial(ISO_UTC, 2005, 7, 2); DateTime instant = new DateTime(2005, 7, 5, 0, 0, 0, 0); assertEquals(true, test.isMatch(instant)); instant = new DateTime(2005, 7, 4, 0, 0, 0, 0); assertEquals(false, test.isMatch(instant)); instant = new DateTime(2005, 7, 6, 0, 0, 0, 0); assertEquals(false, test.isMatch(instant)); instant = new DateTime(2005, 7, 12, 0, 0, 0, 0); assertEquals(true, test.isMatch(instant)); instant = new DateTime(2005, 7, 19, 0, 0, 0, 0); assertEquals(true, test.isMatch(instant)); instant = new DateTime(2005, 7, 26, 0, 0, 0, 0); assertEquals(true, test.isMatch(instant)); instant = new DateTime(2005, 8, 2, 0, 0, 0, 0); assertEquals(false, test.isMatch(instant)); instant = new DateTime(2006, 7, 5, 0, 0, 0, 0); assertEquals(false, test.isMatch(instant)); instant = new DateTime(2005, 6, 5, 0, 0, 0, 0); assertEquals(false, test.isMatch(instant)); } //----------------------------------------------------------------------- public void testIsMatch_Partial() { // Year=2005, Month=7 (July), DayOfWeek=2 (Tuesday) Partial test = createYMDwPartial(ISO_UTC, 2005, 7, 2); LocalDate partial = new LocalDate(2005, 7, 5); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 7, 4); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2005, 7, 6); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2005, 7, 12); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 7, 19); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 7, 26); assertEquals(true, test.isMatch(partial)); partial = new LocalDate(2005, 8, 2); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2006, 7, 5); assertEquals(false, test.isMatch(partial)); partial = new LocalDate(2005, 6, 5); assertEquals(false, test.isMatch(partial)); try { test.isMatch((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- private Partial createYMDwPartial(Chronology chrono, int year, int month, int dow) { return new Partial( new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfWeek()}, new int[] {year, month, dow}, chrono); } } joda-time-2.3/src/test/java/org/joda/time/TestYearMonth_Basics.java0000644000175000017500000006347311564251364024631 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for YearMonth. * * @author Stephen Colebourne */ public class TestYearMonth_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); // private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); // private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON); // private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); // private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS); // private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestYearMonth_Basics.class); } public TestYearMonth_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testGet() { YearMonth test = new YearMonth(); assertEquals(1970, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.dayOfMonth()); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { YearMonth test = new YearMonth(); assertEquals(2, test.size()); } public void testGetFieldType() { YearMonth test = new YearMonth(COPTIC_PARIS); assertSame(DateTimeFieldType.year(), test.getFieldType(0)); assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(1)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { YearMonth test = new YearMonth(COPTIC_PARIS); DateTimeFieldType[] fields = test.getFieldTypes(); assertEquals(2, fields.length); assertSame(DateTimeFieldType.year(), fields[0]); assertSame(DateTimeFieldType.monthOfYear(), fields[1]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField() { YearMonth test = new YearMonth(COPTIC_PARIS); assertSame(COPTIC_UTC.year(), test.getField(0)); assertSame(COPTIC_UTC.monthOfYear(), test.getField(1)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { YearMonth test = new YearMonth(COPTIC_PARIS); DateTimeField[] fields = test.getFields(); assertEquals(2, fields.length); assertSame(COPTIC_UTC.year(), fields[0]); assertSame(COPTIC_UTC.monthOfYear(), fields[1]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue() { YearMonth test = new YearMonth(); assertEquals(1970, test.getValue(0)); assertEquals(6, test.getValue(1)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { YearMonth test = new YearMonth(); int[] values = test.getValues(); assertEquals(2, values.length); assertEquals(1970, values[0]); assertEquals(6, values[1]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported() { YearMonth test = new YearMonth(COPTIC_PARIS); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear())); assertEquals(false, test.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay())); } public void testEqualsHashCode() { YearMonth test1 = new YearMonth(1970, 6, COPTIC_PARIS); YearMonth test2 = new YearMonth(1970, 6, COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); YearMonth test3 = new YearMonth(1971, 6); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockYM())); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); } class MockYM extends MockPartial { public Chronology getChronology() { return COPTIC_UTC; } public DateTimeField[] getFields() { return new DateTimeField[] { COPTIC_UTC.year(), COPTIC_UTC.monthOfYear(), }; } public int[] getValues() { return new int[] {1970, 6}; } } //----------------------------------------------------------------------- public void testCompareTo() { YearMonth test1 = new YearMonth(2005, 6); YearMonth test1a = new YearMonth(2005, 6); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); YearMonth test2 = new YearMonth(2005, 7); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); YearMonth test3 = new YearMonth(2005, 7, GregorianChronology.getInstanceUTC()); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), }; int[] values = new int[] {2005, 6}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} try { test1.compareTo(new LocalTime()); fail(); } catch (ClassCastException ex) {} Partial partial = new Partial() .with(DateTimeFieldType.centuryOfEra(), 1) .with(DateTimeFieldType.halfdayOfDay(), 0) .with(DateTimeFieldType.dayOfMonth(), 9); try { new YearMonth(1970, 6).compareTo(partial); fail(); } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_YM() { YearMonth test1 = new YearMonth(2005, 6); YearMonth test1a = new YearMonth(2005, 6); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); YearMonth test2 = new YearMonth(2005, 7); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); YearMonth test3 = new YearMonth(2005, 7, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { new YearMonth(2005, 7).isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_YM() { YearMonth test1 = new YearMonth(2005, 6); YearMonth test1a = new YearMonth(2005, 6); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); YearMonth test2 = new YearMonth(2005, 7); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); YearMonth test3 = new YearMonth(2005, 7, GregorianChronology.getInstanceUTC()); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new YearMonth(2005, 7).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_YM() { YearMonth test1 = new YearMonth(2005, 6); YearMonth test1a = new YearMonth(2005, 6); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); YearMonth test2 = new YearMonth(2005, 7); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); YearMonth test3 = new YearMonth(2005, 7, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new YearMonth(2005, 7).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithChronologyRetainFields_Chrono() { YearMonth base = new YearMonth(2005, 6, COPTIC_PARIS); YearMonth test = base.withChronologyRetainFields(BUDDHIST_TOKYO); check(base, 2005, 6); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 2005, 6); assertEquals(BUDDHIST_UTC, test.getChronology()); } public void testWithChronologyRetainFields_sameChrono() { YearMonth base = new YearMonth(2005, 6, COPTIC_PARIS); YearMonth test = base.withChronologyRetainFields(COPTIC_TOKYO); assertSame(base, test); } public void testWithChronologyRetainFields_nullChrono() { YearMonth base = new YearMonth(2005, 6, COPTIC_PARIS); YearMonth test = base.withChronologyRetainFields(null); check(base, 2005, 6); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 2005, 6); assertEquals(ISO_UTC, test.getChronology()); } public void testWithChronologyRetainFields_invalidInNewChrono() { YearMonth base = new YearMonth(2005, 13, COPTIC_UTC); try { base.withChronologyRetainFields(ISO_UTC); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- public void testWithField() { YearMonth test = new YearMonth(2004, 6); YearMonth result = test.withField(DateTimeFieldType.year(), 2006); assertEquals(new YearMonth(2004, 6), test); assertEquals(new YearMonth(2006, 6), result); } public void testWithField_nullField() { YearMonth test = new YearMonth(2004, 6); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_unknownField() { YearMonth test = new YearMonth(2004, 6); try { test.withField(DateTimeFieldType.hourOfDay(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_same() { YearMonth test = new YearMonth(2004, 6); YearMonth result = test.withField(DateTimeFieldType.year(), 2004); assertEquals(new YearMonth(2004, 6), test); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded() { YearMonth test = new YearMonth(2004, 6); YearMonth result = test.withFieldAdded(DurationFieldType.years(), 6); assertEquals(new YearMonth(2004, 6), test); assertEquals(new YearMonth(2010, 6), result); } public void testWithFieldAdded_nullField_zero() { YearMonth test = new YearMonth(2004, 6); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_nullField_nonZero() { YearMonth test = new YearMonth(2004, 6); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_zero() { YearMonth test = new YearMonth(2004, 6); YearMonth result = test.withFieldAdded(DurationFieldType.years(), 0); assertSame(test, result); } public void testWithFieldAdded_unknownField() { YearMonth test = new YearMonth(2004, 6); try { test.withFieldAdded(DurationFieldType.hours(), 6); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPlus_RP() { YearMonth test = new YearMonth(2002, 5, BuddhistChronology.getInstance()); YearMonth result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8)); YearMonth expected = new YearMonth(2003, 7, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusYears_int() { YearMonth test = new YearMonth(2002, 5, BuddhistChronology.getInstance()); YearMonth result = test.plusYears(1); YearMonth expected = new YearMonth(2003, 5, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusYears(0); assertSame(test, result); } public void testPlusMonths_int() { YearMonth test = new YearMonth(2002, 5, BuddhistChronology.getInstance()); YearMonth result = test.plusMonths(1); YearMonth expected = new YearMonth(2002, 6, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusMonths(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { YearMonth test = new YearMonth(2002, 5, BuddhistChronology.getInstance()); YearMonth result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); YearMonth expected = new YearMonth(2001, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusYears_int() { YearMonth test = new YearMonth(2002, 5, BuddhistChronology.getInstance()); YearMonth result = test.minusYears(1); YearMonth expected = new YearMonth(2001, 5, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusYears(0); assertSame(test, result); } public void testMinusMonths_int() { YearMonth test = new YearMonth(2002, 5, BuddhistChronology.getInstance()); YearMonth result = test.minusMonths(1); YearMonth expected = new YearMonth(2002, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusMonths(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testToLocalDate() { YearMonth base = new YearMonth(2005, 6, COPTIC_UTC); LocalDate test = base.toLocalDate(9); assertEquals(new LocalDate(2005, 6, 9, COPTIC_UTC), test); try { base.toLocalDate(0); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testToDateTime_RI() { YearMonth base = new YearMonth(2005, 6, COPTIC_PARIS); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTime test = base.toDateTime(dt); check(base, 2005, 6); DateTime expected = dt; expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); assertEquals(expected, test); } public void testToDateTime_nullRI() { YearMonth base = new YearMonth(2005, 6); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 2005, 6); DateTime expected = dt; expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToInterval() { YearMonth base = new YearMonth(2005, 6, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(); check(base, 2005, 6); DateTime start = new DateTime(2005, 6, 1, 0, 0, COPTIC_LONDON); DateTime end = new DateTime(2005, 7, 1, 0, 0, COPTIC_LONDON); Interval expected = new Interval(start, end); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToInterval_Zone() { YearMonth base = new YearMonth(2005, 6, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(TOKYO); check(base, 2005, 6); DateTime start = new DateTime(2005, 6, 1, 0, 0, COPTIC_TOKYO); DateTime end = new DateTime(2005, 7, 1, 0, 0, COPTIC_TOKYO); Interval expected = new Interval(start, end); assertEquals(expected, test); } public void testToInterval_nullZone() { YearMonth base = new YearMonth(2005, 6, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(null); check(base, 2005, 6); DateTime start = new DateTime(2005, 6, 1, 0, 0, COPTIC_LONDON); DateTime end = new DateTime(2005, 7, 1, 0, 0, COPTIC_LONDON); Interval expected = new Interval(start, end); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testWithers() { YearMonth test = new YearMonth(1970, 6); check(test.withYear(2000), 2000, 6); check(test.withMonthOfYear(2), 1970, 2); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testProperty() { YearMonth test = new YearMonth(2005, 6); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear())); try { test.property(DateTimeFieldType.millisOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { YearMonth test = new YearMonth(1972, 6, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); YearMonth result = (YearMonth) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); } //----------------------------------------------------------------------- public void testToString() { YearMonth test = new YearMonth(2002, 6); assertEquals("2002-06", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { YearMonth test = new YearMonth(2002, 6); assertEquals("2002 \ufffd\ufffd", test.toString("yyyy HH")); assertEquals("2002-06", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { YearMonth test = new YearMonth(2002, 6); assertEquals("\ufffd \ufffd/6", test.toString("EEE d/M", Locale.ENGLISH)); assertEquals("\ufffd \ufffd/6", test.toString("EEE d/M", Locale.FRENCH)); assertEquals("2002-06", test.toString(null, Locale.ENGLISH)); assertEquals("\ufffd \ufffd/6", test.toString("EEE d/M", null)); assertEquals("2002-06", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { YearMonth test = new YearMonth(2002, 6); assertEquals("2002 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("2002-06", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private void check(YearMonth test, int year, int month) { assertEquals(year, test.getYear()); assertEquals(month, test.getMonthOfYear()); } } joda-time-2.3/src/test/java/org/joda/time/TestMonths.java0000644000175000017500000003372312200501234022660 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for Months. * * @author Stephen Colebourne */ public class TestMonths extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMonths.class); } public TestMonths(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testConstants() { assertEquals(0, Months.ZERO.getMonths()); assertEquals(1, Months.ONE.getMonths()); assertEquals(2, Months.TWO.getMonths()); assertEquals(3, Months.THREE.getMonths()); assertEquals(4, Months.FOUR.getMonths()); assertEquals(5, Months.FIVE.getMonths()); assertEquals(6, Months.SIX.getMonths()); assertEquals(7, Months.SEVEN.getMonths()); assertEquals(8, Months.EIGHT.getMonths()); assertEquals(9, Months.NINE.getMonths()); assertEquals(10, Months.TEN.getMonths()); assertEquals(11, Months.ELEVEN.getMonths()); assertEquals(12, Months.TWELVE.getMonths()); assertEquals(Integer.MAX_VALUE, Months.MAX_VALUE.getMonths()); assertEquals(Integer.MIN_VALUE, Months.MIN_VALUE.getMonths()); } //----------------------------------------------------------------------- public void testFactory_months_int() { assertSame(Months.ZERO, Months.months(0)); assertSame(Months.ONE, Months.months(1)); assertSame(Months.TWO, Months.months(2)); assertSame(Months.THREE, Months.months(3)); assertSame(Months.FOUR, Months.months(4)); assertSame(Months.FIVE, Months.months(5)); assertSame(Months.SIX, Months.months(6)); assertSame(Months.SEVEN, Months.months(7)); assertSame(Months.EIGHT, Months.months(8)); assertSame(Months.NINE, Months.months(9)); assertSame(Months.TEN, Months.months(10)); assertSame(Months.ELEVEN, Months.months(11)); assertSame(Months.TWELVE, Months.months(12)); assertSame(Months.MAX_VALUE, Months.months(Integer.MAX_VALUE)); assertSame(Months.MIN_VALUE, Months.months(Integer.MIN_VALUE)); assertEquals(-1, Months.months(-1).getMonths()); assertEquals(13, Months.months(13).getMonths()); } //----------------------------------------------------------------------- public void testFactory_monthsBetween_RInstant() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 9, 9, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 12, 9, 12, 0, 0, 0, PARIS); assertEquals(3, Months.monthsBetween(start, end1).getMonths()); assertEquals(0, Months.monthsBetween(start, start).getMonths()); assertEquals(0, Months.monthsBetween(end1, end1).getMonths()); assertEquals(-3, Months.monthsBetween(end1, start).getMonths()); assertEquals(6, Months.monthsBetween(start, end2).getMonths()); } //------------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testFactory_monthsBetween_RPartial_LocalDate() { LocalDate start = new LocalDate(2006, 6, 9); LocalDate end1 = new LocalDate(2006, 9, 9); YearMonthDay end2 = new YearMonthDay(2006, 12, 9); assertEquals(3, Months.monthsBetween(start, end1).getMonths()); assertEquals(0, Months.monthsBetween(start, start).getMonths()); assertEquals(0, Months.monthsBetween(end1, end1).getMonths()); assertEquals(-3, Months.monthsBetween(end1, start).getMonths()); assertEquals(6, Months.monthsBetween(start, end2).getMonths()); } public void testFactory_monthsBetween_RPartial_YearMonth() { YearMonth start1 = new YearMonth(2011, 1); for (int i = 0; i < 6; i++) { YearMonth start2 = new YearMonth(2011 + i, 1); YearMonth end = new YearMonth(2011 + i, 3); assertEquals(i * 12 + 2, Months.monthsBetween(start1, end).getMonths()); assertEquals(2, Months.monthsBetween(start2, end).getMonths()); } } public void testFactory_monthsBetween_RPartial_MonthDay() { MonthDay start = new MonthDay(2, 1); MonthDay end1 = new MonthDay(2, 28); MonthDay end2 = new MonthDay(2, 29); MonthDay end3 = new MonthDay(3, 1); assertEquals(0, Months.monthsBetween(start, end1).getMonths()); assertEquals(0, Months.monthsBetween(start, end2).getMonths()); assertEquals(1, Months.monthsBetween(start, end3).getMonths()); assertEquals(0, Months.monthsBetween(end1, start).getMonths()); assertEquals(0, Months.monthsBetween(end2, start).getMonths()); assertEquals(-1, Months.monthsBetween(end3, start).getMonths()); } //------------------------------------------------------------------------- public void testFactory_monthsIn_RInterval() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 9, 9, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 12, 9, 12, 0, 0, 0, PARIS); assertEquals(0, Months.monthsIn((ReadableInterval) null).getMonths()); assertEquals(3, Months.monthsIn(new Interval(start, end1)).getMonths()); assertEquals(0, Months.monthsIn(new Interval(start, start)).getMonths()); assertEquals(0, Months.monthsIn(new Interval(end1, end1)).getMonths()); assertEquals(6, Months.monthsIn(new Interval(start, end2)).getMonths()); } public void testFactory_parseMonths_String() { assertEquals(0, Months.parseMonths((String) null).getMonths()); assertEquals(0, Months.parseMonths("P0M").getMonths()); assertEquals(1, Months.parseMonths("P1M").getMonths()); assertEquals(-3, Months.parseMonths("P-3M").getMonths()); assertEquals(2, Months.parseMonths("P0Y2M").getMonths()); assertEquals(2, Months.parseMonths("P2MT0H0M").getMonths()); try { Months.parseMonths("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Months.parseMonths("P1MT1H"); fail(); } catch (IllegalArgumentException ex) { // expeceted } } //----------------------------------------------------------------------- public void testGetMethods() { Months test = Months.months(20); assertEquals(20, test.getMonths()); } public void testGetFieldType() { Months test = Months.months(20); assertEquals(DurationFieldType.months(), test.getFieldType()); } public void testGetPeriodType() { Months test = Months.months(20); assertEquals(PeriodType.months(), test.getPeriodType()); } //----------------------------------------------------------------------- public void testIsGreaterThan() { assertEquals(true, Months.THREE.isGreaterThan(Months.TWO)); assertEquals(false, Months.THREE.isGreaterThan(Months.THREE)); assertEquals(false, Months.TWO.isGreaterThan(Months.THREE)); assertEquals(true, Months.ONE.isGreaterThan(null)); assertEquals(false, Months.months(-1).isGreaterThan(null)); } public void testIsLessThan() { assertEquals(false, Months.THREE.isLessThan(Months.TWO)); assertEquals(false, Months.THREE.isLessThan(Months.THREE)); assertEquals(true, Months.TWO.isLessThan(Months.THREE)); assertEquals(false, Months.ONE.isLessThan(null)); assertEquals(true, Months.months(-1).isLessThan(null)); } //----------------------------------------------------------------------- public void testToString() { Months test = Months.months(20); assertEquals("P20M", test.toString()); test = Months.months(-20); assertEquals("P-20M", test.toString()); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Months test = Months.THREE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Months result = (Months) ois.readObject(); ois.close(); assertSame(test, result); } //----------------------------------------------------------------------- public void testPlus_int() { Months test2 = Months.months(2); Months result = test2.plus(3); assertEquals(2, test2.getMonths()); assertEquals(5, result.getMonths()); assertEquals(1, Months.ONE.plus(0).getMonths()); try { Months.MAX_VALUE.plus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testPlus_Months() { Months test2 = Months.months(2); Months test3 = Months.months(3); Months result = test2.plus(test3); assertEquals(2, test2.getMonths()); assertEquals(3, test3.getMonths()); assertEquals(5, result.getMonths()); assertEquals(1, Months.ONE.plus(Months.ZERO).getMonths()); assertEquals(1, Months.ONE.plus((Months) null).getMonths()); try { Months.MAX_VALUE.plus(Months.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_int() { Months test2 = Months.months(2); Months result = test2.minus(3); assertEquals(2, test2.getMonths()); assertEquals(-1, result.getMonths()); assertEquals(1, Months.ONE.minus(0).getMonths()); try { Months.MIN_VALUE.minus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_Months() { Months test2 = Months.months(2); Months test3 = Months.months(3); Months result = test2.minus(test3); assertEquals(2, test2.getMonths()); assertEquals(3, test3.getMonths()); assertEquals(-1, result.getMonths()); assertEquals(1, Months.ONE.minus(Months.ZERO).getMonths()); assertEquals(1, Months.ONE.minus((Months) null).getMonths()); try { Months.MIN_VALUE.minus(Months.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMultipliedBy_int() { Months test = Months.months(2); assertEquals(6, test.multipliedBy(3).getMonths()); assertEquals(2, test.getMonths()); assertEquals(-6, test.multipliedBy(-3).getMonths()); assertSame(test, test.multipliedBy(1)); Months halfMax = Months.months(Integer.MAX_VALUE / 2 + 1); try { halfMax.multipliedBy(2); fail(); } catch (ArithmeticException ex) { // expected } } public void testDividedBy_int() { Months test = Months.months(12); assertEquals(6, test.dividedBy(2).getMonths()); assertEquals(12, test.getMonths()); assertEquals(4, test.dividedBy(3).getMonths()); assertEquals(3, test.dividedBy(4).getMonths()); assertEquals(2, test.dividedBy(5).getMonths()); assertEquals(2, test.dividedBy(6).getMonths()); assertSame(test, test.dividedBy(1)); try { Months.ONE.dividedBy(0); fail(); } catch (ArithmeticException ex) { // expected } } public void testNegated() { Months test = Months.months(12); assertEquals(-12, test.negated().getMonths()); assertEquals(12, test.getMonths()); try { Months.MIN_VALUE.negated(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testAddToLocalDate() { Months test = Months.months(3); LocalDate date = new LocalDate(2006, 6, 1); LocalDate expected = new LocalDate(2006, 9, 1); assertEquals(expected, date.plus(test)); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalTime_Properties.java0000644000175000017500000007662111564251364025523 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for TimeOfDay. * * @author Stephen Colebourne */ public class TestLocalTime_Properties extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME1 = 1L * DateTimeConstants.MILLIS_PER_HOUR + 2L * DateTimeConstants.MILLIS_PER_MINUTE + 3L * DateTimeConstants.MILLIS_PER_SECOND + 4L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalTime_Properties.class); } public TestLocalTime_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testPropertyGetHour() { LocalTime test = new LocalTime(10, 20, 30, 40); assertSame(test.getChronology().hourOfDay(), test.hourOfDay().getField()); assertEquals("hourOfDay", test.hourOfDay().getName()); assertEquals("Property[hourOfDay]", test.hourOfDay().toString()); assertSame(test, test.hourOfDay().getLocalTime()); assertEquals(10, test.hourOfDay().get()); assertEquals("10", test.hourOfDay().getAsString()); assertEquals("10", test.hourOfDay().getAsText()); assertEquals("10", test.hourOfDay().getAsText(Locale.FRENCH)); assertEquals("10", test.hourOfDay().getAsShortText()); assertEquals("10", test.hourOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().hours(), test.hourOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.hourOfDay().getRangeDurationField()); assertEquals(2, test.hourOfDay().getMaximumTextLength(null)); assertEquals(2, test.hourOfDay().getMaximumShortTextLength(null)); } public void testPropertyRoundHour() { LocalTime test = new LocalTime(10, 20); check(test.hourOfDay().roundCeilingCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 10, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 10, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 10, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 10, 0, 0, 0); test = new LocalTime(10, 40); check(test.hourOfDay().roundCeilingCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 10, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 11, 0, 0, 0); test = new LocalTime(10, 30); check(test.hourOfDay().roundCeilingCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 10, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 10, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 10, 0, 0, 0); test = new LocalTime(11, 30); check(test.hourOfDay().roundCeilingCopy(), 12, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 12, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 11, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 12, 0, 0, 0); } public void testPropertyGetMaxMinValuesHour() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(0, test.hourOfDay().getMinimumValue()); assertEquals(0, test.hourOfDay().getMinimumValueOverall()); assertEquals(23, test.hourOfDay().getMaximumValue()); assertEquals(23, test.hourOfDay().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueHour() { LocalTime test = new LocalTime(10, 20, 30, 40); check(test.hourOfDay().withMaximumValue(), 23, 20, 30, 40); check(test.hourOfDay().withMinimumValue(), 0, 20, 30, 40); } public void testPropertyPlusHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().addCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addCopy(13); check(copy, 23, 20, 30, 40); copy = test.hourOfDay().addCopy(14); check(copy, 0, 20, 30, 40); copy = test.hourOfDay().addCopy(-10); check(copy, 0, 20, 30, 40); copy = test.hourOfDay().addCopy(-11); check(copy, 23, 20, 30, 40); } public void testPropertyPlusNoWrapHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(13); check(copy, 23, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(14); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(-10); check(copy, 0, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(-11); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyPlusWrapFieldHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(18); check(copy, 4, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(-15); check(copy, 19, 20, 30, 40); } public void testPropertySetHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 12, 20, 30, 40); try { test.hourOfDay().setCopy(24); fail(); } catch (IllegalArgumentException ex) {} try { test.hourOfDay().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 12, 20, 30, 40); } public void testPropertyWithMaximumValueHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().withMaximumValue(); check(test, 10, 20, 30, 40); check(copy, 23, 20, 30, 40); } public void testPropertyWithMinimumValueHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().withMinimumValue(); check(test, 10, 20, 30, 40); check(copy, 0, 20, 30, 40); } public void testPropertyCompareToHour() { LocalTime test1 = new LocalTime(TEST_TIME1); LocalTime test2 = new LocalTime(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(test2) < 0); assertEquals(true, test2.hourOfDay().compareTo(test1) > 0); assertEquals(true, test1.hourOfDay().compareTo(test1) == 0); try { test1.hourOfDay().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(dt2) < 0); assertEquals(true, test2.hourOfDay().compareTo(dt1) > 0); assertEquals(true, test1.hourOfDay().compareTo(dt1) == 0); try { test1.hourOfDay().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); assertSame(test.getChronology().minuteOfHour(), test.minuteOfHour().getField()); assertEquals("minuteOfHour", test.minuteOfHour().getName()); assertEquals("Property[minuteOfHour]", test.minuteOfHour().toString()); assertSame(test, test.minuteOfHour().getLocalTime()); assertEquals(20, test.minuteOfHour().get()); assertEquals("20", test.minuteOfHour().getAsString()); assertEquals("20", test.minuteOfHour().getAsText()); assertEquals("20", test.minuteOfHour().getAsText(Locale.FRENCH)); assertEquals("20", test.minuteOfHour().getAsShortText()); assertEquals("20", test.minuteOfHour().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.minuteOfHour().getDurationField()); assertEquals(test.getChronology().hours(), test.minuteOfHour().getRangeDurationField()); assertEquals(2, test.minuteOfHour().getMaximumTextLength(null)); assertEquals(2, test.minuteOfHour().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(0, test.minuteOfHour().getMinimumValue()); assertEquals(0, test.minuteOfHour().getMinimumValueOverall()); assertEquals(59, test.minuteOfHour().getMaximumValue()); assertEquals(59, test.minuteOfHour().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); check(test.minuteOfHour().withMaximumValue(), 10, 59, 30, 40); check(test.minuteOfHour().withMinimumValue(), 10, 0, 30, 40); } public void testPropertyPlusMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.minuteOfHour().addCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.minuteOfHour().addCopy(39); check(copy, 10, 59, 30, 40); copy = test.minuteOfHour().addCopy(40); check(copy, 11, 0, 30, 40); copy = test.minuteOfHour().addCopy(1 * 60 + 45); check(copy, 12, 5, 30, 40); copy = test.minuteOfHour().addCopy(13 * 60 + 39); check(copy, 23, 59, 30, 40); copy = test.minuteOfHour().addCopy(13 * 60 + 40); check(copy, 0, 0, 30, 40); copy = test.minuteOfHour().addCopy(-9); check(copy, 10, 11, 30, 40); copy = test.minuteOfHour().addCopy(-19); check(copy, 10, 1, 30, 40); copy = test.minuteOfHour().addCopy(-20); check(copy, 10, 0, 30, 40); copy = test.minuteOfHour().addCopy(-21); check(copy, 9, 59, 30, 40); copy = test.minuteOfHour().addCopy(-(10 * 60 + 20)); check(copy, 0, 0, 30, 40); copy = test.minuteOfHour().addCopy(-(10 * 60 + 21)); check(copy, 23, 59, 30, 40); } public void testPropertyPlusNoWrapMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.minuteOfHour().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(39); check(copy, 10, 59, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(40); check(copy, 11, 0, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(1 * 60 + 45); check(copy, 12, 5, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(13 * 60 + 39); check(copy, 23, 59, 30, 40); try { test.minuteOfHour().addNoWrapToCopy(13 * 60 + 40); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-9); check(copy, 10, 11, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-19); check(copy, 10, 1, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-20); check(copy, 10, 0, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-21); check(copy, 9, 59, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 20)); check(copy, 0, 0, 30, 40); try { test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 21)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyPlusWrapFieldMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.minuteOfHour().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.minuteOfHour().addWrapFieldToCopy(49); check(copy, 10, 9, 30, 40); copy = test.minuteOfHour().addWrapFieldToCopy(-47); check(copy, 10, 33, 30, 40); } public void testPropertySetMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.minuteOfHour().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 12, 30, 40); try { test.minuteOfHour().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.minuteOfHour().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.minuteOfHour().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 10, 12, 30, 40); } public void testPropertyCompareToMinute() { LocalTime test1 = new LocalTime(TEST_TIME1); LocalTime test2 = new LocalTime(TEST_TIME2); assertEquals(true, test1.minuteOfHour().compareTo(test2) < 0); assertEquals(true, test2.minuteOfHour().compareTo(test1) > 0); assertEquals(true, test1.minuteOfHour().compareTo(test1) == 0); try { test1.minuteOfHour().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.minuteOfHour().compareTo(dt2) < 0); assertEquals(true, test2.minuteOfHour().compareTo(dt1) > 0); assertEquals(true, test1.minuteOfHour().compareTo(dt1) == 0); try { test1.minuteOfHour().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); assertSame(test.getChronology().secondOfMinute(), test.secondOfMinute().getField()); assertEquals("secondOfMinute", test.secondOfMinute().getName()); assertEquals("Property[secondOfMinute]", test.secondOfMinute().toString()); assertSame(test, test.secondOfMinute().getLocalTime()); assertEquals(30, test.secondOfMinute().get()); assertEquals("30", test.secondOfMinute().getAsString()); assertEquals("30", test.secondOfMinute().getAsText()); assertEquals("30", test.secondOfMinute().getAsText(Locale.FRENCH)); assertEquals("30", test.secondOfMinute().getAsShortText()); assertEquals("30", test.secondOfMinute().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().seconds(), test.secondOfMinute().getDurationField()); assertEquals(test.getChronology().minutes(), test.secondOfMinute().getRangeDurationField()); assertEquals(2, test.secondOfMinute().getMaximumTextLength(null)); assertEquals(2, test.secondOfMinute().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(0, test.secondOfMinute().getMinimumValue()); assertEquals(0, test.secondOfMinute().getMinimumValueOverall()); assertEquals(59, test.secondOfMinute().getMaximumValue()); assertEquals(59, test.secondOfMinute().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); check(test.secondOfMinute().withMaximumValue(), 10, 20, 59, 40); check(test.secondOfMinute().withMinimumValue(), 10, 20, 0, 40); } public void testPropertyPlusSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.secondOfMinute().addCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 39, 40); copy = test.secondOfMinute().addCopy(29); check(copy, 10, 20, 59, 40); copy = test.secondOfMinute().addCopy(30); check(copy, 10, 21, 0, 40); copy = test.secondOfMinute().addCopy(39 * 60 + 29); check(copy, 10, 59, 59, 40); copy = test.secondOfMinute().addCopy(39 * 60 + 30); check(copy, 11, 0, 0, 40); copy = test.secondOfMinute().addCopy(13 * 60 * 60 + 39 * 60 + 30); check(copy, 0, 0, 0, 40); copy = test.secondOfMinute().addCopy(-9); check(copy, 10, 20, 21, 40); copy = test.secondOfMinute().addCopy(-30); check(copy, 10, 20, 0, 40); copy = test.secondOfMinute().addCopy(-31); check(copy, 10, 19, 59, 40); copy = test.secondOfMinute().addCopy(-(10 * 60 * 60 + 20 * 60 + 30)); check(copy, 0, 0, 0, 40); copy = test.secondOfMinute().addCopy(-(10 * 60 * 60 + 20 * 60 + 31)); check(copy, 23, 59, 59, 40); } public void testPropertyPlusNoWrapSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.secondOfMinute().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 39, 40); copy = test.secondOfMinute().addNoWrapToCopy(29); check(copy, 10, 20, 59, 40); copy = test.secondOfMinute().addNoWrapToCopy(30); check(copy, 10, 21, 0, 40); copy = test.secondOfMinute().addNoWrapToCopy(39 * 60 + 29); check(copy, 10, 59, 59, 40); copy = test.secondOfMinute().addNoWrapToCopy(39 * 60 + 30); check(copy, 11, 0, 0, 40); try { test.secondOfMinute().addNoWrapToCopy(13 * 60 * 60 + 39 * 60 + 30); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.secondOfMinute().addNoWrapToCopy(-9); check(copy, 10, 20, 21, 40); copy = test.secondOfMinute().addNoWrapToCopy(-30); check(copy, 10, 20, 0, 40); copy = test.secondOfMinute().addNoWrapToCopy(-31); check(copy, 10, 19, 59, 40); copy = test.secondOfMinute().addNoWrapToCopy(-(10 * 60 * 60 + 20 * 60 + 30)); check(copy, 0, 0, 0, 40); try { test.secondOfMinute().addNoWrapToCopy(-(10 * 60 * 60 + 20 * 60 + 31)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyPlusWrapFieldSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.secondOfMinute().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 39, 40); copy = test.secondOfMinute().addWrapFieldToCopy(49); check(copy, 10, 20, 19, 40); copy = test.secondOfMinute().addWrapFieldToCopy(-47); check(copy, 10, 20, 43, 40); } public void testPropertySetSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.secondOfMinute().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 20, 12, 40); try { test.secondOfMinute().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.secondOfMinute().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextSecond() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.secondOfMinute().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 10, 20, 12, 40); } public void testPropertyCompareToSecond() { LocalTime test1 = new LocalTime(TEST_TIME1); LocalTime test2 = new LocalTime(TEST_TIME2); assertEquals(true, test1.secondOfMinute().compareTo(test2) < 0); assertEquals(true, test2.secondOfMinute().compareTo(test1) > 0); assertEquals(true, test1.secondOfMinute().compareTo(test1) == 0); try { test1.secondOfMinute().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.secondOfMinute().compareTo(dt2) < 0); assertEquals(true, test2.secondOfMinute().compareTo(dt1) > 0); assertEquals(true, test1.secondOfMinute().compareTo(dt1) == 0); try { test1.secondOfMinute().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); assertSame(test.getChronology().millisOfSecond(), test.millisOfSecond().getField()); assertEquals("millisOfSecond", test.millisOfSecond().getName()); assertEquals("Property[millisOfSecond]", test.millisOfSecond().toString()); assertSame(test, test.millisOfSecond().getLocalTime()); assertEquals(40, test.millisOfSecond().get()); assertEquals("40", test.millisOfSecond().getAsString()); assertEquals("40", test.millisOfSecond().getAsText()); assertEquals("40", test.millisOfSecond().getAsText(Locale.FRENCH)); assertEquals("40", test.millisOfSecond().getAsShortText()); assertEquals("40", test.millisOfSecond().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().millis(), test.millisOfSecond().getDurationField()); assertEquals(test.getChronology().seconds(), test.millisOfSecond().getRangeDurationField()); assertEquals(3, test.millisOfSecond().getMaximumTextLength(null)); assertEquals(3, test.millisOfSecond().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(0, test.millisOfSecond().getMinimumValue()); assertEquals(0, test.millisOfSecond().getMinimumValueOverall()); assertEquals(999, test.millisOfSecond().getMaximumValue()); assertEquals(999, test.millisOfSecond().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); check(test.millisOfSecond().withMaximumValue(), 10, 20, 30, 999); check(test.millisOfSecond().withMinimumValue(), 10, 20, 30, 0); } public void testPropertyPlusMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.millisOfSecond().addCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 49); copy = test.millisOfSecond().addCopy(959); check(copy, 10, 20, 30, 999); copy = test.millisOfSecond().addCopy(960); check(copy, 10, 20, 31, 0); copy = test.millisOfSecond().addCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 959); check(copy, 23, 59, 59, 999); copy = test.millisOfSecond().addCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 960); check(copy, 0, 0, 0, 0); copy = test.millisOfSecond().addCopy(-9); check(copy, 10, 20, 30, 31); copy = test.millisOfSecond().addCopy(-40); check(copy, 10, 20, 30, 0); copy = test.millisOfSecond().addCopy(-41); check(copy, 10, 20, 29, 999); copy = test.millisOfSecond().addCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 40)); check(copy, 0, 0, 0, 0); copy = test.millisOfSecond().addCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 41)); check(copy, 23, 59, 59, 999); } public void testPropertyPlusNoWrapMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.millisOfSecond().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 49); copy = test.millisOfSecond().addNoWrapToCopy(959); check(copy, 10, 20, 30, 999); copy = test.millisOfSecond().addNoWrapToCopy(960); check(copy, 10, 20, 31, 0); copy = test.millisOfSecond().addNoWrapToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 959); check(copy, 23, 59, 59, 999); try { test.millisOfSecond().addNoWrapToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 960); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.millisOfSecond().addNoWrapToCopy(-9); check(copy, 10, 20, 30, 31); copy = test.millisOfSecond().addNoWrapToCopy(-40); check(copy, 10, 20, 30, 0); copy = test.millisOfSecond().addNoWrapToCopy(-41); check(copy, 10, 20, 29, 999); copy = test.millisOfSecond().addNoWrapToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 40)); check(copy, 0, 0, 0, 0); try { test.millisOfSecond().addNoWrapToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 41)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyPlusWrapFieldMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.millisOfSecond().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 49); copy = test.millisOfSecond().addWrapFieldToCopy(995); check(copy, 10, 20, 30, 35); copy = test.millisOfSecond().addWrapFieldToCopy(-47); check(copy, 10, 20, 30, 993); } public void testPropertySetMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.millisOfSecond().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 12); try { test.millisOfSecond().setCopy(1000); fail(); } catch (IllegalArgumentException ex) {} try { test.millisOfSecond().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMilli() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.millisOfSecond().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 12); } public void testPropertyCompareToMilli() { LocalTime test1 = new LocalTime(TEST_TIME1); LocalTime test2 = new LocalTime(TEST_TIME2); assertEquals(true, test1.millisOfSecond().compareTo(test2) < 0); assertEquals(true, test2.millisOfSecond().compareTo(test1) > 0); assertEquals(true, test1.millisOfSecond().compareTo(test1) == 0); try { test1.millisOfSecond().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.millisOfSecond().compareTo(dt2) < 0); assertEquals(true, test2.millisOfSecond().compareTo(dt1) > 0); assertEquals(true, test1.millisOfSecond().compareTo(dt1) == 0); try { test1.millisOfSecond().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- private void check(LocalTime test, int hour, int min, int sec, int milli) { assertEquals(hour, test.getHourOfDay()); assertEquals(min, test.getMinuteOfHour()); assertEquals(sec, test.getSecondOfMinute()); assertEquals(milli, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/field/0000755000175000017500000000000012205344143020771 5ustar ebourgebourgjoda-time-2.3/src/test/java/org/joda/time/field/TestOffsetDateTimeField.java0000644000175000017500000005345411564251364026327 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.TimeOfDay; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for PreciseDateTimeField. * * @author Stephen Colebourne */ public class TestOffsetDateTimeField extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestOffsetDateTimeField.class); } public TestOffsetDateTimeField(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_constructor1() { OffsetDateTimeField field = new OffsetDateTimeField( ISOChronology.getInstance().secondOfMinute(), 3 ); assertEquals(DateTimeFieldType.secondOfMinute(), field.getType()); assertEquals(3, field.getOffset()); try { field = new OffsetDateTimeField(null, 3); fail(); } catch (IllegalArgumentException ex) {} try { field = new OffsetDateTimeField(ISOChronology.getInstance().secondOfMinute(), 0); fail(); } catch (IllegalArgumentException ex) {} try { field = new OffsetDateTimeField(UnsupportedDateTimeField.getInstance( DateTimeFieldType.secondOfMinute(), UnsupportedDurationField.getInstance(DurationFieldType.seconds())), 0); fail(); } catch (IllegalArgumentException ex) {} } public void test_constructor2() { OffsetDateTimeField field = new OffsetDateTimeField( ISOChronology.getInstance().secondOfMinute(), DateTimeFieldType.secondOfDay(), 3 ); assertEquals(DateTimeFieldType.secondOfDay(), field.getType()); assertEquals(3, field.getOffset()); try { field = new OffsetDateTimeField(null, DateTimeFieldType.secondOfDay(), 3); fail(); } catch (IllegalArgumentException ex) {} try { field = new OffsetDateTimeField(ISOChronology.getInstance().secondOfMinute(), null, 3); fail(); } catch (IllegalArgumentException ex) {} try { field = new OffsetDateTimeField(ISOChronology.getInstance().secondOfMinute(), DateTimeFieldType.secondOfDay(), 0); fail(); } catch (IllegalArgumentException ex) {} } public void test_getType() { OffsetDateTimeField field = new OffsetDateTimeField( ISOChronology.getInstance().secondOfMinute(), 3 ); assertEquals(DateTimeFieldType.secondOfMinute(), field.getType()); } public void test_getName() { OffsetDateTimeField field = new OffsetDateTimeField( ISOChronology.getInstance().secondOfMinute(), 3 ); assertEquals("secondOfMinute", field.getName()); } public void test_toString() { OffsetDateTimeField field = new OffsetDateTimeField( ISOChronology.getInstance().secondOfMinute(), 3 ); assertEquals("DateTimeField[secondOfMinute]", field.toString()); } public void test_isSupported() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(true, field.isSupported()); } public void test_isLenient() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(false, field.isLenient()); } public void test_getOffset() { OffsetDateTimeField field = new OffsetDateTimeField( ISOChronology.getInstance().secondOfMinute(), 5 ); assertEquals(5, field.getOffset()); } public void test_get() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(0 + 3, field.get(0)); assertEquals(6 + 3, field.get(6000)); } //----------------------------------------------------------------------- public void test_getAsText_long_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("32", field.getAsText(1000L * 29, Locale.ENGLISH)); assertEquals("32", field.getAsText(1000L * 29, null)); } public void test_getAsText_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("32", field.getAsText(1000L * 29)); } public void test_getAsText_RP_int_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsText_RP_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsText_int_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("80", field.getAsText(80, Locale.ENGLISH)); assertEquals("80", field.getAsText(80, null)); } //----------------------------------------------------------------------- public void test_getAsShortText_long_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("32", field.getAsShortText(1000L * 29, Locale.ENGLISH)); assertEquals("32", field.getAsShortText(1000L * 29, null)); } public void test_getAsShortText_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("32", field.getAsShortText(1000L * 29)); } public void test_getAsShortText_RP_int_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsShortText_RP_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsShortText_int_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals("80", field.getAsShortText(80, Locale.ENGLISH)); assertEquals("80", field.getAsShortText(80, null)); } //----------------------------------------------------------------------- public void test_add_long_int() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(1001, field.add(1L, 1)); } public void test_add_long_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(1001, field.add(1L, 1L)); } public void test_add_RP_int_intarray_int() { int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; OffsetDateTimeField field = new MockStandardDateTimeField(); int[] result = field.add(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 31, 40}; result = field.add(new TimeOfDay(), 2, values, 1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 62, 40}; result = field.add(new TimeOfDay(), 2, values, 32); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 21, 3, 40}; result = field.add(new TimeOfDay(), 2, values, 33); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {23, 59, 30, 40}; try { field.add(new TimeOfDay(), 2, values, 33); fail(); } catch (IllegalArgumentException ex) {} values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.add(new TimeOfDay(), 2, values, -1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 19, 59, 40}; result = field.add(new TimeOfDay(), 2, values, -31); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {0, 0, 30, 40}; try { field.add(new TimeOfDay(), 2, values, -31); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_addWrapField_long_int() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(29 * 1000L, field.addWrapField(1000L * 29, 0)); assertEquals(59 * 1000L, field.addWrapField(1000L * 29, 30)); assertEquals(0L, field.addWrapField(1000L * 29, 31)); } public void test_addWrapField_RP_int_intarray_int() { OffsetDateTimeField field = new MockOffsetDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.addWrapField(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 59, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 3, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 33); assertEquals(true, Arrays.equals(result, expected)); } //----------------------------------------------------------------------- public void test_getDifference_long_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(-21, field.getDifference(20000L, 41000L)); } public void test_getDifferenceAsLong_long_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(-21L, field.getDifferenceAsLong(20000L, 41000L)); } //----------------------------------------------------------------------- public void test_set_long_int() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(3120L, field.set(2120L, 6)); assertEquals(26120L, field.set(120L, 29)); assertEquals(57120L, field.set(2120L, 60)); } public void test_set_RP_int_intarray_int() { OffsetDateTimeField field = new MockOffsetDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, 63); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, 2); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_set_long_String_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(3050L, field.set(50L, "6", null)); assertEquals(26050L, field.set(50L, "29", Locale.ENGLISH)); } public void test_set_long_String() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(3050L, field.set(50L, "6")); assertEquals(26050L, field.set(50L, "29")); } public void test_set_RP_int_intarray_String_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, "30", null); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, "29", Locale.ENGLISH); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "63", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "2", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_convertText() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(0, field.convertText("0", null)); assertEquals(29, field.convertText("29", null)); try { field.convertText("2A", null); fail(); } catch (IllegalArgumentException ex) {} try { field.convertText(null, null); fail(); } catch (IllegalArgumentException ex) {} } //------------------------------------------------------------------------ // public abstract DurationField getDurationField(); // // public abstract DurationField getRangeDurationField(); public void test_isLeap_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(false, field.isLeap(0L)); } public void test_getLeapAmount_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(0, field.getLeapAmount(0L)); } public void test_getLeapDurationField() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(null, field.getLeapDurationField()); } //----------------------------------------------------------------------- public void test_getMinimumValue() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(3, field.getMinimumValue()); } public void test_getMinimumValue_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(3, field.getMinimumValue(0L)); } public void test_getMinimumValue_RP() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(3, field.getMinimumValue(new TimeOfDay())); } public void test_getMinimumValue_RP_intarray() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(3, field.getMinimumValue(new TimeOfDay(), new int[4])); } public void test_getMaximumValue() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(62, field.getMaximumValue()); } public void test_getMaximumValue_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(62, field.getMaximumValue(0L)); } public void test_getMaximumValue_RP() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(62, field.getMaximumValue(new TimeOfDay())); } public void test_getMaximumValue_RP_intarray() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(62, field.getMaximumValue(new TimeOfDay(), new int[4])); } //----------------------------------------------------------------------- public void test_getMaximumTextLength_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(2, field.getMaximumTextLength(Locale.ENGLISH)); } public void test_getMaximumShortTextLength_Locale() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(2, field.getMaximumShortTextLength(Locale.ENGLISH)); } //------------------------------------------------------------------------ public void test_roundFloor_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(-2000L, field.roundFloor(-1001L)); assertEquals(-1000L, field.roundFloor(-1000L)); assertEquals(-1000L, field.roundFloor(-999L)); assertEquals(-1000L, field.roundFloor(-1L)); assertEquals(0L, field.roundFloor(0L)); assertEquals(0L, field.roundFloor(1L)); assertEquals(0L, field.roundFloor(499L)); assertEquals(0L, field.roundFloor(500L)); assertEquals(0L, field.roundFloor(501L)); assertEquals(1000L, field.roundFloor(1000L)); } public void test_roundCeiling_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(-1000L, field.roundCeiling(-1001L)); assertEquals(-1000L, field.roundCeiling(-1000L)); assertEquals(0L, field.roundCeiling(-999L)); assertEquals(0L, field.roundCeiling(-1L)); assertEquals(0L, field.roundCeiling(0L)); assertEquals(1000L, field.roundCeiling(1L)); assertEquals(1000L, field.roundCeiling(499L)); assertEquals(1000L, field.roundCeiling(500L)); assertEquals(1000L, field.roundCeiling(501L)); assertEquals(1000L, field.roundCeiling(1000L)); } public void test_roundHalfFloor_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(0L, field.roundHalfFloor(0L)); assertEquals(0L, field.roundHalfFloor(499L)); assertEquals(0L, field.roundHalfFloor(500L)); assertEquals(1000L, field.roundHalfFloor(501L)); assertEquals(1000L, field.roundHalfFloor(1000L)); } public void test_roundHalfCeiling_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(0L, field.roundHalfCeiling(0L)); assertEquals(0L, field.roundHalfCeiling(499L)); assertEquals(1000L, field.roundHalfCeiling(500L)); assertEquals(1000L, field.roundHalfCeiling(501L)); assertEquals(1000L, field.roundHalfCeiling(1000L)); } public void test_roundHalfEven_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(0L, field.roundHalfEven(0L)); assertEquals(0L, field.roundHalfEven(499L)); assertEquals(0L, field.roundHalfEven(500L)); assertEquals(1000L, field.roundHalfEven(501L)); assertEquals(1000L, field.roundHalfEven(1000L)); assertEquals(1000L, field.roundHalfEven(1499L)); assertEquals(2000L, field.roundHalfEven(1500L)); assertEquals(2000L, field.roundHalfEven(1501L)); } public void test_remainder_long() { OffsetDateTimeField field = new MockOffsetDateTimeField(); assertEquals(0L, field.remainder(0L)); assertEquals(499L, field.remainder(499L)); assertEquals(500L, field.remainder(500L)); assertEquals(501L, field.remainder(501L)); assertEquals(0L, field.remainder(1000L)); } //----------------------------------------------------------------------- static class MockOffsetDateTimeField extends OffsetDateTimeField { protected MockOffsetDateTimeField() { super(ISOChronology.getInstance().secondOfMinute(), 3); } } static class MockStandardDateTimeField extends MockOffsetDateTimeField { protected MockStandardDateTimeField() { super(); } public DurationField getDurationField() { return ISOChronology.getInstanceUTC().seconds(); } public DurationField getRangeDurationField() { return ISOChronology.getInstanceUTC().minutes(); } } } joda-time-2.3/src/test/java/org/joda/time/field/TestAll.java0000644000175000017500000000346311564251364023223 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all tests in this package. * * @version $Id$ * * @author Stephen Colebourne */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static void main(String args[]) { String[] testCaseName = { TestAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestFieldUtils.suite()); suite.addTest(TestBaseDateTimeField.suite()); suite.addTest(TestOffsetDateTimeField.suite()); suite.addTest(TestPreciseDurationDateTimeField.suite()); suite.addTest(TestPreciseDateTimeField.suite()); suite.addTest(TestMillisDurationField.suite()); suite.addTest(TestPreciseDurationField.suite()); suite.addTest(TestScaledDurationField.suite()); suite.addTest(TestUnsupportedDateTimeField.suite()); return suite; } } joda-time-2.3/src/test/java/org/joda/time/field/TestPreciseDateTimeField.java0000644000175000017500000006305311564251364026467 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.TimeOfDay; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for PreciseDateTimeField. * * @author Stephen Colebourne */ public class TestPreciseDateTimeField extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPreciseDateTimeField.class); } public TestPreciseDateTimeField(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_constructor() { BaseDateTimeField field = new PreciseDateTimeField( DateTimeFieldType.secondOfMinute(), ISOChronology.getInstanceUTC().millis(), ISOChronology.getInstanceUTC().hours() ); assertEquals(DateTimeFieldType.secondOfMinute(), field.getType()); try { field = new PreciseDateTimeField(null, null, null); fail(); } catch (IllegalArgumentException ex) {} try { field = new PreciseDateTimeField( DateTimeFieldType.minuteOfHour(), new MockImpreciseDurationField(DurationFieldType.minutes()), ISOChronology.getInstanceUTC().hours()); fail(); } catch (IllegalArgumentException ex) {} try { field = new PreciseDateTimeField( DateTimeFieldType.minuteOfHour(), ISOChronology.getInstanceUTC().hours(), new MockImpreciseDurationField(DurationFieldType.minutes())); fail(); } catch (IllegalArgumentException ex) {} try { field = new PreciseDateTimeField( DateTimeFieldType.minuteOfHour(), ISOChronology.getInstanceUTC().hours(), ISOChronology.getInstanceUTC().hours()); fail(); } catch (IllegalArgumentException ex) {} try { field = new PreciseDateTimeField( DateTimeFieldType.minuteOfHour(), new MockZeroDurationField(DurationFieldType.minutes()), ISOChronology.getInstanceUTC().hours()); fail(); } catch (IllegalArgumentException ex) {} } public void test_getType() { BaseDateTimeField field = new PreciseDateTimeField( DateTimeFieldType.secondOfDay(), ISOChronology.getInstanceUTC().millis(), ISOChronology.getInstanceUTC().hours() ); assertEquals(DateTimeFieldType.secondOfDay(), field.getType()); } public void test_getName() { BaseDateTimeField field = new PreciseDateTimeField( DateTimeFieldType.secondOfDay(), ISOChronology.getInstanceUTC().millis(), ISOChronology.getInstanceUTC().hours() ); assertEquals("secondOfDay", field.getName()); } public void test_toString() { BaseDateTimeField field = new PreciseDateTimeField( DateTimeFieldType.secondOfDay(), ISOChronology.getInstanceUTC().millis(), ISOChronology.getInstanceUTC().hours() ); assertEquals("DateTimeField[secondOfDay]", field.toString()); } public void test_isSupported() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(true, field.isSupported()); } public void test_getRange() { PreciseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(60, field.getRange()); } public void test_get() { PreciseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.get(0)); assertEquals(1, field.get(60)); assertEquals(2, field.get(123)); } //----------------------------------------------------------------------- public void test_getAsText_long_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("29", field.getAsText(60L * 29, Locale.ENGLISH)); assertEquals("29", field.getAsText(60L * 29, null)); } public void test_getAsText_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("29", field.getAsText(60L * 29)); } public void test_getAsText_RP_int_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsText_RP_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsText_int_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("80", field.getAsText(80, Locale.ENGLISH)); assertEquals("80", field.getAsText(80, null)); } //----------------------------------------------------------------------- public void test_getAsShortText_long_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("29", field.getAsShortText(60L * 29, Locale.ENGLISH)); assertEquals("29", field.getAsShortText(60L * 29, null)); } public void test_getAsShortText_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("29", field.getAsShortText(60L * 29)); } public void test_getAsShortText_RP_int_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsShortText_RP_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsShortText_int_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals("80", field.getAsShortText(80, Locale.ENGLISH)); assertEquals("80", field.getAsShortText(80, null)); } //----------------------------------------------------------------------- public void test_add_long_int() { MockCountingDurationField.add_int = 0; BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(61, field.add(1L, 1)); assertEquals(1, MockCountingDurationField.add_int); } public void test_add_long_long() { MockCountingDurationField.add_long = 0; BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(61, field.add(1L, 1L)); assertEquals(1, MockCountingDurationField.add_long); } public void test_add_RP_int_intarray_int() { int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; BaseDateTimeField field = new MockStandardDateTimeField(); int[] result = field.add(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 31, 40}; result = field.add(new TimeOfDay(), 2, values, 1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 21, 0, 40}; result = field.add(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {23, 59, 30, 40}; try { field.add(new TimeOfDay(), 2, values, 30); fail(); } catch (IllegalArgumentException ex) {} values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.add(new TimeOfDay(), 2, values, -1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 19, 59, 40}; result = field.add(new TimeOfDay(), 2, values, -31); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {0, 0, 30, 40}; try { field.add(new TimeOfDay(), 2, values, -31); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_addWrapField_long_int() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(29 * 60L, field.addWrapField(60L * 29, 0)); assertEquals(59 * 60L, field.addWrapField(60L * 29, 30)); assertEquals(0 * 60L, field.addWrapField(60L * 29, 31)); } public void test_addWrapField_RP_int_intarray_int() { BaseDateTimeField field = new MockPreciseDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.addWrapField(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 59, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 0, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 1, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 31); assertEquals(true, Arrays.equals(result, expected)); } //----------------------------------------------------------------------- public void test_getDifference_long_long() { MockCountingDurationField.difference_long = 0; BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(30, field.getDifference(0L, 0L)); assertEquals(1, MockCountingDurationField.difference_long); } public void test_getDifferenceAsLong_long_long() { MockCountingDurationField.difference_long = 0; BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(30, field.getDifferenceAsLong(0L, 0L)); assertEquals(1, MockCountingDurationField.difference_long); } //----------------------------------------------------------------------- public void test_set_long_int() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.set(120L, 0)); assertEquals(29 * 60, field.set(120L, 29)); } public void test_set_RP_int_intarray_int() { BaseDateTimeField field = new MockPreciseDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, 60); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, -1); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_set_long_String_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.set(0L, "0", null)); assertEquals(29 * 60, field.set(0L, "29", Locale.ENGLISH)); } public void test_set_long_String() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.set(0L, "0")); assertEquals(29 * 60, field.set(0L, "29")); } public void test_set_RP_int_intarray_String_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, "30", null); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, "29", Locale.ENGLISH); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "60", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "-1", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_convertText() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.convertText("0", null)); assertEquals(29, field.convertText("29", null)); try { field.convertText("2A", null); fail(); } catch (IllegalArgumentException ex) {} try { field.convertText(null, null); fail(); } catch (IllegalArgumentException ex) {} } //------------------------------------------------------------------------ // public abstract DurationField getDurationField(); // // public abstract DurationField getRangeDurationField(); public void test_isLeap_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(false, field.isLeap(0L)); } public void test_getLeapAmount_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.getLeapAmount(0L)); } public void test_getLeapDurationField() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(null, field.getLeapDurationField()); } //----------------------------------------------------------------------- public void test_getMinimumValue() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.getMinimumValue()); } public void test_getMinimumValue_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.getMinimumValue(0L)); } public void test_getMinimumValue_RP() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.getMinimumValue(new TimeOfDay())); } public void test_getMinimumValue_RP_intarray() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0, field.getMinimumValue(new TimeOfDay(), new int[4])); } public void test_getMaximumValue() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(59, field.getMaximumValue()); } public void test_getMaximumValue_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(59, field.getMaximumValue(0L)); } public void test_getMaximumValue_RP() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(59, field.getMaximumValue(new TimeOfDay())); } public void test_getMaximumValue_RP_intarray() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(59, field.getMaximumValue(new TimeOfDay(), new int[4])); } //----------------------------------------------------------------------- public void test_getMaximumTextLength_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(2, field.getMaximumTextLength(Locale.ENGLISH)); } public void test_getMaximumShortTextLength_Locale() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(2, field.getMaximumShortTextLength(Locale.ENGLISH)); } //------------------------------------------------------------------------ public void test_roundFloor_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(-120L, field.roundFloor(-61L)); assertEquals(-60L, field.roundFloor(-60L)); assertEquals(-60L, field.roundFloor(-59L)); assertEquals(-60L, field.roundFloor(-1L)); assertEquals(0L, field.roundFloor(0L)); assertEquals(0L, field.roundFloor(1L)); assertEquals(0L, field.roundFloor(29L)); assertEquals(0L, field.roundFloor(30L)); assertEquals(0L, field.roundFloor(31L)); assertEquals(60L, field.roundFloor(60L)); } public void test_roundCeiling_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(-60L, field.roundCeiling(-61L)); assertEquals(-60L, field.roundCeiling(-60L)); assertEquals(0L, field.roundCeiling(-59L)); assertEquals(0L, field.roundCeiling(-1L)); assertEquals(0L, field.roundCeiling(0L)); assertEquals(60L, field.roundCeiling(1L)); assertEquals(60L, field.roundCeiling(29L)); assertEquals(60L, field.roundCeiling(30L)); assertEquals(60L, field.roundCeiling(31L)); assertEquals(60L, field.roundCeiling(60L)); } public void test_roundHalfFloor_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0L, field.roundHalfFloor(0L)); assertEquals(0L, field.roundHalfFloor(29L)); assertEquals(0L, field.roundHalfFloor(30L)); assertEquals(60L, field.roundHalfFloor(31L)); assertEquals(60L, field.roundHalfFloor(60L)); } public void test_roundHalfCeiling_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0L, field.roundHalfCeiling(0L)); assertEquals(0L, field.roundHalfCeiling(29L)); assertEquals(60L, field.roundHalfCeiling(30L)); assertEquals(60L, field.roundHalfCeiling(31L)); assertEquals(60L, field.roundHalfCeiling(60L)); } public void test_roundHalfEven_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0L, field.roundHalfEven(0L)); assertEquals(0L, field.roundHalfEven(29L)); assertEquals(0L, field.roundHalfEven(30L)); assertEquals(60L, field.roundHalfEven(31L)); assertEquals(60L, field.roundHalfEven(60L)); assertEquals(60L, field.roundHalfEven(89L)); assertEquals(120L, field.roundHalfEven(90L)); assertEquals(120L, field.roundHalfEven(91L)); } public void test_remainder_long() { BaseDateTimeField field = new MockPreciseDateTimeField(); assertEquals(0L, field.remainder(0L)); assertEquals(29L, field.remainder(29L)); assertEquals(30L, field.remainder(30L)); assertEquals(31L, field.remainder(31L)); assertEquals(0L, field.remainder(60L)); } //----------------------------------------------------------------------- static class MockPreciseDateTimeField extends PreciseDateTimeField { protected MockPreciseDateTimeField() { super(DateTimeFieldType.secondOfMinute(), new MockCountingDurationField(DurationFieldType.seconds(), 60), new MockCountingDurationField(DurationFieldType.minutes(), 60 * 60)); } protected MockPreciseDateTimeField( DateTimeFieldType type, DurationField dur, DurationField range) { super(type, dur, range); } } static class MockStandardDateTimeField extends MockPreciseDateTimeField { protected MockStandardDateTimeField() { super(); } public DurationField getDurationField() { return ISOChronology.getInstanceUTC().seconds(); } public DurationField getRangeDurationField() { return ISOChronology.getInstanceUTC().minutes(); } } //----------------------------------------------------------------------- static class MockCountingDurationField extends BaseDurationField { static int add_int = 0; static int add_long = 0; static int difference_long = 0; int unit; protected MockCountingDurationField(DurationFieldType type, int unit) { super(type); this.unit = unit; } public boolean isPrecise() { return true; } public long getUnitMillis() { return unit; } public long getValueAsLong(long duration, long instant) { return 0; } public long getMillis(int value, long instant) { return 0; } public long getMillis(long value, long instant) { return 0; } public long add(long instant, int value) { add_int++; return instant + (value * 60L); } public long add(long instant, long value) { add_long++; return instant + (value * 60L); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { difference_long++; return 30; } } //----------------------------------------------------------------------- static class MockZeroDurationField extends BaseDurationField { protected MockZeroDurationField(DurationFieldType type) { super(type); } public boolean isPrecise() { return true; } public long getUnitMillis() { return 0; // this is zero } public long getValueAsLong(long duration, long instant) { return 0; } public long getMillis(int value, long instant) { return 0; } public long getMillis(long value, long instant) { return 0; } public long add(long instant, int value) { return 0; } public long add(long instant, long value) { return 0; } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return 0; } } //----------------------------------------------------------------------- static class MockImpreciseDurationField extends BaseDurationField { protected MockImpreciseDurationField(DurationFieldType type) { super(type); } public boolean isPrecise() { return false; // this is false } public long getUnitMillis() { return 0; } public long getValueAsLong(long duration, long instant) { return 0; } public long getMillis(int value, long instant) { return 0; } public long getMillis(long value, long instant) { return 0; } public long add(long instant, int value) { return 0; } public long add(long instant, long value) { return 0; } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return 0; } } } joda-time-2.3/src/test/java/org/joda/time/field/TestMillisDurationField.java0000644000175000017500000002152411564251364026414 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for PeriodFormatterBuilder. * * @author Stephen Colebourne */ public class TestMillisDurationField extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMillisDurationField.class); } public TestMillisDurationField(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_getType() { assertEquals(DurationFieldType.millis(), MillisDurationField.INSTANCE.getType()); } public void test_getName() { assertEquals("millis", MillisDurationField.INSTANCE.getName()); } public void test_isSupported() { assertEquals(true, MillisDurationField.INSTANCE.isSupported()); } public void test_isPrecise() { assertEquals(true, MillisDurationField.INSTANCE.isPrecise()); } public void test_getUnitMillis() { assertEquals(1, MillisDurationField.INSTANCE.getUnitMillis()); } public void test_toString() { assertEquals("DurationField[millis]", MillisDurationField.INSTANCE.toString()); } //----------------------------------------------------------------------- public void test_getValue_long() { assertEquals(0, MillisDurationField.INSTANCE.getValue(0L)); assertEquals(1234, MillisDurationField.INSTANCE.getValue(1234L)); assertEquals(-1234, MillisDurationField.INSTANCE.getValue(-1234L)); try { MillisDurationField.INSTANCE.getValue(((long) (Integer.MAX_VALUE)) + 1L); fail(); } catch (ArithmeticException ex) {} } public void test_getValueAsLong_long() { assertEquals(0L, MillisDurationField.INSTANCE.getValueAsLong(0L)); assertEquals(1234L, MillisDurationField.INSTANCE.getValueAsLong(1234L)); assertEquals(-1234L, MillisDurationField.INSTANCE.getValueAsLong(-1234L)); assertEquals(((long) (Integer.MAX_VALUE)) + 1L, MillisDurationField.INSTANCE.getValueAsLong(((long) (Integer.MAX_VALUE)) + 1L)); } public void test_getValue_long_long() { assertEquals(0, MillisDurationField.INSTANCE.getValue(0L, 567L)); assertEquals(1234, MillisDurationField.INSTANCE.getValue(1234L, 567L)); assertEquals(-1234, MillisDurationField.INSTANCE.getValue(-1234L, 567L)); try { MillisDurationField.INSTANCE.getValue(((long) (Integer.MAX_VALUE)) + 1L, 567L); fail(); } catch (ArithmeticException ex) {} } public void test_getValueAsLong_long_long() { assertEquals(0L, MillisDurationField.INSTANCE.getValueAsLong(0L, 567L)); assertEquals(1234L, MillisDurationField.INSTANCE.getValueAsLong(1234L, 567L)); assertEquals(-1234L, MillisDurationField.INSTANCE.getValueAsLong(-1234L, 567L)); assertEquals(((long) (Integer.MAX_VALUE)) + 1L, MillisDurationField.INSTANCE.getValueAsLong(((long) (Integer.MAX_VALUE)) + 1L, 567L)); } //----------------------------------------------------------------------- public void test_getMillis_int() { assertEquals(0, MillisDurationField.INSTANCE.getMillis(0)); assertEquals(1234, MillisDurationField.INSTANCE.getMillis(1234)); assertEquals(-1234, MillisDurationField.INSTANCE.getMillis(-1234)); } public void test_getMillis_long() { assertEquals(0L, MillisDurationField.INSTANCE.getMillis(0L)); assertEquals(1234L, MillisDurationField.INSTANCE.getMillis(1234L)); assertEquals(-1234L, MillisDurationField.INSTANCE.getMillis(-1234L)); } public void test_getMillis_int_long() { assertEquals(0, MillisDurationField.INSTANCE.getMillis(0, 567L)); assertEquals(1234, MillisDurationField.INSTANCE.getMillis(1234, 567L)); assertEquals(-1234, MillisDurationField.INSTANCE.getMillis(-1234, 567L)); } public void test_getMillis_long_long() { assertEquals(0L, MillisDurationField.INSTANCE.getMillis(0L, 567L)); assertEquals(1234L, MillisDurationField.INSTANCE.getMillis(1234L, 567L)); assertEquals(-1234L, MillisDurationField.INSTANCE.getMillis(-1234L, 567L)); } //----------------------------------------------------------------------- public void test_add_long_int() { assertEquals(567L, MillisDurationField.INSTANCE.add(567L, 0)); assertEquals(567L + 1234L, MillisDurationField.INSTANCE.add(567L, 1234)); assertEquals(567L - 1234L, MillisDurationField.INSTANCE.add(567L, -1234)); try { MillisDurationField.INSTANCE.add(Long.MAX_VALUE, 1); fail(); } catch (ArithmeticException ex) {} } public void test_add_long_long() { assertEquals(567L, MillisDurationField.INSTANCE.add(567L, 0L)); assertEquals(567L + 1234L, MillisDurationField.INSTANCE.add(567L, 1234L)); assertEquals(567L - 1234L, MillisDurationField.INSTANCE.add(567L, -1234L)); try { MillisDurationField.INSTANCE.add(Long.MAX_VALUE, 1L); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_getDifference_long_int() { assertEquals(567, MillisDurationField.INSTANCE.getDifference(567L, 0L)); assertEquals(567 - 1234, MillisDurationField.INSTANCE.getDifference(567L, 1234L)); assertEquals(567 + 1234, MillisDurationField.INSTANCE.getDifference(567L, -1234L)); try { MillisDurationField.INSTANCE.getDifference(Long.MAX_VALUE, 1L); fail(); } catch (ArithmeticException ex) {} } public void test_getDifferenceAsLong_long_long() { assertEquals(567L, MillisDurationField.INSTANCE.getDifferenceAsLong(567L, 0L)); assertEquals(567L - 1234L, MillisDurationField.INSTANCE.getDifferenceAsLong(567L, 1234L)); assertEquals(567L + 1234L, MillisDurationField.INSTANCE.getDifferenceAsLong(567L, -1234L)); try { MillisDurationField.INSTANCE.getDifferenceAsLong(Long.MAX_VALUE, -1L); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_compareTo() { assertEquals(0, MillisDurationField.INSTANCE.compareTo(MillisDurationField.INSTANCE)); assertEquals(-1, MillisDurationField.INSTANCE.compareTo(ISOChronology.getInstance().seconds())); DurationField dummy = new PreciseDurationField(DurationFieldType.seconds(), 0); assertEquals(1, MillisDurationField.INSTANCE.compareTo(dummy)); // try { // MillisDurationField.INSTANCE.compareTo(""); // fail(); // } catch (ClassCastException ex) {} try { MillisDurationField.INSTANCE.compareTo(null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { DurationField test = MillisDurationField.INSTANCE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DurationField result = (DurationField) ois.readObject(); ois.close(); assertSame(test, result); } } joda-time-2.3/src/test/java/org/joda/time/field/TestPreciseDurationDateTimeField.java0000644000175000017500000006404311564251364030175 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.TimeOfDay; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for PreciseDurationDateTimeField. * * @author Stephen Colebourne */ public class TestPreciseDurationDateTimeField extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPreciseDurationDateTimeField.class); } public TestPreciseDurationDateTimeField(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_constructor() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(DateTimeFieldType.secondOfMinute(), field.getType()); try { field = new MockPreciseDurationDateTimeField(null, null); fail(); } catch (IllegalArgumentException ex) {} try { field = new MockPreciseDurationDateTimeField( DateTimeFieldType.minuteOfHour(), new MockImpreciseDurationField(DurationFieldType.minutes())); fail(); } catch (IllegalArgumentException ex) {} try { field = new MockPreciseDurationDateTimeField( DateTimeFieldType.minuteOfHour(), new MockZeroDurationField(DurationFieldType.minutes())); fail(); } catch (IllegalArgumentException ex) {} } public void test_getType() { BaseDateTimeField field = new MockPreciseDurationDateTimeField( DateTimeFieldType.secondOfDay(), new MockCountingDurationField(DurationFieldType.minutes())); assertEquals(DateTimeFieldType.secondOfDay(), field.getType()); } public void test_getName() { BaseDateTimeField field = new MockPreciseDurationDateTimeField( DateTimeFieldType.secondOfDay(), new MockCountingDurationField(DurationFieldType.minutes())); assertEquals("secondOfDay", field.getName()); } public void test_toString() { BaseDateTimeField field = new MockPreciseDurationDateTimeField( DateTimeFieldType.secondOfDay(), new MockCountingDurationField(DurationFieldType.minutes())); assertEquals("DateTimeField[secondOfDay]", field.toString()); } public void test_isSupported() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(true, field.isSupported()); } public void test_isLenient() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(false, field.isLenient()); } public void test_get() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.get(0)); assertEquals(1, field.get(60)); assertEquals(2, field.get(123)); } //----------------------------------------------------------------------- public void test_getAsText_long_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("29", field.getAsText(60L * 29, Locale.ENGLISH)); assertEquals("29", field.getAsText(60L * 29, null)); } public void test_getAsText_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("29", field.getAsText(60L * 29)); } public void test_getAsText_RP_int_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsText_RP_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsText_int_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("80", field.getAsText(80, Locale.ENGLISH)); assertEquals("80", field.getAsText(80, null)); } //----------------------------------------------------------------------- public void test_getAsShortText_long_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("29", field.getAsShortText(60L * 29, Locale.ENGLISH)); assertEquals("29", field.getAsShortText(60L * 29, null)); } public void test_getAsShortText_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("29", field.getAsShortText(60L * 29)); } public void test_getAsShortText_RP_int_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsShortText_RP_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsShortText_int_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals("80", field.getAsShortText(80, Locale.ENGLISH)); assertEquals("80", field.getAsShortText(80, null)); } //----------------------------------------------------------------------- public void test_add_long_int() { MockCountingDurationField.add_int = 0; BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(61, field.add(1L, 1)); assertEquals(1, MockCountingDurationField.add_int); } public void test_add_long_long() { MockCountingDurationField.add_long = 0; BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(61, field.add(1L, 1L)); assertEquals(1, MockCountingDurationField.add_long); } public void test_add_RP_int_intarray_int() { int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; BaseDateTimeField field = new MockStandardBaseDateTimeField(); int[] result = field.add(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 31, 40}; result = field.add(new TimeOfDay(), 2, values, 1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 21, 0, 40}; result = field.add(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {23, 59, 30, 40}; try { field.add(new TimeOfDay(), 2, values, 30); fail(); } catch (IllegalArgumentException ex) {} values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.add(new TimeOfDay(), 2, values, -1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 19, 59, 40}; result = field.add(new TimeOfDay(), 2, values, -31); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {0, 0, 30, 40}; try { field.add(new TimeOfDay(), 2, values, -31); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_addWrapField_long_int() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(29 * 60L, field.addWrapField(60L * 29, 0)); assertEquals(59 * 60L, field.addWrapField(60L * 29, 30)); assertEquals(0 * 60L, field.addWrapField(60L * 29, 31)); } public void test_addWrapField_RP_int_intarray_int() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.addWrapField(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 59, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 0, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 1, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 31); assertEquals(true, Arrays.equals(result, expected)); } //----------------------------------------------------------------------- public void test_getDifference_long_long() { MockCountingDurationField.difference_long = 0; BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(30, field.getDifference(0L, 0L)); assertEquals(1, MockCountingDurationField.difference_long); } public void test_getDifferenceAsLong_long_long() { MockCountingDurationField.difference_long = 0; BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(30, field.getDifferenceAsLong(0L, 0L)); assertEquals(1, MockCountingDurationField.difference_long); } //----------------------------------------------------------------------- public void test_set_long_int() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.set(120L, 0)); assertEquals(29 * 60, field.set(120L, 29)); } public void test_set_RP_int_intarray_int() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, 60); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, -1); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_set_long_String_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.set(0L, "0", null)); assertEquals(29 * 60, field.set(0L, "29", Locale.ENGLISH)); } public void test_set_long_String() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.set(0L, "0")); assertEquals(29 * 60, field.set(0L, "29")); } public void test_set_RP_int_intarray_String_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, "30", null); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, "29", Locale.ENGLISH); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "60", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "-1", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_convertText() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.convertText("0", null)); assertEquals(29, field.convertText("29", null)); try { field.convertText("2A", null); fail(); } catch (IllegalArgumentException ex) {} try { field.convertText(null, null); fail(); } catch (IllegalArgumentException ex) {} } //------------------------------------------------------------------------ // public abstract DurationField getDurationField(); // // public abstract DurationField getRangeDurationField(); public void test_isLeap_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(false, field.isLeap(0L)); } public void test_getLeapAmount_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.getLeapAmount(0L)); } public void test_getLeapDurationField() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(null, field.getLeapDurationField()); } //----------------------------------------------------------------------- public void test_getMinimumValue() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.getMinimumValue()); } public void test_getMinimumValue_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.getMinimumValue(0L)); } public void test_getMinimumValue_RP() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.getMinimumValue(new TimeOfDay())); } public void test_getMinimumValue_RP_intarray() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.getMinimumValue(new TimeOfDay(), new int[4])); } public void test_getMaximumValue() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(59, field.getMaximumValue()); } public void test_getMaximumValue_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(59, field.getMaximumValue(0L)); } public void test_getMaximumValue_RP() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(59, field.getMaximumValue(new TimeOfDay())); } public void test_getMaximumValue_RP_intarray() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(59, field.getMaximumValue(new TimeOfDay(), new int[4])); } //----------------------------------------------------------------------- public void test_getMaximumTextLength_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(2, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockPreciseDurationDateTimeField() { public int getMaximumValue() { return 5; } }; assertEquals(1, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockPreciseDurationDateTimeField() { public int getMaximumValue() { return 555; } }; assertEquals(3, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockPreciseDurationDateTimeField() { public int getMaximumValue() { return 5555; } }; assertEquals(4, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockPreciseDurationDateTimeField() { public int getMaximumValue() { return -1; } }; assertEquals(2, field.getMaximumTextLength(Locale.ENGLISH)); } public void test_getMaximumShortTextLength_Locale() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(2, field.getMaximumShortTextLength(Locale.ENGLISH)); } //------------------------------------------------------------------------ public void test_roundFloor_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(-120L, field.roundFloor(-61L)); assertEquals(-60L, field.roundFloor(-60L)); assertEquals(-60L, field.roundFloor(-59L)); assertEquals(-60L, field.roundFloor(-1L)); assertEquals(0L, field.roundFloor(0L)); assertEquals(0L, field.roundFloor(1L)); assertEquals(0L, field.roundFloor(29L)); assertEquals(0L, field.roundFloor(30L)); assertEquals(0L, field.roundFloor(31L)); assertEquals(60L, field.roundFloor(60L)); } public void test_roundCeiling_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(-60L, field.roundCeiling(-61L)); assertEquals(-60L, field.roundCeiling(-60L)); assertEquals(0L, field.roundCeiling(-59L)); assertEquals(0L, field.roundCeiling(-1L)); assertEquals(0L, field.roundCeiling(0L)); assertEquals(60L, field.roundCeiling(1L)); assertEquals(60L, field.roundCeiling(29L)); assertEquals(60L, field.roundCeiling(30L)); assertEquals(60L, field.roundCeiling(31L)); assertEquals(60L, field.roundCeiling(60L)); } public void test_roundHalfFloor_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0L, field.roundHalfFloor(0L)); assertEquals(0L, field.roundHalfFloor(29L)); assertEquals(0L, field.roundHalfFloor(30L)); assertEquals(60L, field.roundHalfFloor(31L)); assertEquals(60L, field.roundHalfFloor(60L)); } public void test_roundHalfCeiling_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0L, field.roundHalfCeiling(0L)); assertEquals(0L, field.roundHalfCeiling(29L)); assertEquals(60L, field.roundHalfCeiling(30L)); assertEquals(60L, field.roundHalfCeiling(31L)); assertEquals(60L, field.roundHalfCeiling(60L)); } public void test_roundHalfEven_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0L, field.roundHalfEven(0L)); assertEquals(0L, field.roundHalfEven(29L)); assertEquals(0L, field.roundHalfEven(30L)); assertEquals(60L, field.roundHalfEven(31L)); assertEquals(60L, field.roundHalfEven(60L)); assertEquals(60L, field.roundHalfEven(89L)); assertEquals(120L, field.roundHalfEven(90L)); assertEquals(120L, field.roundHalfEven(91L)); } public void test_remainder_long() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0L, field.remainder(0L)); assertEquals(29L, field.remainder(29L)); assertEquals(30L, field.remainder(30L)); assertEquals(31L, field.remainder(31L)); assertEquals(0L, field.remainder(60L)); } //----------------------------------------------------------------------- static class MockPreciseDurationDateTimeField extends PreciseDurationDateTimeField { protected MockPreciseDurationDateTimeField() { super(DateTimeFieldType.secondOfMinute(), new MockCountingDurationField(DurationFieldType.seconds())); } protected MockPreciseDurationDateTimeField(DateTimeFieldType type, DurationField dur) { super(type, dur); } public int get(long instant) { return (int) (instant / 60L); } public DurationField getRangeDurationField() { return new MockCountingDurationField(DurationFieldType.minutes()); } public int getMaximumValue() { return 59; } } static class MockStandardBaseDateTimeField extends MockPreciseDurationDateTimeField { protected MockStandardBaseDateTimeField() { super(); } public DurationField getDurationField() { return ISOChronology.getInstanceUTC().seconds(); } public DurationField getRangeDurationField() { return ISOChronology.getInstanceUTC().minutes(); } } //----------------------------------------------------------------------- static class MockCountingDurationField extends BaseDurationField { static int add_int = 0; static int add_long = 0; static int difference_long = 0; protected MockCountingDurationField(DurationFieldType type) { super(type); } public boolean isPrecise() { return true; } public long getUnitMillis() { return 60; } public long getValueAsLong(long duration, long instant) { return 0; } public long getMillis(int value, long instant) { return 0; } public long getMillis(long value, long instant) { return 0; } public long add(long instant, int value) { add_int++; return instant + (value * 60L); } public long add(long instant, long value) { add_long++; return instant + (value * 60L); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { difference_long++; return 30; } } //----------------------------------------------------------------------- static class MockZeroDurationField extends BaseDurationField { protected MockZeroDurationField(DurationFieldType type) { super(type); } public boolean isPrecise() { return true; } public long getUnitMillis() { return 0; // this is zero } public long getValueAsLong(long duration, long instant) { return 0; } public long getMillis(int value, long instant) { return 0; } public long getMillis(long value, long instant) { return 0; } public long add(long instant, int value) { return 0; } public long add(long instant, long value) { return 0; } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return 0; } } //----------------------------------------------------------------------- static class MockImpreciseDurationField extends BaseDurationField { protected MockImpreciseDurationField(DurationFieldType type) { super(type); } public boolean isPrecise() { return false; // this is false } public long getUnitMillis() { return 0; } public long getValueAsLong(long duration, long instant) { return 0; } public long getMillis(int value, long instant) { return 0; } public long getMillis(long value, long instant) { return 0; } public long add(long instant, int value) { return 0; } public long add(long instant, long value) { return 0; } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return 0; } } } joda-time-2.3/src/test/java/org/joda/time/field/TestFieldUtils.java0000644000175000017500000002206511747473160024561 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import junit.framework.TestCase; import junit.framework.TestSuite; /** * * * @author Brian S O'Neill */ public class TestFieldUtils extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestFieldUtils.class); } public TestFieldUtils(String name) { super(name); } public void testSafeAddInt() { assertEquals(0, FieldUtils.safeAdd(0, 0)); assertEquals(5, FieldUtils.safeAdd(2, 3)); assertEquals(-1, FieldUtils.safeAdd(2, -3)); assertEquals(1, FieldUtils.safeAdd(-2, 3)); assertEquals(-5, FieldUtils.safeAdd(-2, -3)); assertEquals(Integer.MAX_VALUE - 1, FieldUtils.safeAdd(Integer.MAX_VALUE, -1)); assertEquals(Integer.MIN_VALUE + 1, FieldUtils.safeAdd(Integer.MIN_VALUE, 1)); assertEquals(-1, FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MAX_VALUE)); assertEquals(-1, FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MIN_VALUE)); try { FieldUtils.safeAdd(Integer.MAX_VALUE, 1); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Integer.MAX_VALUE, 100); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MAX_VALUE); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Integer.MIN_VALUE, -1); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Integer.MIN_VALUE, -100); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MIN_VALUE); fail(); } catch (ArithmeticException e) { } } public void testSafeAddLong() { assertEquals(0L, FieldUtils.safeAdd(0L, 0L)); assertEquals(5L, FieldUtils.safeAdd(2L, 3L)); assertEquals(-1L, FieldUtils.safeAdd(2L, -3L)); assertEquals(1L, FieldUtils.safeAdd(-2L, 3L)); assertEquals(-5L, FieldUtils.safeAdd(-2L, -3L)); assertEquals(Long.MAX_VALUE - 1, FieldUtils.safeAdd(Long.MAX_VALUE, -1L)); assertEquals(Long.MIN_VALUE + 1, FieldUtils.safeAdd(Long.MIN_VALUE, 1L)); assertEquals(-1, FieldUtils.safeAdd(Long.MIN_VALUE, Long.MAX_VALUE)); assertEquals(-1, FieldUtils.safeAdd(Long.MAX_VALUE, Long.MIN_VALUE)); try { FieldUtils.safeAdd(Long.MAX_VALUE, 1L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Long.MAX_VALUE, 100L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Long.MAX_VALUE, Long.MAX_VALUE); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Long.MIN_VALUE, -1L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Long.MIN_VALUE, -100L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeAdd(Long.MIN_VALUE, Long.MIN_VALUE); fail(); } catch (ArithmeticException e) { } } public void testSafeSubtractLong() { assertEquals(0L, FieldUtils.safeSubtract(0L, 0L)); assertEquals(-1L, FieldUtils.safeSubtract(2L, 3L)); assertEquals(5L, FieldUtils.safeSubtract(2L, -3L)); assertEquals(-5L, FieldUtils.safeSubtract(-2L, 3L)); assertEquals(1L, FieldUtils.safeSubtract(-2L, -3L)); assertEquals(Long.MAX_VALUE - 1, FieldUtils.safeSubtract(Long.MAX_VALUE, 1L)); assertEquals(Long.MIN_VALUE + 1, FieldUtils.safeSubtract(Long.MIN_VALUE, -1L)); assertEquals(0, FieldUtils.safeSubtract(Long.MIN_VALUE, Long.MIN_VALUE)); assertEquals(0, FieldUtils.safeSubtract(Long.MAX_VALUE, Long.MAX_VALUE)); try { FieldUtils.safeSubtract(Long.MIN_VALUE, 1L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeSubtract(Long.MIN_VALUE, 100L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeSubtract(Long.MIN_VALUE, Long.MAX_VALUE); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeSubtract(Long.MAX_VALUE, -1L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeSubtract(Long.MAX_VALUE, -100L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeSubtract(Long.MAX_VALUE, Long.MIN_VALUE); fail(); } catch (ArithmeticException e) { } } //----------------------------------------------------------------------- public void testSafeMultiplyLongLong() { assertEquals(0L, FieldUtils.safeMultiply(0L, 0L)); assertEquals(1L, FieldUtils.safeMultiply(1L, 1L)); assertEquals(3L, FieldUtils.safeMultiply(1L, 3L)); assertEquals(3L, FieldUtils.safeMultiply(3L, 1L)); assertEquals(6L, FieldUtils.safeMultiply(2L, 3L)); assertEquals(-6L, FieldUtils.safeMultiply(2L, -3L)); assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3L)); assertEquals(6L, FieldUtils.safeMultiply(-2L, -3L)); assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1L)); assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1L)); assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1L)); try { FieldUtils.safeMultiply(Long.MIN_VALUE, -1L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeMultiply(-1L, Long.MIN_VALUE); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeMultiply(Long.MIN_VALUE, 100L); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeMultiply(Long.MIN_VALUE, Long.MAX_VALUE); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeMultiply(Long.MAX_VALUE, Long.MIN_VALUE); fail(); } catch (ArithmeticException e) { } } //----------------------------------------------------------------------- public void testSafeMultiplyLongInt() { assertEquals(0L, FieldUtils.safeMultiply(0L, 0)); assertEquals(1L, FieldUtils.safeMultiply(1L, 1)); assertEquals(3L, FieldUtils.safeMultiply(1L, 3)); assertEquals(3L, FieldUtils.safeMultiply(3L, 1)); assertEquals(6L, FieldUtils.safeMultiply(2L, 3)); assertEquals(-6L, FieldUtils.safeMultiply(2L, -3)); assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3)); assertEquals(6L, FieldUtils.safeMultiply(-2L, -3)); assertEquals(-1L * Integer.MIN_VALUE, FieldUtils.safeMultiply(-1L, Integer.MIN_VALUE)); assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1)); assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1)); assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1)); try { FieldUtils.safeMultiply(Long.MIN_VALUE, -1); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeMultiply(Long.MIN_VALUE, 100); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeMultiply(Long.MIN_VALUE, Integer.MAX_VALUE); fail(); } catch (ArithmeticException e) { } try { FieldUtils.safeMultiply(Long.MAX_VALUE, Integer.MIN_VALUE); fail(); } catch (ArithmeticException e) { } } } joda-time-2.3/src/test/java/org/joda/time/field/TestPreciseDurationField.java0000644000175000017500000002467411564251364026566 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for PreciseDurationField. * * @author Stephen Colebourne */ public class TestPreciseDurationField extends TestCase { private static final long LONG_INTEGER_MAX = Integer.MAX_VALUE; private static final int INTEGER_MAX = Integer.MAX_VALUE; private static final long LONG_MAX = Long.MAX_VALUE; private PreciseDurationField iField; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPreciseDurationField.class); } public TestPreciseDurationField(String name) { super(name); } protected void setUp() throws Exception { iField = new PreciseDurationField(DurationFieldType.seconds(), 1000); } protected void tearDown() throws Exception { iField = null; } //----------------------------------------------------------------------- public void test_constructor() { try { new PreciseDurationField(null, 10); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_getType() { assertEquals(DurationFieldType.seconds(), iField.getType()); } public void test_getName() { assertEquals("seconds", iField.getName()); } public void test_isSupported() { assertEquals(true, iField.isSupported()); } public void test_isPrecise() { assertEquals(true, iField.isPrecise()); } public void test_getUnitMillis() { assertEquals(1000, iField.getUnitMillis()); } public void test_toString() { assertEquals("DurationField[seconds]", iField.toString()); } //----------------------------------------------------------------------- public void test_getValue_long() { assertEquals(0, iField.getValue(0L)); assertEquals(12345, iField.getValue(12345678L)); assertEquals(-1, iField.getValue(-1234L)); assertEquals(INTEGER_MAX, iField.getValue(LONG_INTEGER_MAX * 1000L + 999L)); try { iField.getValue(LONG_INTEGER_MAX * 1000L + 1000L); fail(); } catch (ArithmeticException ex) {} } public void test_getValueAsLong_long() { assertEquals(0L, iField.getValueAsLong(0L)); assertEquals(12345L, iField.getValueAsLong(12345678L)); assertEquals(-1L, iField.getValueAsLong(-1234L)); assertEquals(LONG_INTEGER_MAX + 1L, iField.getValueAsLong(LONG_INTEGER_MAX * 1000L + 1000L)); } public void test_getValue_long_long() { assertEquals(0, iField.getValue(0L, 567L)); assertEquals(12345, iField.getValue(12345678L, 567L)); assertEquals(-1, iField.getValue(-1234L, 567L)); assertEquals(INTEGER_MAX, iField.getValue(LONG_INTEGER_MAX * 1000L + 999L, 567L)); try { iField.getValue(LONG_INTEGER_MAX * 1000L + 1000L, 567L); fail(); } catch (ArithmeticException ex) {} } public void test_getValueAsLong_long_long() { assertEquals(0L, iField.getValueAsLong(0L, 567L)); assertEquals(12345L, iField.getValueAsLong(12345678L, 567L)); assertEquals(-1L, iField.getValueAsLong(-1234L, 567L)); assertEquals(LONG_INTEGER_MAX + 1L, iField.getValueAsLong(LONG_INTEGER_MAX * 1000L + 1000L, 567L)); } //----------------------------------------------------------------------- public void test_getMillis_int() { assertEquals(0, iField.getMillis(0)); assertEquals(1234000L, iField.getMillis(1234)); assertEquals(-1234000L, iField.getMillis(-1234)); assertEquals(LONG_INTEGER_MAX * 1000L, iField.getMillis(INTEGER_MAX)); } public void test_getMillis_long() { assertEquals(0L, iField.getMillis(0L)); assertEquals(1234000L, iField.getMillis(1234L)); assertEquals(-1234000L, iField.getMillis(-1234L)); try { iField.getMillis(LONG_MAX); fail(); } catch (ArithmeticException ex) {} } public void test_getMillis_int_long() { assertEquals(0L, iField.getMillis(0, 567L)); assertEquals(1234000L, iField.getMillis(1234, 567L)); assertEquals(-1234000L, iField.getMillis(-1234, 567L)); assertEquals(LONG_INTEGER_MAX * 1000L, iField.getMillis(INTEGER_MAX, 567L)); } public void test_getMillis_long_long() { assertEquals(0L, iField.getMillis(0L, 567L)); assertEquals(1234000L, iField.getMillis(1234L, 567L)); assertEquals(-1234000L, iField.getMillis(-1234L, 567L)); try { iField.getMillis(LONG_MAX, 567L); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_add_long_int() { assertEquals(567L, iField.add(567L, 0)); assertEquals(567L + 1234000L, iField.add(567L, 1234)); assertEquals(567L - 1234000L, iField.add(567L, -1234)); try { iField.add(LONG_MAX, 1); fail(); } catch (ArithmeticException ex) {} } public void test_add_long_long() { assertEquals(567L, iField.add(567L, 0L)); assertEquals(567L + 1234000L, iField.add(567L, 1234L)); assertEquals(567L - 1234000L, iField.add(567L, -1234L)); try { iField.add(LONG_MAX, 1L); fail(); } catch (ArithmeticException ex) {} try { iField.add(1L, LONG_MAX); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_getDifference_long_int() { assertEquals(0, iField.getDifference(1L, 0L)); assertEquals(567, iField.getDifference(567000L, 0L)); assertEquals(567 - 1234, iField.getDifference(567000L, 1234000L)); assertEquals(567 + 1234, iField.getDifference(567000L, -1234000L)); try { iField.getDifference(LONG_MAX, -1L); fail(); } catch (ArithmeticException ex) {} } public void test_getDifferenceAsLong_long_long() { assertEquals(0L, iField.getDifferenceAsLong(1L, 0L)); assertEquals(567L, iField.getDifferenceAsLong(567000L, 0L)); assertEquals(567L - 1234L, iField.getDifferenceAsLong(567000L, 1234000L)); assertEquals(567L + 1234L, iField.getDifferenceAsLong(567000L, -1234000L)); try { iField.getDifferenceAsLong(LONG_MAX, -1L); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_equals() { assertEquals(true, iField.equals(iField)); assertEquals(false, iField.equals(ISOChronology.getInstance().minutes())); DurationField dummy = new PreciseDurationField(DurationFieldType.seconds(), 0); assertEquals(false, iField.equals(dummy)); dummy = new PreciseDurationField(DurationFieldType.seconds(), 1000); assertEquals(true, iField.equals(dummy)); dummy = new PreciseDurationField(DurationFieldType.millis(), 1000); assertEquals(false, iField.equals(dummy)); assertEquals(false, iField.equals("")); assertEquals(false, iField.equals(null)); } public void test_hashCode() { assertEquals(true, iField.hashCode() == iField.hashCode()); assertEquals(false, iField.hashCode() == ISOChronology.getInstance().minutes().hashCode()); DurationField dummy = new PreciseDurationField(DurationFieldType.seconds(), 0); assertEquals(false, iField.hashCode() == dummy.hashCode()); dummy = new PreciseDurationField(DurationFieldType.seconds(), 1000); assertEquals(true, iField.hashCode() == dummy.hashCode()); dummy = new PreciseDurationField(DurationFieldType.millis(), 1000); assertEquals(false, iField.hashCode() == dummy.hashCode()); } //----------------------------------------------------------------------- public void test_compareTo() { assertEquals(0, iField.compareTo(iField)); assertEquals(-1, iField.compareTo(ISOChronology.getInstance().minutes())); DurationField dummy = new PreciseDurationField(DurationFieldType.seconds(), 0); assertEquals(1, iField.compareTo(dummy)); // try { // iField.compareTo(""); // fail(); // } catch (ClassCastException ex) {} try { iField.compareTo(null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { DurationField test = iField; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DurationField result = (DurationField) ois.readObject(); ois.close(); assertEquals(test, result); } } joda-time-2.3/src/test/java/org/joda/time/field/TestScaledDurationField.java0000644000175000017500000002655711564251364026371 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for PreciseDurationField. * * @author Stephen Colebourne */ public class TestScaledDurationField extends TestCase { private static final long LONG_INTEGER_MAX = Integer.MAX_VALUE; private static final int INTEGER_MAX = Integer.MAX_VALUE; private static final long LONG_MAX = Long.MAX_VALUE; private ScaledDurationField iField; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestScaledDurationField.class); } public TestScaledDurationField(String name) { super(name); } protected void setUp() throws Exception { DurationField base = MillisDurationField.INSTANCE; iField = new ScaledDurationField(base, DurationFieldType.minutes(), 90); } protected void tearDown() throws Exception { iField = null; } //----------------------------------------------------------------------- public void test_constructor() { try { new ScaledDurationField(null, DurationFieldType.minutes(), 10); fail(); } catch (IllegalArgumentException ex) {} try { new ScaledDurationField(MillisDurationField.INSTANCE, null, 10); fail(); } catch (IllegalArgumentException ex) {} try { new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 0); fail(); } catch (IllegalArgumentException ex) {} try { new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 1); fail(); } catch (IllegalArgumentException ex) {} } public void test_getScalar() { assertEquals(90, iField.getScalar()); } //----------------------------------------------------------------------- public void test_getType() { assertEquals(DurationFieldType.minutes(), iField.getType()); } public void test_getName() { assertEquals("minutes", iField.getName()); } public void test_isSupported() { assertEquals(true, iField.isSupported()); } public void test_isPrecise() { assertEquals(true, iField.isPrecise()); } public void test_getUnitMillis() { assertEquals(90, iField.getUnitMillis()); } public void test_toString() { assertEquals("DurationField[minutes]", iField.toString()); } //----------------------------------------------------------------------- public void test_getValue_long() { assertEquals(0, iField.getValue(0L)); assertEquals(12345678 / 90, iField.getValue(12345678L)); assertEquals(-1234 / 90, iField.getValue(-1234L)); assertEquals(INTEGER_MAX / 90, iField.getValue(LONG_INTEGER_MAX)); try { iField.getValue(LONG_INTEGER_MAX + 1L); fail(); } catch (ArithmeticException ex) {} } public void test_getValueAsLong_long() { assertEquals(0L, iField.getValueAsLong(0L)); assertEquals(12345678L / 90, iField.getValueAsLong(12345678L)); assertEquals(-1234 / 90L, iField.getValueAsLong(-1234L)); assertEquals(LONG_INTEGER_MAX + 1L, iField.getValueAsLong(LONG_INTEGER_MAX * 90L + 90L)); } public void test_getValue_long_long() { assertEquals(0, iField.getValue(0L, 567L)); assertEquals(12345678 / 90, iField.getValue(12345678L, 567L)); assertEquals(-1234 / 90, iField.getValue(-1234L, 567L)); assertEquals(INTEGER_MAX / 90, iField.getValue(LONG_INTEGER_MAX, 567L)); try { iField.getValue(LONG_INTEGER_MAX + 1L, 567L); fail(); } catch (ArithmeticException ex) {} } public void test_getValueAsLong_long_long() { assertEquals(0L, iField.getValueAsLong(0L, 567L)); assertEquals(12345678 / 90L, iField.getValueAsLong(12345678L, 567L)); assertEquals(-1234 / 90L, iField.getValueAsLong(-1234L, 567L)); assertEquals(LONG_INTEGER_MAX + 1L, iField.getValueAsLong(LONG_INTEGER_MAX * 90L + 90L, 567L)); } //----------------------------------------------------------------------- public void test_getMillis_int() { assertEquals(0, iField.getMillis(0)); assertEquals(1234L * 90L, iField.getMillis(1234)); assertEquals(-1234L * 90L, iField.getMillis(-1234)); assertEquals(LONG_INTEGER_MAX * 90L, iField.getMillis(INTEGER_MAX)); } public void test_getMillis_long() { assertEquals(0L, iField.getMillis(0L)); assertEquals(1234L * 90L, iField.getMillis(1234L)); assertEquals(-1234L * 90L, iField.getMillis(-1234L)); try { iField.getMillis(LONG_MAX); fail(); } catch (ArithmeticException ex) {} } public void test_getMillis_int_long() { assertEquals(0L, iField.getMillis(0, 567L)); assertEquals(1234L * 90L, iField.getMillis(1234, 567L)); assertEquals(-1234L * 90L, iField.getMillis(-1234, 567L)); assertEquals(LONG_INTEGER_MAX * 90L, iField.getMillis(INTEGER_MAX, 567L)); } public void test_getMillis_long_long() { assertEquals(0L, iField.getMillis(0L, 567L)); assertEquals(1234L * 90L, iField.getMillis(1234L, 567L)); assertEquals(-1234L * 90L, iField.getMillis(-1234L, 567L)); try { iField.getMillis(LONG_MAX, 567L); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_add_long_int() { assertEquals(567L, iField.add(567L, 0)); assertEquals(567L + 1234L * 90L, iField.add(567L, 1234)); assertEquals(567L - 1234L * 90L, iField.add(567L, -1234)); try { iField.add(LONG_MAX, 1); fail(); } catch (ArithmeticException ex) {} } public void test_add_long_long() { assertEquals(567L, iField.add(567L, 0L)); assertEquals(567L + 1234L * 90L, iField.add(567L, 1234L)); assertEquals(567L - 1234L * 90L, iField.add(567L, -1234L)); try { iField.add(LONG_MAX, 1L); fail(); } catch (ArithmeticException ex) {} try { iField.add(1L, LONG_MAX); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_getDifference_long_int() { assertEquals(0, iField.getDifference(1L, 0L)); assertEquals(567, iField.getDifference(567L * 90L, 0L)); assertEquals(567 - 1234, iField.getDifference(567L * 90L, 1234L * 90L)); assertEquals(567 + 1234, iField.getDifference(567L * 90L, -1234L * 90L)); try { iField.getDifference(LONG_MAX, -1L); fail(); } catch (ArithmeticException ex) {} } public void test_getDifferenceAsLong_long_long() { assertEquals(0L, iField.getDifferenceAsLong(1L, 0L)); assertEquals(567L, iField.getDifferenceAsLong(567L * 90L, 0L)); assertEquals(567L - 1234L, iField.getDifferenceAsLong(567L * 90L, 1234L * 90L)); assertEquals(567L + 1234L, iField.getDifferenceAsLong(567L * 90L, -1234L * 90L)); try { iField.getDifferenceAsLong(LONG_MAX, -1L); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void test_equals() { assertEquals(true, iField.equals(iField)); assertEquals(false, iField.equals(ISOChronology.getInstance().minutes())); DurationField dummy = new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 2); assertEquals(false, iField.equals(dummy)); dummy = new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 90); assertEquals(true, iField.equals(dummy)); dummy = new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.millis(), 90); assertEquals(false, iField.equals(dummy)); assertEquals(false, iField.equals("")); assertEquals(false, iField.equals(null)); } public void test_hashCode() { assertEquals(iField.hashCode(), iField.hashCode()); assertEquals(false, iField.hashCode() == ISOChronology.getInstance().minutes().hashCode()); DurationField dummy = new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 2); assertEquals(false, iField.hashCode() == dummy.hashCode()); dummy = new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 90); assertEquals(true, iField.hashCode() == dummy.hashCode()); dummy = new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.millis(), 90); assertEquals(false, iField.hashCode() == dummy.hashCode()); } //----------------------------------------------------------------------- public void test_compareTo() { assertEquals(0, iField.compareTo(iField)); assertEquals(-1, iField.compareTo(ISOChronology.getInstance().minutes())); DurationField dummy = new PreciseDurationField(DurationFieldType.minutes(), 0); assertEquals(1, iField.compareTo(dummy)); // try { // iField.compareTo(""); // fail(); // } catch (ClassCastException ex) {} try { iField.compareTo(null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { DurationField test = iField; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DurationField result = (DurationField) ois.readObject(); ois.close(); assertEquals(test, result); } } joda-time-2.3/src/test/java/org/joda/time/field/TestBaseDateTimeField.java0000644000175000017500000005644411564251364025755 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.TimeOfDay; import org.joda.time.base.BasePartial; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for BaseDateTimeField. * * @author Stephen Colebourne */ public class TestBaseDateTimeField extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestBaseDateTimeField.class); } public TestBaseDateTimeField(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_constructor() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(DateTimeFieldType.secondOfMinute(), field.getType()); try { field = new MockBaseDateTimeField(null); fail(); } catch (IllegalArgumentException ex) {} } public void test_getType() { BaseDateTimeField field = new MockBaseDateTimeField(DateTimeFieldType.secondOfDay()); assertEquals(DateTimeFieldType.secondOfDay(), field.getType()); } public void test_getName() { BaseDateTimeField field = new MockBaseDateTimeField(DateTimeFieldType.secondOfDay()); assertEquals("secondOfDay", field.getName()); } public void test_toString() { BaseDateTimeField field = new MockBaseDateTimeField(DateTimeFieldType.secondOfDay()); assertEquals("DateTimeField[secondOfDay]", field.toString()); } public void test_isSupported() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(true, field.isSupported()); } public void test_get() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0, field.get(0)); assertEquals(1, field.get(60)); assertEquals(2, field.get(123)); } //----------------------------------------------------------------------- public void test_getAsText_long_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("29", field.getAsText(60L * 29, Locale.ENGLISH)); assertEquals("29", field.getAsText(60L * 29, null)); } public void test_getAsText_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("29", field.getAsText(60L * 29)); } public void test_getAsText_RP_int_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsText_RP_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsText_int_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("80", field.getAsText(80, Locale.ENGLISH)); assertEquals("80", field.getAsText(80, null)); } //----------------------------------------------------------------------- public void test_getAsShortText_long_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("29", field.getAsShortText(60L * 29, Locale.ENGLISH)); assertEquals("29", field.getAsShortText(60L * 29, null)); } public void test_getAsShortText_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("29", field.getAsShortText(60L * 29)); } public void test_getAsShortText_RP_int_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, Locale.ENGLISH)); assertEquals("20", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), 20, null)); } public void test_getAsShortText_RP_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), Locale.ENGLISH)); assertEquals("40", field.getAsShortText(new TimeOfDay(12, 30, 40, 50), null)); } public void test_getAsShortText_int_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals("80", field.getAsShortText(80, Locale.ENGLISH)); assertEquals("80", field.getAsShortText(80, null)); } //----------------------------------------------------------------------- public void test_add_long_int() { MockCountingDurationField.add_int = 0; BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(61, field.add(1L, 1)); assertEquals(1, MockCountingDurationField.add_int); } public void test_add_long_long() { MockCountingDurationField.add_long = 0; BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(61, field.add(1L, 1L)); assertEquals(1, MockCountingDurationField.add_long); } public void test_add_RP_int_intarray_int() { int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; BaseDateTimeField field = new MockStandardBaseDateTimeField(); int[] result = field.add(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 31, 40}; result = field.add(new TimeOfDay(), 2, values, 1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 21, 0, 40}; result = field.add(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {23, 59, 30, 40}; try { field.add(new TimeOfDay(), 2, values, 30); fail(); } catch (IllegalArgumentException ex) {} values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.add(new TimeOfDay(), 2, values, -1); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 19, 59, 40}; result = field.add(new TimeOfDay(), 2, values, -31); assertEquals(true, Arrays.equals(expected, result)); values = new int[] {0, 0, 30, 40}; try { field.add(new TimeOfDay(), 2, values, -31); fail(); } catch (IllegalArgumentException ex) {} values = new int[] {0, 0}; try { field.add(new MockPartial(), 0, values, 1000); fail(); } catch (IllegalArgumentException ex) {} values = new int[] {1, 0}; try { field.add(new MockPartial(), 0, values, -1000); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_addWrapField_long_int() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(1029, field.addWrapField(60L * 29, 0)); assertEquals(1059, field.addWrapField(60L * 29, 30)); assertEquals(1000, field.addWrapField(60L * 29, 31)); } public void test_addWrapField_RP_int_intarray_int() { BaseDateTimeField field = new MockBaseDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.addWrapField(new TimeOfDay(), 2, values, 0); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 59, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 0, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 1, 40}; result = field.addWrapField(new TimeOfDay(), 2, values, 31); assertEquals(true, Arrays.equals(result, expected)); } //----------------------------------------------------------------------- public void test_getDifference_long_long() { MockCountingDurationField.difference_long = 0; BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(30, field.getDifference(0L, 0L)); assertEquals(1, MockCountingDurationField.difference_long); } public void test_getDifferenceAsLong_long_long() { MockCountingDurationField.difference_long = 0; BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(30, field.getDifferenceAsLong(0L, 0L)); assertEquals(1, MockCountingDurationField.difference_long); } //----------------------------------------------------------------------- public void test_set_long_int() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(1000, field.set(0L, 0)); assertEquals(1029, field.set(0L, 29)); } public void test_set_RP_int_intarray_int() { BaseDateTimeField field = new MockBaseDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, 30); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, 29); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, 60); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, -1); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_set_long_String_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(1000, field.set(0L, "0", null)); assertEquals(1029, field.set(0L, "29", Locale.ENGLISH)); } public void test_set_long_String() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(1000, field.set(0L, "0")); assertEquals(1029, field.set(0L, "29")); } public void test_set_RP_int_intarray_String_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); int[] values = new int[] {10, 20, 30, 40}; int[] expected = new int[] {10, 20, 30, 40}; int[] result = field.set(new TimeOfDay(), 2, values, "30", null); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 29, 40}; result = field.set(new TimeOfDay(), 2, values, "29", Locale.ENGLISH); assertEquals(true, Arrays.equals(result, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "60", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); values = new int[] {10, 20, 30, 40}; expected = new int[] {10, 20, 30, 40}; try { field.set(new TimeOfDay(), 2, values, "-1", null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, Arrays.equals(values, expected)); } public void test_convertText() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0, field.convertText("0", null)); assertEquals(29, field.convertText("29", null)); try { field.convertText("2A", null); fail(); } catch (IllegalArgumentException ex) {} try { field.convertText(null, null); fail(); } catch (IllegalArgumentException ex) {} } //------------------------------------------------------------------------ // public abstract DurationField getDurationField(); // // public abstract DurationField getRangeDurationField(); public void test_isLeap_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(false, field.isLeap(0L)); } public void test_getLeapAmount_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0, field.getLeapAmount(0L)); } public void test_getLeapDurationField() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(null, field.getLeapDurationField()); } //----------------------------------------------------------------------- public void test_getMinimumValue() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0, field.getMinimumValue()); } public void test_getMinimumValue_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0, field.getMinimumValue(0L)); } public void test_getMinimumValue_RP() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0, field.getMinimumValue(new TimeOfDay())); } public void test_getMinimumValue_RP_intarray() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0, field.getMinimumValue(new TimeOfDay(), new int[4])); } public void test_getMaximumValue() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(59, field.getMaximumValue()); } public void test_getMaximumValue_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(59, field.getMaximumValue(0L)); } public void test_getMaximumValue_RP() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(59, field.getMaximumValue(new TimeOfDay())); } public void test_getMaximumValue_RP_intarray() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(59, field.getMaximumValue(new TimeOfDay(), new int[4])); } //----------------------------------------------------------------------- public void test_getMaximumTextLength_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(2, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockBaseDateTimeField() { public int getMaximumValue() { return 5; } }; assertEquals(1, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockBaseDateTimeField() { public int getMaximumValue() { return 555; } }; assertEquals(3, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockBaseDateTimeField() { public int getMaximumValue() { return 5555; } }; assertEquals(4, field.getMaximumTextLength(Locale.ENGLISH)); field = new MockBaseDateTimeField() { public int getMaximumValue() { return -1; } }; assertEquals(2, field.getMaximumTextLength(Locale.ENGLISH)); } public void test_getMaximumShortTextLength_Locale() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(2, field.getMaximumShortTextLength(Locale.ENGLISH)); } //------------------------------------------------------------------------ public void test_roundFloor_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0L, field.roundFloor(0L)); assertEquals(0L, field.roundFloor(29L)); assertEquals(0L, field.roundFloor(30L)); assertEquals(0L, field.roundFloor(31L)); assertEquals(60L, field.roundFloor(60L)); } public void test_roundCeiling_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0L, field.roundCeiling(0L)); assertEquals(60L, field.roundCeiling(29L)); assertEquals(60L, field.roundCeiling(30L)); assertEquals(60L, field.roundCeiling(31L)); assertEquals(60L, field.roundCeiling(60L)); } public void test_roundHalfFloor_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0L, field.roundHalfFloor(0L)); assertEquals(0L, field.roundHalfFloor(29L)); assertEquals(0L, field.roundHalfFloor(30L)); assertEquals(60L, field.roundHalfFloor(31L)); assertEquals(60L, field.roundHalfFloor(60L)); } public void test_roundHalfCeiling_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0L, field.roundHalfCeiling(0L)); assertEquals(0L, field.roundHalfCeiling(29L)); assertEquals(60L, field.roundHalfCeiling(30L)); assertEquals(60L, field.roundHalfCeiling(31L)); assertEquals(60L, field.roundHalfCeiling(60L)); } public void test_roundHalfEven_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0L, field.roundHalfEven(0L)); assertEquals(0L, field.roundHalfEven(29L)); assertEquals(0L, field.roundHalfEven(30L)); assertEquals(60L, field.roundHalfEven(31L)); assertEquals(60L, field.roundHalfEven(60L)); assertEquals(60L, field.roundHalfEven(89L)); assertEquals(120L, field.roundHalfEven(90L)); assertEquals(120L, field.roundHalfEven(91L)); } public void test_remainder_long() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(0L, field.remainder(0L)); assertEquals(29L, field.remainder(29L)); assertEquals(30L, field.remainder(30L)); assertEquals(31L, field.remainder(31L)); assertEquals(0L, field.remainder(60L)); } //----------------------------------------------------------------------- static class MockBaseDateTimeField extends BaseDateTimeField { protected MockBaseDateTimeField() { super(DateTimeFieldType.secondOfMinute()); } protected MockBaseDateTimeField(DateTimeFieldType type) { super(type); } public int get(long instant) { return (int) (instant / 60L); } public long set(long instant, int value) { return 1000 + value; } public DurationField getDurationField() { return new MockCountingDurationField(DurationFieldType.seconds()); } public DurationField getRangeDurationField() { return new MockCountingDurationField(DurationFieldType.minutes()); } public int getMinimumValue() { return 0; } public int getMaximumValue() { return 59; } public long roundFloor(long instant) { return (instant / 60L) * 60L; } public boolean isLenient() { return false; } } static class MockStandardBaseDateTimeField extends MockBaseDateTimeField { protected MockStandardBaseDateTimeField() { super(); } public DurationField getDurationField() { return ISOChronology.getInstanceUTC().seconds(); } public DurationField getRangeDurationField() { return ISOChronology.getInstanceUTC().minutes(); } } //----------------------------------------------------------------------- static class MockCountingDurationField extends BaseDurationField { static int add_int = 0; static int add_long = 0; static int difference_long = 0; protected MockCountingDurationField(DurationFieldType type) { super(type); } public boolean isPrecise() { return false; } public long getUnitMillis() { return 0; } public long getValueAsLong(long duration, long instant) { return 0; } public long getMillis(int value, long instant) { return 0; } public long getMillis(long value, long instant) { return 0; } public long add(long instant, int value) { add_int++; return instant + (value * 60L); } public long add(long instant, long value) { add_long++; return instant + (value * 60L); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { difference_long++; return 30; } } static class MockPartial extends BasePartial { protected DateTimeField getField(int index, Chronology chrono) { if (index == 0) { return ISOChronology.getInstanceUTC().minuteOfHour(); } if (index == 1) { return ISOChronology.getInstanceUTC().millisOfSecond(); } return null; } public int size() { return 2; } } } joda-time-2.3/src/test/java/org/joda/time/field/TestUnsupportedDateTimeField.java0000644000175000017500000006215711564251364027431 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationFieldType; import org.joda.time.LocalTime; import org.joda.time.ReadablePartial; /** * This class is a JUnit test to test only the UnsupportedDateTimeField class. * This set of test cases exercises everything described in the Javadoc for this * class. * * @author Jeremy R. Rickard */ public class TestUnsupportedDateTimeField extends TestCase { private DurationFieldType weeks; private DurationFieldType months; private DateTimeFieldType dateTimeFieldTypeOne; private ReadablePartial localTime; public static TestSuite suite() { return new TestSuite(TestUnsupportedDateTimeField.class); } protected void setUp() throws Exception { weeks = DurationFieldType.weeks(); months = DurationFieldType.months(); dateTimeFieldTypeOne = DateTimeFieldType.centuryOfEra(); localTime = new LocalTime(); } /** * Passing null values into UnsupportedDateTimeField.getInstance() should * throw an IllegalArguementsException */ public void testNullValuesToGetInstanceThrowsException() { try { UnsupportedDateTimeField.getInstance(null, null); assertTrue(false); } catch (IllegalArgumentException e) { assertTrue(true); } } /** * * This test exercises the logic in UnsupportedDateTimeField.getInstance. If * getInstance() is invoked twice with: - the same DateTimeFieldType - * different duration fields * * Then the field returned in the first invocation should not be equal to * the field returned by the second invocation. In otherwords, the generated * instance should be the same for a unique pairing of * DateTimeFieldType/DurationField */ public void testDifferentDurationReturnDifferentObjects() { /** * The fields returned by getInstance should be the same when the * duration is the same for both method calls. */ DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); DateTimeField fieldTwo = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertSame(fieldOne, fieldTwo); /** * The fields returned by getInstance should NOT be the same when the * duration is the same for both method calls. */ DateTimeField fieldThree = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(months)); assertNotSame(fieldOne, fieldThree); } /** * The getName() method should return the same value as the getName() method * of the DateTimeFieldType that was used to create the instance. * */ public void testPublicGetNameMethod() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertSame(fieldOne.getName(), dateTimeFieldTypeOne.getName()); } /** * As this is an unsupported date/time field, some normal methods will * always return false, as they are not supported. Verify that each method * correctly returns null. */ public void testAlwaysFalseReturnTypes() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertFalse(fieldOne.isLenient()); assertFalse(fieldOne.isSupported()); } /** * According to the JavaDocs, there are two methods that should always * return null. * getRangeDurationField() * getLeapDurationField() * * Ensure that these are in fact null. */ public void testMethodsThatShouldAlwaysReturnNull() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertNull(fieldOne.getLeapDurationField()); assertNull(fieldOne.getRangeDurationField()); } /** * As this is an unsupported date/time field, many normal methods are * unsupported and throw an UnsupportedOperationException. Verify that each * method correctly throws this exception. * add(ReadablePartial instant, * int fieldIndex, int[] values, int valueToAdd) * addWrapField(long * instant, int value) * addWrapField(ReadablePartial instant, int * fieldIndex, int[] values, int valueToAdd) * * addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int * valueToAdd) * get(long instant) * getAsShortText(int fieldValue, Locale * locale) * getAsShortText(long instant) * getAsShortText(long instant, * Locale locale) * getAsShortText(ReadablePartial partial, int fieldValue, * Locale locale) * getAsShortText(ReadablePartial partial, Locale locale) * * getAsText(int fieldValue, Locale locale) * getAsText(long instant) * * getAsText(long instant, Locale locale) * getAsText(ReadablePartial * partial, int fieldValue, Locale locale) * getAsText(ReadablePartial * partial, Locale locale) * getLeapAmount(long instant) * * getMaximumShortTextLength(Locale locale) * getMaximumTextLength(Locale * locale) * getMaximumValue() * getMaximumValue(long instant) * * getMaximumValue(ReadablePartial instant) * * getMaximumValue(ReadablePartial instant, int[] values) * * getMinimumValue() * getMinimumValue(long instant) * * getMinimumValue(ReadablePartial instant) * * getMinimumValue(ReadablePartial instant, int[] values) * isLeap(long * instant) * remainder(long instant) * roundCeiling(long instant) * * roundFloor(long instant) * roundHalfCeiling(long instant) * * roundHalfEven(long instant) * roundHalfFloor(long instant) * set(long * instant, int value) * set(long instant, String text) * set(long instant, * String text, Locale locale) * set(ReadablePartial instant, int * fieldIndex, int[] values, int newValue) * set(ReadablePartial instant, * int fieldIndex, int[] values, String text, Locale locale) */ public void testUnsupportedMethods() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); // add(ReadablePartial instant, int fieldIndex, int[] values, int // valueToAdd) try { fieldOne.add(localTime, 0, new int[] { 0, 100 }, 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // addWrapField(long instant, int value) try { fieldOne.addWrapField(100000L, 250); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // addWrapField(ReadablePartial instant, int fieldIndex, int[] values, // int valueToAdd) try { fieldOne.addWrapField(localTime, 0, new int[] { 0, 100 }, 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, // int valueToAdd) try { fieldOne.addWrapPartial(localTime, 0, new int[] { 0, 100 }, 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.get(long instant) try { fieldOne.get(1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(int fieldValue, // Locale locale) try { fieldOne.getAsShortText(0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(long instant) try { fieldOne.getAsShortText(100000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(long instant, Locale locale) try { fieldOne.getAsShortText(100000L, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(ReadablePartial partial, // int fieldValue, // Locale locale) try { fieldOne.getAsShortText(localTime, 0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsShortText(ReadablePartial partial, // Locale locale) try { fieldOne.getAsShortText(localTime, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(int fieldValue, // Locale locale) try { fieldOne.getAsText(0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(long instant) try { fieldOne.getAsText(1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(long instant, Locale locale) try { fieldOne.getAsText(1000L, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(ReadablePartial partial, // int fieldValue, // Locale locale) try { fieldOne.getAsText(localTime, 0, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getAsText(ReadablePartial partial, // Locale locale) try { fieldOne.getAsText(localTime, Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getLeapAmount(long instant) is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getLeapAmount(System.currentTimeMillis()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumShortTextLength(Locale locale) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumShortTextLength(Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumTextLength(Locale locale) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumTextLength(Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue() is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMaximumValue(); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue(long instant) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumValue(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue(ReadablePartial instant) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumValue(localTime); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMaximumValue(ReadablePartial instant, // int[] values) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMaximumValue(localTime, new int[] { 0 }); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue() is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMinimumValue(); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue(long instant) is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMinimumValue(10000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue(ReadablePartial instant) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne.getMinimumValue(localTime); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.getMinumumValue(ReadablePartial instant, // int[] values) is unsupported // and should always thrown an UnsupportedOperationException try { fieldOne.getMinimumValue(localTime, new int[] { 0 }); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.isLeap(long instant) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.isLeap(System.currentTimeMillis()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.remainder(long instant) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.remainder(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundCeiling(long instant) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.roundCeiling(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundFloor(long instant) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.roundFloor(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundHalfCeiling(long instant) is // unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.roundHalfCeiling(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundHalfEven(long instant) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.roundHalfEven(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.roundHalfFloor(long instant) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.roundHalfFloor(1000000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(long instant, int value) is unsupported // and // should always thrown an UnsupportedOperationException try { fieldOne.set(1000000L, 1000); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(long instant, String test) is // unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.set(1000000L, "Unsupported Operation"); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(long instant, String text, Locale // locale) // is unsupported and should always thrown an // UnsupportedOperationException try { fieldOne .set(1000000L, "Unsupported Operation", Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(ReadablePartial instant, // int fieldIndex, // int[] values, // int newValue) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.set(localTime, 0, new int[] { 0 }, 10000); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } // UnsupportedDateTimeField.set(ReadablePartial instant, // int fieldIndex, // int[] values, // String text, // Locale locale) is unsupported and // should always thrown an UnsupportedOperationException try { fieldOne.set(localTime, 0, new int[] { 0 }, "Unsupported Operation", Locale.getDefault()); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } } /** * As this is an unsupported date/time field, many normal methods are * unsupported. Some delegate and can possibly throw an * UnsupportedOperationException or have a valid return. Verify that each * method correctly throws this exception when appropriate and delegates * correctly based on the Duration used to get the instance. */ public void testDelegatedMethods() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); PreciseDurationField hoursDuration = new PreciseDurationField( DurationFieldType.hours(), 10L); DateTimeField fieldTwo = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, hoursDuration); // UnsupportedDateTimeField.add(long instant, int value) should // throw an UnsupportedOperationException when the duration does // not support the operation, otherwise it delegates to the duration. // First // try it with an UnsupportedDurationField, then a PreciseDurationField. try { fieldOne.add(System.currentTimeMillis(), 100); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long currentTime = System.currentTimeMillis(); long firstComputation = hoursDuration.add(currentTime, 100); long secondComputation = fieldTwo.add(currentTime, 100); assertEquals(firstComputation,secondComputation); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.add(long instant, long value) should // throw an UnsupportedOperationException when the duration does // not support the operation, otherwise it delegates to the duration. // First // try it with an UnsupportedDurationField, then a PreciseDurationField. try { fieldOne.add(System.currentTimeMillis(), 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long currentTime = System.currentTimeMillis(); long firstComputation = hoursDuration.add(currentTime, 1000L); long secondComputation = fieldTwo.add(currentTime, 1000L); assertTrue(firstComputation == secondComputation); assertEquals(firstComputation,secondComputation); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.getDifference(long minuendInstant, // long subtrahendInstant) // should throw an UnsupportedOperationException when the duration does // not support the operation, otherwise return the result from the // delegated call. try { fieldOne.getDifference(100000L, 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { int firstDifference = hoursDuration.getDifference(100000L, 1000L); int secondDifference = fieldTwo.getDifference(100000L, 1000L); assertEquals(firstDifference,secondDifference); } catch (UnsupportedOperationException e) { assertTrue(false); } // UnsupportedDateTimeField.getDifferenceAsLong(long minuendInstant, // long subtrahendInstant) // should throw an UnsupportedOperationException when the duration does // not support the operation, otherwise return the result from the // delegated call. try { fieldOne.getDifferenceAsLong(100000L, 1000L); assertTrue(false); } catch (UnsupportedOperationException e) { assertTrue(true); } try { long firstDifference = hoursDuration.getDifference(100000L, 1000L); long secondDifference = fieldTwo.getDifference(100000L, 1000L); assertEquals(firstDifference,secondDifference); } catch (UnsupportedOperationException e) { assertTrue(false); } } /** * The toString method should return a suitable debug message (not null). * Ensure that the toString method returns a string with length greater than * 0 (and not null) * */ public void testToString() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); String debugMessage = fieldOne.toString(); assertNotNull(debugMessage); assertTrue(debugMessage.length() > 0); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalTime_Basics.java0000644000175000017500000010565312200501234024547 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for LocalTime. * * @author Stephen Colebourne */ public class TestLocalTime_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON); private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; // private long TEST_TIME1 = // 1L * DateTimeConstants.MILLIS_PER_HOUR // + 2L * DateTimeConstants.MILLIS_PER_MINUTE // + 3L * DateTimeConstants.MILLIS_PER_SECOND // + 4L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalTime_Basics.class); } public TestLocalTime_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testGet_DateTimeFieldType() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(10, test.get(DateTimeFieldType.hourOfDay())); assertEquals(20, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(30, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(40, test.get(DateTimeFieldType.millisOfSecond())); assertEquals(TEST_TIME_NOW / 60000 , test.get(DateTimeFieldType.minuteOfDay())); assertEquals(TEST_TIME_NOW / 1000 , test.get(DateTimeFieldType.secondOfDay())); assertEquals(TEST_TIME_NOW , test.get(DateTimeFieldType.millisOfDay())); assertEquals(10, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(DateTimeConstants.AM, test.get(DateTimeFieldType.halfdayOfDay())); test = new LocalTime(12, 30); assertEquals(0, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(12, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(12, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(DateTimeConstants.PM, test.get(DateTimeFieldType.halfdayOfDay())); test = new LocalTime(14, 30); assertEquals(2, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(2, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(14, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(DateTimeConstants.PM, test.get(DateTimeFieldType.halfdayOfDay())); test = new LocalTime(0, 30); assertEquals(0, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(12, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(24, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(DateTimeConstants.AM, test.get(DateTimeFieldType.halfdayOfDay())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.dayOfMonth()); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(4, test.size()); } public void testGetFieldType_int() { LocalTime test = new LocalTime(10, 20, 30, 40); assertSame(DateTimeFieldType.hourOfDay(), test.getFieldType(0)); assertSame(DateTimeFieldType.minuteOfHour(), test.getFieldType(1)); assertSame(DateTimeFieldType.secondOfMinute(), test.getFieldType(2)); assertSame(DateTimeFieldType.millisOfSecond(), test.getFieldType(3)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(5); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { LocalTime test = new LocalTime(10, 20, 30, 40); DateTimeFieldType[] fields = test.getFieldTypes(); assertSame(DateTimeFieldType.hourOfDay(), fields[0]); assertSame(DateTimeFieldType.minuteOfHour(), fields[1]); assertSame(DateTimeFieldType.secondOfMinute(), fields[2]); assertSame(DateTimeFieldType.millisOfSecond(), fields[3]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField_int() { LocalTime test = new LocalTime(10, 20, 30, 40, COPTIC_UTC); assertSame(COPTIC_UTC.hourOfDay(), test.getField(0)); assertSame(COPTIC_UTC.minuteOfHour(), test.getField(1)); assertSame(COPTIC_UTC.secondOfMinute(), test.getField(2)); assertSame(COPTIC_UTC.millisOfSecond(), test.getField(3)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(5); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { LocalTime test = new LocalTime(10, 20, 30, 40, COPTIC_UTC); DateTimeField[] fields = test.getFields(); assertSame(COPTIC_UTC.hourOfDay(), fields[0]); assertSame(COPTIC_UTC.minuteOfHour(), fields[1]); assertSame(COPTIC_UTC.secondOfMinute(), fields[2]); assertSame(COPTIC_UTC.millisOfSecond(), fields[3]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue_int() { LocalTime test = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); assertEquals(10, test.getValue(0)); assertEquals(20, test.getValue(1)); assertEquals(30, test.getValue(2)); assertEquals(40, test.getValue(3)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(5); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { LocalTime test = new LocalTime(10, 20, 30, 40, COPTIC_UTC); int[] values = test.getValues(); assertEquals(10, values[0]); assertEquals(20, values[1]); assertEquals(30, values[2]); assertEquals(40, values[3]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported_DateTimeFieldType() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(true, test.isSupported(DateTimeFieldType.secondOfMinute())); assertEquals(true, test.isSupported(DateTimeFieldType.millisOfSecond())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.secondOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.millisOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfHalfday())); assertEquals(true, test.isSupported(DateTimeFieldType.halfdayOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.clockhourOfHalfday())); assertEquals(true, test.isSupported(DateTimeFieldType.clockhourOfDay())); assertEquals(false, test.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(false, test.isSupported((DateTimeFieldType) null)); DateTimeFieldType d = new DateTimeFieldType("hours") { private static final long serialVersionUID = 1L; public DurationFieldType getDurationType() { return DurationFieldType.hours(); } public DurationFieldType getRangeDurationType() { return null; } public DateTimeField getField(Chronology chronology) { return chronology.hourOfDay(); } }; assertEquals(false, test.isSupported(d)); d = new DateTimeFieldType("hourOfYear") { private static final long serialVersionUID = 1L; public DurationFieldType getDurationType() { return DurationFieldType.hours(); } public DurationFieldType getRangeDurationType() { return DurationFieldType.years(); } public DateTimeField getField(Chronology chronology) { return chronology.hourOfDay(); } }; assertEquals(false, test.isSupported(d)); } public void testIsSupported_DurationFieldType() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(true, test.isSupported(DurationFieldType.hours())); assertEquals(true, test.isSupported(DurationFieldType.minutes())); assertEquals(true, test.isSupported(DurationFieldType.seconds())); assertEquals(true, test.isSupported(DurationFieldType.millis())); assertEquals(true, test.isSupported(DurationFieldType.halfdays())); assertEquals(false, test.isSupported(DurationFieldType.days())); assertEquals(false, test.isSupported((DurationFieldType) null)); } @SuppressWarnings("deprecation") public void testEqualsHashCode() { LocalTime test1 = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); LocalTime test2 = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); LocalTime test3 = new LocalTime(15, 20, 30, 40); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new TimeOfDay(10, 20, 30, 40, COPTIC_UTC))); assertEquals(true, test1.hashCode() == new TimeOfDay(10, 20, 30, 40, COPTIC_UTC).hashCode()); assertEquals(true, test1.equals(new MockInstant())); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); } class MockInstant extends MockPartial { public Chronology getChronology() { return COPTIC_UTC; } public DateTimeField[] getFields() { return new DateTimeField[] { COPTIC_UTC.hourOfDay(), COPTIC_UTC.minuteOfHour(), COPTIC_UTC.secondOfMinute(), COPTIC_UTC.millisOfSecond(), }; } public int[] getValues() { return new int[] {10, 20, 30, 40}; } } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testCompareTo() { LocalTime test1 = new LocalTime(10, 20, 30, 40); LocalTime test1a = new LocalTime(10, 20, 30, 40); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); LocalTime test2 = new LocalTime(10, 20, 35, 40); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); LocalTime test3 = new LocalTime(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour(), DateTimeFieldType.secondOfMinute(), DateTimeFieldType.millisOfSecond(), }; int[] values = new int[] {10, 20, 30, 40}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); assertEquals(0, test1.compareTo(new TimeOfDay(10, 20, 30, 40))); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_LocalTime() { LocalTime test1 = new LocalTime(10, 20, 30, 40); LocalTime test1a = new LocalTime(10, 20, 30, 40); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); LocalTime test2 = new LocalTime(10, 20, 35, 40); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); LocalTime test3 = new LocalTime(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { new LocalTime(10, 20, 35, 40).isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_LocalTime() { LocalTime test1 = new LocalTime(10, 20, 30, 40); LocalTime test1a = new LocalTime(10, 20, 30, 40); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); LocalTime test2 = new LocalTime(10, 20, 35, 40); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); LocalTime test3 = new LocalTime(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new LocalTime(10, 20, 35, 40).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_LocalTime() { LocalTime test1 = new LocalTime(10, 20, 30, 40); LocalTime test1a = new LocalTime(10, 20, 30, 40); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); LocalTime test2 = new LocalTime(10, 20, 35, 40); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); LocalTime test3 = new LocalTime(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new LocalTime(10, 20, 35, 40).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithField_DateTimeFieldType_int_1() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime result = test.withField(DateTimeFieldType.hourOfDay(), 15); assertEquals(new LocalTime(10, 20, 30, 40), test); assertEquals(new LocalTime(15, 20, 30, 40), result); } public void testWithField_DateTimeFieldType_int_2() { LocalTime test = new LocalTime(10, 20, 30, 40); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_DateTimeFieldType_int_3() { LocalTime test = new LocalTime(10, 20, 30, 40); try { test.withField(DateTimeFieldType.dayOfMonth(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_DateTimeFieldType_int_4() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime result = test.withField(DateTimeFieldType.hourOfDay(), 10); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded_DurationFieldType_int_1() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime result = test.withFieldAdded(DurationFieldType.hours(), 6); assertEquals(new LocalTime(10, 20, 30, 40), test); assertEquals(new LocalTime(16, 20, 30, 40), result); } public void testWithFieldAdded_DurationFieldType_int_2() { LocalTime test = new LocalTime(10, 20, 30, 40); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_DurationFieldType_int_3() { LocalTime test = new LocalTime(10, 20, 30, 40); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_DurationFieldType_int_4() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime result = test.withFieldAdded(DurationFieldType.hours(), 0); assertSame(test, result); } public void testWithFieldAdded_DurationFieldType_int_5() { LocalTime test = new LocalTime(10, 20, 30, 40); try { test.withFieldAdded(DurationFieldType.days(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_DurationFieldType_int_6() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime result = test.withFieldAdded(DurationFieldType.hours(), 16); assertEquals(new LocalTime(10, 20, 30, 40), test); assertEquals(new LocalTime(2, 20, 30, 40), result); } public void testWithFieldAdded_DurationFieldType_int_7() { LocalTime test = new LocalTime(23, 59, 59, 999); LocalTime result = test.withFieldAdded(DurationFieldType.millis(), 1); assertEquals(new LocalTime(0, 0, 0, 0), result); test = new LocalTime(23, 59, 59, 999); result = test.withFieldAdded(DurationFieldType.seconds(), 1); assertEquals(new LocalTime(0, 0, 0, 999), result); test = new LocalTime(23, 59, 59, 999); result = test.withFieldAdded(DurationFieldType.minutes(), 1); assertEquals(new LocalTime(0, 0, 59, 999), result); test = new LocalTime(23, 59, 59, 999); result = test.withFieldAdded(DurationFieldType.hours(), 1); assertEquals(new LocalTime(0, 59, 59, 999), result); } public void testWithFieldAdded_DurationFieldType_int_8() { LocalTime test = new LocalTime(0, 0, 0, 0); LocalTime result = test.withFieldAdded(DurationFieldType.millis(), -1); assertEquals(new LocalTime(23, 59, 59, 999), result); test = new LocalTime(0, 0, 0, 0); result = test.withFieldAdded(DurationFieldType.seconds(), -1); assertEquals(new LocalTime(23, 59, 59, 0), result); test = new LocalTime(0, 0, 0, 0); result = test.withFieldAdded(DurationFieldType.minutes(), -1); assertEquals(new LocalTime(23, 59, 0, 0), result); test = new LocalTime(0, 0, 0, 0); result = test.withFieldAdded(DurationFieldType.hours(), -1); assertEquals(new LocalTime(23, 0, 0, 0), result); } //----------------------------------------------------------------------- public void testPlus_RP() { LocalTime test = new LocalTime(10, 20, 30, 40, BUDDHIST_LONDON); LocalTime result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8)); LocalTime expected = new LocalTime(15, 26, 37, 48, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusHours_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.plusHours(1); LocalTime expected = new LocalTime(2, 2, 3, 4, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusHours(0); assertSame(test, result); } public void testPlusMinutes_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.plusMinutes(1); LocalTime expected = new LocalTime(1, 3, 3, 4, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusMinutes(0); assertSame(test, result); } public void testPlusSeconds_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.plusSeconds(1); LocalTime expected = new LocalTime(1, 2, 4, 4, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusSeconds(0); assertSame(test, result); } public void testPlusMillis_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.plusMillis(1); LocalTime expected = new LocalTime(1, 2, 3, 5, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { LocalTime test = new LocalTime(10, 20, 30, 40, BUDDHIST_LONDON); LocalTime result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); LocalTime expected = new LocalTime(9, 19, 29, 39, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusHours_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.minusHours(1); LocalTime expected = new LocalTime(0, 2, 3, 4, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusHours(0); assertSame(test, result); } public void testMinusMinutes_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.minusMinutes(1); LocalTime expected = new LocalTime(1, 1, 3, 4, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusMinutes(0); assertSame(test, result); } public void testMinusSeconds_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.minusSeconds(1); LocalTime expected = new LocalTime(1, 2, 2, 4, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusSeconds(0); assertSame(test, result); } public void testMinusMillis_int() { LocalTime test = new LocalTime(1, 2, 3, 4, BUDDHIST_LONDON); LocalTime result = test.minusMillis(1); LocalTime expected = new LocalTime(1, 2, 3, 3, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testGetters() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(TEST_TIME_NOW, test.getMillisOfDay()); } //----------------------------------------------------------------------- public void testWithers() { LocalTime test = new LocalTime(10, 20, 30, 40); check(test.withHourOfDay(6), 6, 20, 30, 40); check(test.withMinuteOfHour(6), 10, 6, 30, 40); check(test.withSecondOfMinute(6), 10, 20, 6, 40); check(test.withMillisOfSecond(6), 10, 20, 30, 6); check(test.withMillisOfDay(61234), 0, 1, 1, 234); try { test.withHourOfDay(-1); fail(); } catch (IllegalArgumentException ex) {} try { test.withHourOfDay(24); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testToDateTimeTodayDefaultZone() { LocalTime base = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeToday(); check(base, 10, 20, 30, 40); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.hourOfDay().setCopy(10); expected = expected.minuteOfHour().setCopy(20); expected = expected.secondOfMinute().setCopy(30); expected = expected.millisOfSecond().setCopy(40); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTimeToday_Zone() { LocalTime base = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeToday(TOKYO); check(base, 10, 20, 30, 40); DateTime expected = new DateTime(dt.getMillis(), COPTIC_TOKYO); expected = expected.hourOfDay().setCopy(10); expected = expected.minuteOfHour().setCopy(20); expected = expected.secondOfMinute().setCopy(30); expected = expected.millisOfSecond().setCopy(40); assertEquals(expected, test); } public void testToDateTimeToday_nullZone() { LocalTime base = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeToday((DateTimeZone) null); check(base, 10, 20, 30, 40); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.hourOfDay().setCopy(10); expected = expected.minuteOfHour().setCopy(20); expected = expected.secondOfMinute().setCopy(30); expected = expected.millisOfSecond().setCopy(40); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTime_RI() { LocalTime base = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); DateTime dt = new DateTime(0L); // LONDON zone assertEquals("1970-01-01T01:00:00.000+01:00", dt.toString()); DateTime test = base.toDateTime(dt); check(base, 10, 20, 30, 40); assertEquals("1970-01-01T01:00:00.000+01:00", dt.toString()); assertEquals("1970-01-01T10:20:30.040+01:00", test.toString()); } public void testToDateTime_nullRI() { LocalTime base = new LocalTime(1, 2, 3, 4); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 1, 2, 3, 4); assertEquals("1970-01-02T01:02:03.004+01:00", test.toString()); } //----------------------------------------------------------------------- public void testProperty() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(test.hourOfDay(), test.property(DateTimeFieldType.hourOfDay())); assertEquals(test.minuteOfHour(), test.property(DateTimeFieldType.minuteOfHour())); assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute())); assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond())); assertEquals(test.millisOfDay(), test.property(DateTimeFieldType.millisOfDay())); assertEquals(test, test.property(DateTimeFieldType.minuteOfDay()).getLocalTime()); assertEquals(test, test.property(DateTimeFieldType.secondOfDay()).getLocalTime()); assertEquals(test, test.property(DateTimeFieldType.millisOfDay()).getLocalTime()); assertEquals(test, test.property(DateTimeFieldType.hourOfHalfday()).getLocalTime()); assertEquals(test, test.property(DateTimeFieldType.halfdayOfDay()).getLocalTime()); assertEquals(test, test.property(DateTimeFieldType.clockhourOfHalfday()).getLocalTime()); assertEquals(test, test.property(DateTimeFieldType.clockhourOfDay()).getLocalTime()); try { test.property(DateTimeFieldType.dayOfWeek()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { LocalTime test = new LocalTime(10, 20, 30, 40, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); LocalTime result = (LocalTime) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); } //----------------------------------------------------------------------- public void testToString() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals("10:20:30.040", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals("\ufffd\ufffd\ufffd\ufffd 10", test.toString("yyyy HH")); assertEquals("10:20:30.040", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals("10 20", test.toString("H m", Locale.ENGLISH)); assertEquals("10:20:30.040", test.toString(null, Locale.ENGLISH)); assertEquals("10 20", test.toString("H m", null)); assertEquals("10:20:30.040", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals("\ufffd\ufffd\ufffd\ufffd 10", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("10:20:30.040", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private void check(LocalTime test, int hour, int min, int sec, int milli) { assertEquals(hour, test.getHourOfDay()); assertEquals(min, test.getMinuteOfHour()); assertEquals(sec, test.getSecondOfMinute()); assertEquals(milli, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalDateTime_Constructors.java0000644000175000017500000010606612072543747026676 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for LocalDateTime. * * @author Stephen Colebourne */ public class TestLocalDateTime_Constructors extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone MOSCOW = DateTimeZone.forID("Europe/Moscow"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology GREGORIAN_UTC = GregorianChronology.getInstanceUTC(); private static final Chronology GREGORIAN_PARIS = GregorianChronology.getInstance(PARIS); private static final Chronology GREGORIAN_MOSCOW = GregorianChronology.getInstance(MOSCOW); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private static final int OFFSET_PARIS = PARIS.getOffset(0L) / DateTimeConstants.MILLIS_PER_HOUR; private static final int OFFSET_MOSCOW = MOSCOW.getOffset(0L) / DateTimeConstants.MILLIS_PER_HOUR; private long MILLIS_OF_DAY = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY + MILLIS_OF_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalDateTime_Constructors.class); } public TestLocalDateTime_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(MOSCOW); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new LocalDateTime(2010, 6, 30, 1, 20), LocalDateTime.parse("2010-06-30T01:20")); assertEquals(new LocalDateTime(2010, 1, 2, 14, 50, 30, 432), LocalDateTime.parse("2010-002T14:50:30.432")); } public void testParse_formatter() throws Throwable { DateTimeFormatter f = DateTimeFormat.forPattern("yyyy--dd MM HH").withChronology(ISOChronology.getInstance(PARIS)); assertEquals(new LocalDateTime(2010, 6, 30, 13, 0), LocalDateTime.parse("2010--30 06 13", f)); } //----------------------------------------------------------------------- public void testFactory_fromCalendarFields() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalDateTime expected = new LocalDateTime(1970, 2, 3, 4, 5, 6, 7); assertEquals(expected, LocalDateTime.fromCalendarFields(cal)); } public void testFactory_fromCalendarFields_beforeYearZero1() throws Exception { GregorianCalendar cal = new GregorianCalendar(1, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDateTime expected = new LocalDateTime(0, 2, 3, 4, 5, 6, 7); assertEquals(expected, LocalDateTime.fromCalendarFields(cal)); } public void testFactory_fromCalendarFields_beforeYearZero3() throws Exception { GregorianCalendar cal = new GregorianCalendar(3, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDateTime expected = new LocalDateTime(-2, 2, 3, 4, 5, 6, 7); assertEquals(expected, LocalDateTime.fromCalendarFields(cal)); } public void testFactory_fromCalendarFields_null() throws Exception { try { LocalDateTime.fromCalendarFields((Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFactory_fromDateFields_after1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalDateTime expected = new LocalDateTime(1970, 2, 3, 4, 5 ,6, 7); assertEquals(expected, LocalDateTime.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_before1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1969, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalDateTime expected = new LocalDateTime(1969, 2, 3, 4, 5 ,6, 7); assertEquals(expected, LocalDateTime.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_beforeYearZero1() throws Exception { GregorianCalendar cal = new GregorianCalendar(1, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDateTime expected = new LocalDateTime(0, 2, 3, 4, 5, 6, 7); assertEquals(expected, LocalDateTime.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_beforeYearZero3() throws Exception { GregorianCalendar cal = new GregorianCalendar(3, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDateTime expected = new LocalDateTime(-2, 2, 3, 4, 5, 6, 7); assertEquals(expected, LocalDateTime.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_null() throws Exception { try { LocalDateTime.fromDateFields((Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor() throws Throwable { LocalDateTime test = new LocalDateTime(); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(test, LocalDateTime.now()); } //----------------------------------------------------------------------- public void testConstructor_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 0, 0, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris LocalDateTime test = new LocalDateTime(LONDON); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(8, test.getDayOfMonth()); assertEquals(23, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); assertEquals(test, LocalDateTime.now(LONDON)); test = new LocalDateTime(PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(0, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); assertEquals(test, LocalDateTime.now(PARIS)); } public void testConstructor_nullDateTimeZone() throws Throwable { LocalDateTime test = new LocalDateTime((DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_Chronology() throws Throwable { LocalDateTime test = new LocalDateTime(GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(test, LocalDateTime.now(GREGORIAN_PARIS)); } public void testConstructor_nullChronology() throws Throwable { LocalDateTime test = new LocalDateTime((Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_long1() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_long2() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME2); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); assertEquals(14 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(28, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_long1_DateTimeZone() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME1, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_long2_DateTimeZone() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME2, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); assertEquals(14 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(28, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_long_nullDateTimeZone() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME1, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_long1_Chronology() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME1, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_long2_Chronology() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME2, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); assertEquals(14 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(28, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_long_nullChronology() throws Throwable { LocalDateTime test = new LocalDateTime(TEST_TIME1, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_Object1() throws Throwable { Date date = new Date(TEST_TIME1); LocalDateTime test = new LocalDateTime(date); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_nullObject() throws Throwable { LocalDateTime test = new LocalDateTime((Object) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString1() throws Throwable { LocalDateTime test = new LocalDateTime("1972-04-06"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(0, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectString2() throws Throwable { LocalDateTime test = new LocalDateTime("1972-037"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(2, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(0, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectString3() throws Throwable { LocalDateTime test = new LocalDateTime("1972-04-06T10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString4() throws Throwable { LocalDateTime test = new LocalDateTime("1972-04-06T10:20"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectStringEx1() throws Throwable { try { new LocalDateTime("1970-04-06T+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx2() throws Throwable { try { new LocalDateTime("1970-04-06T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx3() throws Throwable { try { new LocalDateTime("T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx4() throws Throwable { try { new LocalDateTime("T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx5() throws Throwable { try { new LocalDateTime("10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx6() throws Throwable { try { new LocalDateTime("10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectLocalDateTime() throws Throwable { LocalDateTime dt = new LocalDateTime(1970, 5, 6, 10, 20, 30, 40, BUDDHIST_UTC); LocalDateTime test = new LocalDateTime(dt); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectLocalDate() throws Throwable { LocalDate date = new LocalDate(1970, 5, 6); try { new LocalDateTime(date); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectLocalTime() throws Throwable { LocalTime time = new LocalTime(10, 20, 30, 40); try { new LocalDateTime(time); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_Object_DateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); LocalDateTime test = new LocalDateTime(date, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_Object_DateTimeZoneMoscow() throws Throwable { LocalDateTime test = new LocalDateTime("1970-04-06T12:24:00", MOSCOW); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_Object_DateTimeZoneMoscowBadDateTime() throws Throwable { // 1981-03-31T23:59:59.999+03:00 followed by 1981-04-01T01:00:00.000+04:00 // 1981-09-30T23:59:59.999+04:00 followed by 1981-09-30T23:00:00.000+03:00 // when a DST non-existing time is passed in, it should still work (ie. zone ignored) LocalDateTime test = new LocalDateTime("1981-04-01T00:30:00", MOSCOW); // doesnt exist assertEquals(ISO_UTC, test.getChronology()); assertEquals(1981, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); assertEquals(0, test.getHourOfDay()); assertEquals(30, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_nullObject_DateTimeZone() throws Throwable { LocalDateTime test = new LocalDateTime((Object) null, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_Object_nullDateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); LocalDateTime test = new LocalDateTime(date, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_nullObject_nullDateTimeZone() throws Throwable { LocalDateTime test = new LocalDateTime((Object) null, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); LocalDateTime test = new LocalDateTime(date, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_Object_Chronology_crossChronology() throws Throwable { LocalDateTime input = new LocalDateTime(1970, 4, 6, 12, 30, 0, 0, ISO_UTC); LocalDateTime test = new LocalDateTime(input, BUDDHIST_UTC); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(30, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_Object_ChronologyMoscow() throws Throwable { LocalDateTime test = new LocalDateTime("1970-04-06T12:24:00", GREGORIAN_MOSCOW); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_Object_ChronologyMoscowBadDateTime() throws Throwable { // 1981-03-31T23:59:59.999+03:00 followed by 1981-04-01T01:00:00.000+04:00 // 1981-09-30T23:59:59.999+04:00 followed by 1981-09-30T23:00:00.000+03:00 // when a DST non-existing time is passed in, it should still work (ie. zone ignored) LocalDateTime test = new LocalDateTime("1981-04-01T00:30:00", GREGORIAN_MOSCOW); // doesnt exist assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1981, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); assertEquals(0, test.getHourOfDay()); assertEquals(30, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_nullObject_Chronology() throws Throwable { LocalDateTime test = new LocalDateTime((Object) null, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); LocalDateTime test = new LocalDateTime(date, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(12 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_nullObject_nullChronology() throws Throwable { LocalDateTime test = new LocalDateTime((Object) null, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10 + OFFSET_MOSCOW, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_int_int_int_int_int() throws Throwable { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_int_int_int_int_int_int() throws Throwable { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_int_int_int_int_int_int_int() throws Throwable { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new LocalDateTime(Integer.MIN_VALUE, 6, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(Integer.MAX_VALUE, 6, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 0, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 13, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 6, 0, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 6, 31, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} new LocalDateTime(2005, 7, 31, 10, 20, 30, 40); try { new LocalDateTime(2005, 7, 32, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int_Chronology() throws Throwable { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); // PARIS has no effect assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new LocalDateTime(Integer.MIN_VALUE, 6, 9, 10, 20, 30, 40, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(Integer.MAX_VALUE, 6, 9, 10, 20, 30, 40, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 0, 9, 10, 20, 30, 40, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 13, 9, 10, 20, 30, 40, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 6, 0, 10, 20, 30, 40, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 6, 31, 10, 20, 30, 40, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} new LocalDateTime(2005, 7, 31, 10, 20, 30, 40, GREGORIAN_PARIS); try { new LocalDateTime(2005, 7, 32, 10, 20, 30, 40, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int_nullChronology() throws Throwable { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestPeriodType.java0000644000175000017500000013276411667412004023515 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a JUnit test for PeriodType. * * @author Stephen Colebourne */ public class TestPeriodType extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPeriodType.class); } public TestPeriodType(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- private void assertEqualsAfterSerialization(PeriodType type) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(type); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); PeriodType result = (PeriodType) ois.readObject(); ois.close(); assertEquals(type, result); } private void assertSameAfterSerialization(PeriodType type) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(type); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); PeriodType result = (PeriodType) ois.readObject(); ois.close(); assertEquals(type, result); } //----------------------------------------------------------------------- public void testStandard() throws Exception { PeriodType type = PeriodType.standard(); assertEquals(8, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.weeks(), type.getFieldType(2)); assertEquals(DurationFieldType.days(), type.getFieldType(3)); assertEquals(DurationFieldType.hours(), type.getFieldType(4)); assertEquals(DurationFieldType.minutes(), type.getFieldType(5)); assertEquals(DurationFieldType.seconds(), type.getFieldType(6)); assertEquals(DurationFieldType.millis(), type.getFieldType(7)); assertEquals("Standard", type.getName()); assertEquals("PeriodType[Standard]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.standard()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testYearMonthDayTime() throws Exception { PeriodType type = PeriodType.yearMonthDayTime(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.days(), type.getFieldType(2)); assertEquals(DurationFieldType.hours(), type.getFieldType(3)); assertEquals(DurationFieldType.minutes(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals("YearMonthDayTime", type.getName()); assertEquals("PeriodType[YearMonthDayTime]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.yearMonthDayTime()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.yearMonthDayTime().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testYearMonthDay() throws Exception { PeriodType type = PeriodType.yearMonthDay(); assertEquals(3, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.days(), type.getFieldType(2)); assertEquals("YearMonthDay", type.getName()); assertEquals("PeriodType[YearMonthDay]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.yearMonthDay()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.yearMonthDay().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testYearWeekDayTime() throws Exception { PeriodType type = PeriodType.yearWeekDayTime(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.weeks(), type.getFieldType(1)); assertEquals(DurationFieldType.days(), type.getFieldType(2)); assertEquals(DurationFieldType.hours(), type.getFieldType(3)); assertEquals(DurationFieldType.minutes(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals("YearWeekDayTime", type.getName()); assertEquals("PeriodType[YearWeekDayTime]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.yearWeekDayTime()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.yearWeekDayTime().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testYearWeekDay() throws Exception { PeriodType type = PeriodType.yearWeekDay(); assertEquals(3, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.weeks(), type.getFieldType(1)); assertEquals(DurationFieldType.days(), type.getFieldType(2)); assertEquals("YearWeekDay", type.getName()); assertEquals("PeriodType[YearWeekDay]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.yearWeekDay()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.yearWeekDay().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testYearDayTime() throws Exception { PeriodType type = PeriodType.yearDayTime(); assertEquals(6, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.days(), type.getFieldType(1)); assertEquals(DurationFieldType.hours(), type.getFieldType(2)); assertEquals(DurationFieldType.minutes(), type.getFieldType(3)); assertEquals(DurationFieldType.seconds(), type.getFieldType(4)); assertEquals(DurationFieldType.millis(), type.getFieldType(5)); assertEquals("YearDayTime", type.getName()); assertEquals("PeriodType[YearDayTime]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.yearDayTime()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.yearDayTime().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testYearDay() throws Exception { PeriodType type = PeriodType.yearDay(); assertEquals(2, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.days(), type.getFieldType(1)); assertEquals("YearDay", type.getName()); assertEquals("PeriodType[YearDay]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.yearDay()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.yearDay().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testDayTime() throws Exception { PeriodType type = PeriodType.dayTime(); assertEquals(5, type.size()); assertEquals(DurationFieldType.days(), type.getFieldType(0)); assertEquals(DurationFieldType.hours(), type.getFieldType(1)); assertEquals(DurationFieldType.minutes(), type.getFieldType(2)); assertEquals(DurationFieldType.seconds(), type.getFieldType(3)); assertEquals(DurationFieldType.millis(), type.getFieldType(4)); assertEquals("DayTime", type.getName()); assertEquals("PeriodType[DayTime]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.dayTime()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.dayTime().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testTime() throws Exception { PeriodType type = PeriodType.time(); assertEquals(4, type.size()); assertEquals(DurationFieldType.hours(), type.getFieldType(0)); assertEquals(DurationFieldType.minutes(), type.getFieldType(1)); assertEquals(DurationFieldType.seconds(), type.getFieldType(2)); assertEquals(DurationFieldType.millis(), type.getFieldType(3)); assertEquals("Time", type.getName()); assertEquals("PeriodType[Time]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.time()); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.time().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testYears() throws Exception { PeriodType type = PeriodType.years(); assertEquals(1, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals("Years", type.getName()); assertEquals("PeriodType[Years]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.years()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.years().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testMonths() throws Exception { PeriodType type = PeriodType.months(); assertEquals(1, type.size()); assertEquals(DurationFieldType.months(), type.getFieldType(0)); assertEquals("Months", type.getName()); assertEquals("PeriodType[Months]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.months()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.months().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testWeeks() throws Exception { PeriodType type = PeriodType.weeks(); assertEquals(1, type.size()); assertEquals(DurationFieldType.weeks(), type.getFieldType(0)); assertEquals("Weeks", type.getName()); assertEquals("PeriodType[Weeks]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.weeks()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.weeks().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testDays() throws Exception { PeriodType type = PeriodType.days(); assertEquals(1, type.size()); assertEquals(DurationFieldType.days(), type.getFieldType(0)); assertEquals("Days", type.getName()); assertEquals("PeriodType[Days]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.days()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.days().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testHours() throws Exception { PeriodType type = PeriodType.hours(); assertEquals(1, type.size()); assertEquals(DurationFieldType.hours(), type.getFieldType(0)); assertEquals("Hours", type.getName()); assertEquals("PeriodType[Hours]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.hours()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.hours().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testMinutes() throws Exception { PeriodType type = PeriodType.minutes(); assertEquals(1, type.size()); assertEquals(DurationFieldType.minutes(), type.getFieldType(0)); assertEquals("Minutes", type.getName()); assertEquals("PeriodType[Minutes]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.minutes()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.minutes().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testSeconds() throws Exception { PeriodType type = PeriodType.seconds(); assertEquals(1, type.size()); assertEquals(DurationFieldType.seconds(), type.getFieldType(0)); assertEquals("Seconds", type.getName()); assertEquals("PeriodType[Seconds]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.seconds()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.seconds().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testMillis() throws Exception { PeriodType type = PeriodType.millis(); assertEquals(1, type.size()); assertEquals(DurationFieldType.millis(), type.getFieldType(0)); assertEquals("Millis", type.getName()); assertEquals("PeriodType[Millis]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.millis()); assertEquals(false, type.equals(PeriodType.standard())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.millis().hashCode()); assertEquals(false, type.hashCode() == PeriodType.standard().hashCode()); assertSameAfterSerialization(type); } //----------------------------------------------------------------------- public void testForFields1() throws Exception { PeriodType type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.years(), }); assertSame(PeriodType.years(), type); type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.months(), }); assertSame(PeriodType.months(), type); type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.weeks(), }); assertSame(PeriodType.weeks(), type); type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.days(), }); assertSame(PeriodType.days(), type); type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.hours(), }); assertSame(PeriodType.hours(), type); type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.minutes(), }); assertSame(PeriodType.minutes(), type); type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.seconds(), }); assertSame(PeriodType.seconds(), type); type = PeriodType.forFields(new DurationFieldType[] { DurationFieldType.millis(), }); assertSame(PeriodType.millis(), type); } public void testForFields2() throws Exception { DurationFieldType[] types = new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.hours(), }; PeriodType type = PeriodType.forFields(types); assertEquals(2, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.hours(), type.getFieldType(1)); assertEquals("StandardNoMonthsNoWeeksNoDaysNoMinutesNoSecondsNoMillis", type.getName()); assertEquals("PeriodType[StandardNoMonthsNoWeeksNoDaysNoMinutesNoSecondsNoMillis]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.forFields(types)); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.forFields(types).hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } public void testForFields3() throws Exception { DurationFieldType[] types = new DurationFieldType[] { DurationFieldType.months(), DurationFieldType.weeks(), }; PeriodType type = PeriodType.forFields(types); assertEquals(2, type.size()); assertEquals(DurationFieldType.months(), type.getFieldType(0)); assertEquals(DurationFieldType.weeks(), type.getFieldType(1)); assertEquals("StandardNoYearsNoDaysNoHoursNoMinutesNoSecondsNoMillis", type.getName()); assertEquals("PeriodType[StandardNoYearsNoDaysNoHoursNoMinutesNoSecondsNoMillis]", type.toString()); assertEquals(true, type.equals(type)); assertEquals(true, type == PeriodType.forFields(types)); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.forFields(types).hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertSameAfterSerialization(type); } public void testForFields4() throws Exception { DurationFieldType[] types = new DurationFieldType[] { DurationFieldType.weeks(), DurationFieldType.days(), // adding this makes this test unique, so cache is not pre-populated DurationFieldType.months(), }; DurationFieldType[] types2 = new DurationFieldType[] { DurationFieldType.months(), DurationFieldType.days(), DurationFieldType.weeks(), }; PeriodType type = PeriodType.forFields(types); PeriodType type2 = PeriodType.forFields(types2); assertEquals(true, type == type2); } public void testForFields5() throws Exception { DurationFieldType[] types = new DurationFieldType[] { DurationFieldType.centuries(), DurationFieldType.months(), }; try { PeriodType.forFields(types); fail(); } catch (IllegalArgumentException ex) { // expected } try { PeriodType.forFields(types); // repeated for test coverage of cache fail(); } catch (IllegalArgumentException ex) { // expected } } public void testForFields6() throws Exception { DurationFieldType[] types = null; try { PeriodType.forFields(types); fail(); } catch (IllegalArgumentException ex) { // expected } types = new DurationFieldType[0]; try { PeriodType.forFields(types); fail(); } catch (IllegalArgumentException ex) { // expected } types = new DurationFieldType[] { null, DurationFieldType.months(), }; try { PeriodType.forFields(types); fail(); } catch (IllegalArgumentException ex) { // expected } types = new DurationFieldType[] { DurationFieldType.months(), null, }; try { PeriodType.forFields(types); fail(); } catch (IllegalArgumentException ex) { // expected } } // ensure hash key distribution public void testForFields7() throws Exception { DurationFieldType[] types = new DurationFieldType[] { DurationFieldType.weeks(), DurationFieldType.months(), }; DurationFieldType[] types2 = new DurationFieldType[] { DurationFieldType.seconds(), }; PeriodType type = PeriodType.forFields(types); PeriodType type2 = PeriodType.forFields(types2); assertEquals(false, type == type2); assertEquals(false, type.equals(type2)); assertEquals(false, type.hashCode() == type2.hashCode()); } //----------------------------------------------------------------------- public void testMaskYears() throws Exception { PeriodType type = PeriodType.standard().withYearsRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.months(), type.getFieldType(0)); assertEquals(DurationFieldType.weeks(), type.getFieldType(1)); assertEquals(DurationFieldType.days(), type.getFieldType(2)); assertEquals(DurationFieldType.hours(), type.getFieldType(3)); assertEquals(DurationFieldType.minutes(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withYearsRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withYearsRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoYears", type.getName()); assertEquals("PeriodType[StandardNoYears]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskMonths() throws Exception { PeriodType type = PeriodType.standard().withMonthsRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.weeks(), type.getFieldType(1)); assertEquals(DurationFieldType.days(), type.getFieldType(2)); assertEquals(DurationFieldType.hours(), type.getFieldType(3)); assertEquals(DurationFieldType.minutes(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withMonthsRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withMonthsRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoMonths", type.getName()); assertEquals("PeriodType[StandardNoMonths]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskWeeks() throws Exception { PeriodType type = PeriodType.standard().withWeeksRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.days(), type.getFieldType(2)); assertEquals(DurationFieldType.hours(), type.getFieldType(3)); assertEquals(DurationFieldType.minutes(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withWeeksRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withWeeksRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoWeeks", type.getName()); assertEquals("PeriodType[StandardNoWeeks]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskDays() throws Exception { PeriodType type = PeriodType.standard().withDaysRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.weeks(), type.getFieldType(2)); assertEquals(DurationFieldType.hours(), type.getFieldType(3)); assertEquals(DurationFieldType.minutes(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withDaysRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withDaysRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoDays", type.getName()); assertEquals("PeriodType[StandardNoDays]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskHours() throws Exception { PeriodType type = PeriodType.standard().withHoursRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.weeks(), type.getFieldType(2)); assertEquals(DurationFieldType.days(), type.getFieldType(3)); assertEquals(DurationFieldType.minutes(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withHoursRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withHoursRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoHours", type.getName()); assertEquals("PeriodType[StandardNoHours]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskMinutes() throws Exception { PeriodType type = PeriodType.standard().withMinutesRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.weeks(), type.getFieldType(2)); assertEquals(DurationFieldType.days(), type.getFieldType(3)); assertEquals(DurationFieldType.hours(), type.getFieldType(4)); assertEquals(DurationFieldType.seconds(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withMinutesRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withMinutesRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoMinutes", type.getName()); assertEquals("PeriodType[StandardNoMinutes]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskSeconds() throws Exception { PeriodType type = PeriodType.standard().withSecondsRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.weeks(), type.getFieldType(2)); assertEquals(DurationFieldType.days(), type.getFieldType(3)); assertEquals(DurationFieldType.hours(), type.getFieldType(4)); assertEquals(DurationFieldType.minutes(), type.getFieldType(5)); assertEquals(DurationFieldType.millis(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withSecondsRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withSecondsRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoSeconds", type.getName()); assertEquals("PeriodType[StandardNoSeconds]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskMillis() throws Exception { PeriodType type = PeriodType.standard().withMillisRemoved(); assertEquals(7, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.weeks(), type.getFieldType(2)); assertEquals(DurationFieldType.days(), type.getFieldType(3)); assertEquals(DurationFieldType.hours(), type.getFieldType(4)); assertEquals(DurationFieldType.minutes(), type.getFieldType(5)); assertEquals(DurationFieldType.seconds(), type.getFieldType(6)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withMillisRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withMillisRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoMillis", type.getName()); assertEquals("PeriodType[StandardNoMillis]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskHoursMinutesSeconds() throws Exception { PeriodType type = PeriodType.standard().withHoursRemoved().withMinutesRemoved().withSecondsRemoved(); assertEquals(5, type.size()); assertEquals(DurationFieldType.years(), type.getFieldType(0)); assertEquals(DurationFieldType.months(), type.getFieldType(1)); assertEquals(DurationFieldType.weeks(), type.getFieldType(2)); assertEquals(DurationFieldType.days(), type.getFieldType(3)); assertEquals(DurationFieldType.millis(), type.getFieldType(4)); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.standard().withHoursRemoved().withMinutesRemoved().withSecondsRemoved())); assertEquals(false, type.equals(PeriodType.millis())); assertEquals(true, type.hashCode() == type.hashCode()); assertEquals(true, type.hashCode() == PeriodType.standard().withHoursRemoved().withMinutesRemoved().withSecondsRemoved().hashCode()); assertEquals(false, type.hashCode() == PeriodType.millis().hashCode()); assertEquals("StandardNoHoursNoMinutesNoSeconds", type.getName()); assertEquals("PeriodType[StandardNoHoursNoMinutesNoSeconds]", type.toString()); assertEqualsAfterSerialization(type); } //----------------------------------------------------------------------- public void testMaskTwice1() throws Exception { PeriodType type = PeriodType.standard().withYearsRemoved(); PeriodType type2 = type.withYearsRemoved(); assertEquals(true, type == type2); type = PeriodType.standard().withMonthsRemoved(); type2 = type.withMonthsRemoved(); assertEquals(true, type == type2); type = PeriodType.standard().withWeeksRemoved(); type2 = type.withWeeksRemoved(); assertEquals(true, type == type2); type = PeriodType.standard().withDaysRemoved(); type2 = type.withDaysRemoved(); assertEquals(true, type == type2); type = PeriodType.standard().withHoursRemoved(); type2 = type.withHoursRemoved(); assertEquals(true, type == type2); type = PeriodType.standard().withMinutesRemoved(); type2 = type.withMinutesRemoved(); assertEquals(true, type == type2); type = PeriodType.standard().withSecondsRemoved(); type2 = type.withSecondsRemoved(); assertEquals(true, type == type2); type = PeriodType.standard().withMillisRemoved(); type2 = type.withMillisRemoved(); assertEquals(true, type == type2); } //----------------------------------------------------------------------- public void testMaskTwice2() throws Exception { PeriodType type = PeriodType.dayTime(); PeriodType type2 = type.withYearsRemoved(); assertEquals(true, type == type2); type = PeriodType.dayTime(); type2 = type.withMonthsRemoved(); assertEquals(true, type == type2); type = PeriodType.dayTime(); type2 = type.withWeeksRemoved(); assertEquals(true, type == type2); type = PeriodType.millis(); type2 = type.withDaysRemoved(); assertEquals(true, type == type2); type = PeriodType.millis(); type2 = type.withHoursRemoved(); assertEquals(true, type == type2); type = PeriodType.millis(); type2 = type.withMinutesRemoved(); assertEquals(true, type == type2); type = PeriodType.millis(); type2 = type.withSecondsRemoved(); assertEquals(true, type == type2); } //----------------------------------------------------------------------- public void testEquals() throws Exception { PeriodType type = PeriodType.dayTime().withMillisRemoved(); assertEquals(true, type.equals(type)); assertEquals(true, type.equals(PeriodType.dayTime().withMillisRemoved())); assertEquals(false, type.equals(null)); assertEquals(false, type.equals("")); } public void testHashCode() throws Exception { PeriodType type = PeriodType.dayTime().withMillisRemoved(); assertEquals(type.hashCode(), type.hashCode()); } //----------------------------------------------------------------------- public void testIsSupported() throws Exception { PeriodType type = PeriodType.dayTime().withMillisRemoved(); assertEquals(false, type.isSupported(DurationFieldType.years())); assertEquals(false, type.isSupported(DurationFieldType.months())); assertEquals(false, type.isSupported(DurationFieldType.weeks())); assertEquals(true, type.isSupported(DurationFieldType.days())); assertEquals(true, type.isSupported(DurationFieldType.hours())); assertEquals(true, type.isSupported(DurationFieldType.minutes())); assertEquals(true, type.isSupported(DurationFieldType.seconds())); assertEquals(false, type.isSupported(DurationFieldType.millis())); } //----------------------------------------------------------------------- public void testIndexOf() throws Exception { PeriodType type = PeriodType.dayTime().withMillisRemoved(); assertEquals(-1, type.indexOf(DurationFieldType.years())); assertEquals(-1, type.indexOf(DurationFieldType.months())); assertEquals(-1, type.indexOf(DurationFieldType.weeks())); assertEquals(0, type.indexOf(DurationFieldType.days())); assertEquals(1, type.indexOf(DurationFieldType.hours())); assertEquals(2, type.indexOf(DurationFieldType.minutes())); assertEquals(3, type.indexOf(DurationFieldType.seconds())); assertEquals(-1, type.indexOf(DurationFieldType.millis())); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalDate_Constructors.java0000644000175000017500000006042012072543747026050 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for LocalDate. * * @author Stephen Colebourne */ public class TestLocalDate_Constructors extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private static final Chronology GREGORIAN_UTC = GregorianChronology.getInstanceUTC(); private static final Chronology GREGORIAN_PARIS = GregorianChronology.getInstance(PARIS); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME1_ROUNDED = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalDate_Constructors.class); } public TestLocalDate_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new LocalDate(2010, 6, 30), LocalDate.parse("2010-06-30")); assertEquals(new LocalDate(2010, 1, 2), LocalDate.parse("2010-002")); } public void testParse_formatter() throws Throwable { DateTimeFormatter f = DateTimeFormat.forPattern("yyyy--dd MM").withChronology(ISOChronology.getInstance(PARIS)); assertEquals(new LocalDate(2010, 6, 30), LocalDate.parse("2010--30 06", f)); } //----------------------------------------------------------------------- public void testFactory_fromCalendarFields() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalDate expected = new LocalDate(1970, 2, 3); assertEquals(expected, LocalDate.fromCalendarFields(cal)); } public void testFactory_fromCalendarFields_beforeYearZero1() throws Exception { GregorianCalendar cal = new GregorianCalendar(1, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDate expected = new LocalDate(0, 2, 3); assertEquals(expected, LocalDate.fromCalendarFields(cal)); } public void testFactory_fromCalendarFields_beforeYearZero3() throws Exception { GregorianCalendar cal = new GregorianCalendar(3, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDate expected = new LocalDate(-2, 2, 3); assertEquals(expected, LocalDate.fromCalendarFields(cal)); } public void testFactory_fromCalendarFields_null() throws Exception { try { LocalDate.fromCalendarFields((Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFactory_fromDateFields_after1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalDate expected = new LocalDate(1970, 2, 3); assertEquals(expected, LocalDate.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_before1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1969, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalDate expected = new LocalDate(1969, 2, 3); assertEquals(expected, LocalDate.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_beforeYearZero1() throws Exception { GregorianCalendar cal = new GregorianCalendar(1, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDate expected = new LocalDate(0, 2, 3); assertEquals(expected, LocalDate.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_beforeYearZero3() throws Exception { GregorianCalendar cal = new GregorianCalendar(3, 1, 3, 4, 5, 6); cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.MILLISECOND, 7); LocalDate expected = new LocalDate(-2, 2, 3); assertEquals(expected, LocalDate.fromDateFields(cal.getTime())); } public void testFactory_fromDateFields_null() throws Exception { try { LocalDate.fromDateFields((Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor() throws Throwable { LocalDate test = new LocalDate(); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(test, LocalDate.now()); } public void testConstructor_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 0, 0, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris LocalDate test = new LocalDate(LONDON); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(8, test.getDayOfMonth()); assertEquals(test, LocalDate.now(LONDON)); test = new LocalDate(PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(test, LocalDate.now(PARIS)); } public void testConstructor_nullDateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 0, 0, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris LocalDate test = new LocalDate((DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(8, test.getDayOfMonth()); } public void testConstructor_Chronology() throws Throwable { LocalDate test = new LocalDate(GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(test, LocalDate.now(GREGORIAN_PARIS)); } public void testConstructor_nullChronology() throws Throwable { LocalDate test = new LocalDate((Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } //----------------------------------------------------------------------- public void testConstructor_long1() throws Throwable { LocalDate test = new LocalDate(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_long2() throws Throwable { LocalDate test = new LocalDate(TEST_TIME2); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); } public void testConstructor_long1_DateTimeZone() throws Throwable { LocalDate test = new LocalDate(TEST_TIME1, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); assertEquals(TEST_TIME1_ROUNDED, test.getLocalMillis()); } public void testConstructor_long2_DateTimeZone() throws Throwable { LocalDate test = new LocalDate(TEST_TIME2, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); } public void testConstructor_long3_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2006, 6, 9, 0, 0, 0, 0, PARIS); DateTime dtUTC = new DateTime(2006, 6, 9, 0, 0, 0, 0, DateTimeZone.UTC); LocalDate test = new LocalDate(dt.getMillis(), PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2006, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(dtUTC.getMillis(), test.getLocalMillis()); } public void testConstructor_long4_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2006, 6, 9, 23, 59, 59, 999, PARIS); DateTime dtUTC = new DateTime(2006, 6, 9, 0, 0, 0, 0, DateTimeZone.UTC); LocalDate test = new LocalDate(dt.getMillis(), PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2006, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(dtUTC.getMillis(), test.getLocalMillis()); } public void testConstructor_long_nullDateTimeZone() throws Throwable { LocalDate test = new LocalDate(TEST_TIME1, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_long1_Chronology() throws Throwable { LocalDate test = new LocalDate(TEST_TIME1, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_long2_Chronology() throws Throwable { LocalDate test = new LocalDate(TEST_TIME2, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); } public void testConstructor_long_nullChronology() throws Throwable { LocalDate test = new LocalDate(TEST_TIME1, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } //----------------------------------------------------------------------- public void testConstructor_Object1() throws Throwable { Date date = new Date(TEST_TIME1); LocalDate test = new LocalDate(date); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_nullObject() throws Throwable { LocalDate test = new LocalDate((Object) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } public void testConstructor_ObjectString1() throws Throwable { LocalDate test = new LocalDate("1972-04-06"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_ObjectString2() throws Throwable { LocalDate test = new LocalDate("1972-037"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(2, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_ObjectString3() throws Throwable { LocalDate test = new LocalDate("1972-02"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(2, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); } public void testConstructor_ObjectStringEx1() throws Throwable { try { new LocalDate("1970-04-06T+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx2() throws Throwable { try { new LocalDate("1970-04-06T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx3() throws Throwable { try { new LocalDate("1970-04-06T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx4() throws Throwable { try { new LocalDate("T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx5() throws Throwable { try { new LocalDate("T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx6() throws Throwable { try { new LocalDate("10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx7() throws Throwable { try { new LocalDate("10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectLocalDate() throws Throwable { LocalDate date = new LocalDate(1970, 4, 6, BUDDHIST_UTC); LocalDate test = new LocalDate(date); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_ObjectLocalTime() throws Throwable { LocalTime time = new LocalTime(10, 20, 30, 40, BUDDHIST_UTC); try { new LocalDate(time); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectLocalDateTime() throws Throwable { LocalDateTime dt = new LocalDateTime(1970, 5, 6, 10, 20, 30, 40, BUDDHIST_UTC); LocalDate test = new LocalDate(dt); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } @SuppressWarnings("deprecation") public void testConstructor_ObjectYearMonthDay() throws Throwable { YearMonthDay date = new YearMonthDay(1970, 4, 6, BUDDHIST_UTC); LocalDate test = new LocalDate(date); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } //----------------------------------------------------------------------- public void testConstructor_Object_DateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); LocalDate test = new LocalDate(date, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_nullObject_DateTimeZone() throws Throwable { LocalDate test = new LocalDate((Object) null, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } public void testConstructor_Object_nullDateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); LocalDate test = new LocalDate(date, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_nullObject_nullDateTimeZone() throws Throwable { LocalDate test = new LocalDate((Object) null, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); LocalDate test = new LocalDate(date, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_Object_Chronology_crossChronology() throws Throwable { LocalDate input = new LocalDate(1970, 4, 6, ISO_UTC); LocalDate test = new LocalDate(input, BUDDHIST_UTC); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_nullObject_Chronology() throws Throwable { LocalDate test = new LocalDate((Object) null, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); LocalDate test = new LocalDate(date, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_nullObject_nullChronology() throws Throwable { LocalDate test = new LocalDate((Object) null, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } //----------------------------------------------------------------------- public void testConstructor_int_int_int() throws Throwable { LocalDate test = new LocalDate(1970, 6, 9); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); try { new LocalDate(Integer.MIN_VALUE, 6, 9); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(Integer.MAX_VALUE, 6, 9); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 0, 9); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 13, 9); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 6, 0); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 6, 31); fail(); } catch (IllegalArgumentException ex) {} new LocalDate(1970, 7, 31); try { new LocalDate(1970, 7, 32); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int_Chronology() throws Throwable { LocalDate test = new LocalDate(1970, 6, 9, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); try { new LocalDate(Integer.MIN_VALUE, 6, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(Integer.MAX_VALUE, 6, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 0, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 13, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 6, 0, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDate(1970, 6, 31, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} new LocalDate(1970, 7, 31, GREGORIAN_PARIS); try { new LocalDate(1970, 7, 32, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int_nullChronology() throws Throwable { LocalDate test = new LocalDate(1970, 6, 9, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestDateTime_Constructors.java0000644000175000017500000007607611616003375025721 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Date; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.MockZeroNullIntegerConverter; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for DateTime. * * @author Stephen Colebourne */ public class TestDateTime_Constructors extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTime_Constructors.class); } public TestDateTime_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); java.util.TimeZone.setDefault(LONDON.toTimeZone()); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); java.util.TimeZone.setDefault(zone.toTimeZone()); Locale.setDefault(locale); zone = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- /** * Test now () */ public void test_now() throws Throwable { DateTime test = DateTime.now(); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test now (DateTimeZone) */ public void test_now_DateTimeZone() throws Throwable { DateTime test = DateTime.now(PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test now (DateTimeZone=null) */ public void test_now_nullDateTimeZone() throws Throwable { try { DateTime.now((DateTimeZone) null); fail(); } catch (NullPointerException ex) {} } /** * Test now (Chronology) */ public void test_now_Chronology() throws Throwable { DateTime test = DateTime.now(GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test now (Chronology=null) */ public void test_now_nullChronology() throws Throwable { try { DateTime.now((Chronology) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new DateTime(2010, 6, 30, 1, 20, ISOChronology.getInstance(DateTimeZone.forOffsetHours(2))), DateTime.parse("2010-06-30T01:20+02:00")); assertEquals(new DateTime(2010, 1, 2, 14, 50, ISOChronology.getInstance(LONDON)), DateTime.parse("2010-002T14:50")); } public void testParse_formatter() throws Throwable { DateTimeFormatter f = DateTimeFormat.forPattern("yyyy--dd MM HH").withChronology(ISOChronology.getInstance(PARIS)); assertEquals(new DateTime(2010, 6, 30, 13, 0, ISOChronology.getInstance(PARIS)), DateTime.parse("2010--30 06 13", f)); } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstructor() throws Throwable { DateTime test = new DateTime(); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (DateTimeZone) */ public void testConstructor_DateTimeZone() throws Throwable { DateTime test = new DateTime(PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (DateTimeZone=null) */ public void testConstructor_nullDateTimeZone() throws Throwable { DateTime test = new DateTime((DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Chronology) */ public void testConstructor_Chronology() throws Throwable { DateTime test = new DateTime(GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Chronology=null) */ public void testConstructor_nullChronology() throws Throwable { DateTime test = new DateTime((Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (long) */ public void testConstructor_long1() throws Throwable { DateTime test = new DateTime(TEST_TIME1); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long) */ public void testConstructor_long2() throws Throwable { DateTime test = new DateTime(TEST_TIME2); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME2, test.getMillis()); } /** * Test constructor (long, DateTimeZone) */ public void testConstructor_long1_DateTimeZone() throws Throwable { DateTime test = new DateTime(TEST_TIME1, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long, DateTimeZone) */ public void testConstructor_long2_DateTimeZone() throws Throwable { DateTime test = new DateTime(TEST_TIME2, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME2, test.getMillis()); } /** * Test constructor (long, DateTimeZone=null) */ public void testConstructor_long_nullDateTimeZone() throws Throwable { DateTime test = new DateTime(TEST_TIME1, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long1_Chronology() throws Throwable { DateTime test = new DateTime(TEST_TIME1, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long2_Chronology() throws Throwable { DateTime test = new DateTime(TEST_TIME2, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME2, test.getMillis()); } /** * Test constructor (long, Chronology=null) */ public void testConstructor_long_nullChronology() throws Throwable { DateTime test = new DateTime(TEST_TIME1, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (Object) */ public void testConstructor_Object() throws Throwable { Date date = new Date(TEST_TIME1); DateTime test = new DateTime(date); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object) */ public void testConstructor_invalidObject() throws Throwable { try { new DateTime(new Object()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null) */ public void testConstructor_nullObject() throws Throwable { DateTime test = new DateTime((Object) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object=null) */ public void testConstructor_badconverterObject() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); DateTime test = new DateTime(new Integer(0)); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } public void testConstructor_ObjectString1() throws Throwable { DateTime test = new DateTime("1972-12-03"); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); assertEquals(0, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectString2() throws Throwable { DateTime test = new DateTime("2006-06-03T+14:00"); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(2006, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(2, test.getDayOfMonth()); // timezone assertEquals(11, test.getHourOfDay()); // test zone is +1, so shift back (14 - 1) hours from midnight assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectString3() throws Throwable { DateTime test = new DateTime("1972-12-03T10:20:30.040"); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString4() throws Throwable { DateTime test = new DateTime("2006-06-03T10:20:30.040+14:00"); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(2006, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(2, test.getDayOfMonth()); // timezone assertEquals(21, test.getHourOfDay()); // test zone is +1, so shift back (14 - 1) hours from 10am assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString5() throws Throwable { DateTime test = new DateTime("T10:20:30.040"); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(1, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString6() throws Throwable { DateTime test = new DateTime("T10:20:30.040+14:00"); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(1969, test.getYear()); // timezone assertEquals(12, test.getMonthOfYear()); // timezone assertEquals(31, test.getDayOfMonth()); // timezone assertEquals(21, test.getHourOfDay()); // test zone is +1, so shift back (14 - 1) hours from 10am assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString7() throws Throwable { DateTime test = new DateTime("10"); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(10, test.getYear()); assertEquals(1, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); assertEquals(0, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectStringEx1() throws Throwable { try { new DateTime("10:20:30.040"); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testConstructor_ObjectStringEx2() throws Throwable { try { new DateTime("10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_Object_DateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); DateTime test = new DateTime(date, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_invalidObject_DateTimeZone() throws Throwable { try { new DateTime(new Object(), PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null, DateTimeZone) */ public void testConstructor_nullObject_DateTimeZone() throws Throwable { DateTime test = new DateTime((Object) null, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, DateTimeZone=null) */ public void testConstructor_Object_nullDateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); DateTime test = new DateTime(date, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object=null, DateTimeZone=null) */ public void testConstructor_nullObject_nullDateTimeZone() throws Throwable { DateTime test = new DateTime((Object) null, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_badconverterObject_DateTimeZone() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); DateTime test = new DateTime(new Integer(0), GregorianChronology.getInstance()); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } /** * Test constructor (Object, Chronology) */ public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); DateTime test = new DateTime(date, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object, Chronology) */ public void testConstructor_invalidObject_Chronology() throws Throwable { try { new DateTime(new Object(), GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null, Chronology) */ public void testConstructor_nullObject_Chronology() throws Throwable { DateTime test = new DateTime((Object) null, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, Chronology=null) */ public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); DateTime test = new DateTime(date, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object=null, Chronology=null) */ public void testConstructor_nullObject_nullChronology() throws Throwable { DateTime test = new DateTime((Object) null, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, Chronology) */ public void testConstructor_badconverterObject_Chronology() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); DateTime test = new DateTime(new Integer(0), GregorianChronology.getInstance()); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } //----------------------------------------------------------------------- /** * Test constructor (int, int, int, int, int) */ public void testConstructor_int_int_int_int_int() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(LONDON, test.getZone()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, DateTimeZone) */ public void testConstructor_int_int_int_int_int_DateTimeZone() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 2, 0, PARIS); // +02:00 assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, DateTimeZone=null) */ public void testConstructor_int_int_int_int_int_nullDateTimeZone() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, (DateTimeZone) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, Chronology) */ public void testConstructor_int_int_int_int_int_Chronology() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, GregorianChronology.getInstance()); // +01:00 assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, Chronology=null) */ public void testConstructor_int_int_int_int_int_nullChronology() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, (Chronology) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (int, int, int, int, int, int) */ public void testConstructor_int_int_int_int_int_int() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(LONDON, test.getZone()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, int, DateTimeZone) */ public void testConstructor_int_int_int_int_int_int_DateTimeZone() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 2, 0, 0, PARIS); // +02:00 assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, int, DateTimeZone=null) */ public void testConstructor_int_int_int_int_int_int_nullDateTimeZone() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, (DateTimeZone) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, int, Chronology) */ public void testConstructor_int_int_int_int_int_int_Chronology() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, GregorianChronology.getInstance()); // +01:00 assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, int, int, int, Chronology=null) */ public void testConstructor_int_int_int_int_int_int_nullChronology() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, (Chronology) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (int, int, int) */ public void testConstructor_int_int_int_int_int_int_int() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, 0); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(LONDON, test.getZone()); assertEquals(TEST_TIME_NOW, test.getMillis()); try { new DateTime(Integer.MIN_VALUE, 6, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(Integer.MAX_VALUE, 6, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 0, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 13, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 6, 0, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 6, 31, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} new DateTime(2002, 7, 31, 0, 0, 0, 0); try { new DateTime(2002, 7, 32, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, DateTimeZone) */ public void testConstructor_int_int_int_int_int_int_int_DateTimeZone() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 2, 0, 0, 0, PARIS); // +02:00 assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); try { new DateTime(Integer.MIN_VALUE, 6, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(Integer.MAX_VALUE, 6, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 0, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 13, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 6, 0, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 6, 31, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} new DateTime(2002, 7, 31, 0, 0, 0, 0, PARIS); try { new DateTime(2002, 7, 32, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, DateTimeZone=null) */ public void testConstructor_int_int_int_int_int_int_int_nullDateTimeZone() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, 0, (DateTimeZone) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, Chronology) */ public void testConstructor_int_int_int_int_int_int_int_Chronology() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, 0, GregorianChronology.getInstance()); // +01:00 assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); try { new DateTime(Integer.MIN_VALUE, 6, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(Integer.MAX_VALUE, 6, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 0, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 13, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 6, 0, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateTime(2002, 6, 31, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} new DateTime(2002, 7, 31, 0, 0, 0, 0, GregorianChronology.getInstance()); try { new DateTime(2002, 7, 32, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology=null) */ public void testConstructor_int_int_int_int_int_int_int_nullChronology() throws Throwable { DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, 0, (Chronology) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } } joda-time-2.3/src/test/java/org/joda/time/TestAllPackages.java0000644000175000017500000000405211640073672023571 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all tests in Joda Time. * * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public class TestAllPackages extends TestCase { public TestAllPackages(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(org.joda.time.TestAll.suite()); suite.addTest(org.joda.time.chrono.TestAll.suite()); suite.addTest(org.joda.time.chrono.gj.TestAll.suite()); suite.addTest(org.joda.time.convert.TestAll.suite()); suite.addTest(org.joda.time.field.TestAll.suite()); suite.addTest(org.joda.time.format.TestAll.suite()); suite.addTest(org.joda.time.tz.TestAll.suite()); return suite; } public static void main(String args[]) { // setup a time zone other than one tester is in TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul")); // setup a locale other than one the tester is in Locale.setDefault(new Locale("th", "TH")); // run tests String[] testCaseName = { TestAllPackages.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } joda-time-2.3/src/test/java/org/joda/time/TestDateTimeFieldType.java0000644000175000017500000005365611564251363024742 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Constructor; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; /** * This class is a Junit unit test for Chronology. * * @author Stephen Colebourne */ public class TestDateTimeFieldType extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFieldType.class); } public TestDateTimeFieldType(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_era() throws Exception { assertEquals(DateTimeFieldType.era(), DateTimeFieldType.era()); assertEquals("era", DateTimeFieldType.era().getName()); assertEquals(DurationFieldType.eras(), DateTimeFieldType.era().getDurationType()); assertEquals(null, DateTimeFieldType.era().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().era(), DateTimeFieldType.era().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().era().isSupported(), DateTimeFieldType.era().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.era()); } public void test_centuryOfEra() throws Exception { assertEquals(DateTimeFieldType.centuryOfEra(), DateTimeFieldType.centuryOfEra()); assertEquals("centuryOfEra", DateTimeFieldType.centuryOfEra().getName()); assertEquals(DurationFieldType.centuries(), DateTimeFieldType.centuryOfEra().getDurationType()); assertEquals(DurationFieldType.eras(), DateTimeFieldType.centuryOfEra().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().centuryOfEra(), DateTimeFieldType.centuryOfEra().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().centuryOfEra().isSupported(), DateTimeFieldType.centuryOfEra().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.centuryOfEra()); } public void test_yearOfCentury() throws Exception { assertEquals(DateTimeFieldType.yearOfCentury(), DateTimeFieldType.yearOfCentury()); assertEquals("yearOfCentury", DateTimeFieldType.yearOfCentury().getName()); assertEquals(DurationFieldType.years(), DateTimeFieldType.yearOfCentury().getDurationType()); assertEquals(DurationFieldType.centuries(), DateTimeFieldType.yearOfCentury().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().yearOfCentury(), DateTimeFieldType.yearOfCentury().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().yearOfCentury().isSupported(), DateTimeFieldType.yearOfCentury().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.yearOfCentury()); } public void test_yearOfEra() throws Exception { assertEquals(DateTimeFieldType.yearOfEra(), DateTimeFieldType.yearOfEra()); assertEquals("yearOfEra", DateTimeFieldType.yearOfEra().getName()); assertEquals(DurationFieldType.years(), DateTimeFieldType.yearOfEra().getDurationType()); assertEquals(DurationFieldType.eras(), DateTimeFieldType.yearOfEra().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().yearOfEra(), DateTimeFieldType.yearOfEra().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().yearOfEra().isSupported(), DateTimeFieldType.yearOfEra().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.yearOfEra()); } public void test_year() throws Exception { assertEquals(DateTimeFieldType.year(), DateTimeFieldType.year()); assertEquals("year", DateTimeFieldType.year().getName()); assertEquals(DurationFieldType.years(), DateTimeFieldType.year().getDurationType()); assertEquals(null, DateTimeFieldType.year().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().year(), DateTimeFieldType.year().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().year().isSupported(), DateTimeFieldType.year().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.year()); } public void test_monthOfYear() throws Exception { assertEquals(DateTimeFieldType.monthOfYear(), DateTimeFieldType.monthOfYear()); assertEquals("monthOfYear", DateTimeFieldType.monthOfYear().getName()); assertEquals(DurationFieldType.months(), DateTimeFieldType.monthOfYear().getDurationType()); assertEquals(DurationFieldType.years(), DateTimeFieldType.monthOfYear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().monthOfYear(), DateTimeFieldType.monthOfYear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().monthOfYear().isSupported(), DateTimeFieldType.monthOfYear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.monthOfYear()); } public void test_weekyearOfCentury() throws Exception { assertEquals(DateTimeFieldType.weekyearOfCentury(), DateTimeFieldType.weekyearOfCentury()); assertEquals("weekyearOfCentury", DateTimeFieldType.weekyearOfCentury().getName()); assertEquals(DurationFieldType.weekyears(), DateTimeFieldType.weekyearOfCentury().getDurationType()); assertEquals(DurationFieldType.centuries(), DateTimeFieldType.weekyearOfCentury().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().weekyearOfCentury(), DateTimeFieldType.weekyearOfCentury().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weekyearOfCentury().isSupported(), DateTimeFieldType.weekyearOfCentury().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.weekyearOfCentury()); } public void test_weekyear() throws Exception { assertEquals(DateTimeFieldType.weekyear(), DateTimeFieldType.weekyear()); assertEquals("weekyear", DateTimeFieldType.weekyear().getName()); assertEquals(DurationFieldType.weekyears(), DateTimeFieldType.weekyear().getDurationType()); assertEquals(null, DateTimeFieldType.weekyear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().weekyear(), DateTimeFieldType.weekyear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weekyear().isSupported(), DateTimeFieldType.weekyear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.weekyear()); } public void test_weekOfWeekyear() throws Exception { assertEquals(DateTimeFieldType.weekOfWeekyear(), DateTimeFieldType.weekOfWeekyear()); assertEquals("weekOfWeekyear", DateTimeFieldType.weekOfWeekyear().getName()); assertEquals(DurationFieldType.weeks(), DateTimeFieldType.weekOfWeekyear().getDurationType()); assertEquals(DurationFieldType.weekyears(), DateTimeFieldType.weekOfWeekyear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().weekOfWeekyear(), DateTimeFieldType.weekOfWeekyear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weekOfWeekyear().isSupported(), DateTimeFieldType.weekOfWeekyear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.weekOfWeekyear()); } public void test_dayOfYear() throws Exception { assertEquals(DateTimeFieldType.dayOfYear(), DateTimeFieldType.dayOfYear()); assertEquals("dayOfYear", DateTimeFieldType.dayOfYear().getName()); assertEquals(DurationFieldType.days(), DateTimeFieldType.dayOfYear().getDurationType()); assertEquals(DurationFieldType.years(), DateTimeFieldType.dayOfYear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().dayOfYear(), DateTimeFieldType.dayOfYear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().dayOfYear().isSupported(), DateTimeFieldType.dayOfYear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.dayOfYear()); } public void test_dayOfMonth() throws Exception { assertEquals(DateTimeFieldType.dayOfMonth(), DateTimeFieldType.dayOfMonth()); assertEquals("dayOfMonth", DateTimeFieldType.dayOfMonth().getName()); assertEquals(DurationFieldType.days(), DateTimeFieldType.dayOfMonth().getDurationType()); assertEquals(DurationFieldType.months(), DateTimeFieldType.dayOfMonth().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().dayOfMonth(), DateTimeFieldType.dayOfMonth().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().dayOfMonth().isSupported(), DateTimeFieldType.dayOfMonth().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.dayOfMonth()); } public void test_dayOfWeek() throws Exception { assertEquals(DateTimeFieldType.dayOfWeek(), DateTimeFieldType.dayOfWeek()); assertEquals("dayOfWeek", DateTimeFieldType.dayOfWeek().getName()); assertEquals(DurationFieldType.days(), DateTimeFieldType.dayOfWeek().getDurationType()); assertEquals(DurationFieldType.weeks(), DateTimeFieldType.dayOfWeek().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().dayOfWeek(), DateTimeFieldType.dayOfWeek().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().dayOfWeek().isSupported(), DateTimeFieldType.dayOfWeek().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.dayOfWeek()); } public void test_halfdayOfDay() throws Exception { assertEquals(DateTimeFieldType.halfdayOfDay(), DateTimeFieldType.halfdayOfDay()); assertEquals("halfdayOfDay", DateTimeFieldType.halfdayOfDay().getName()); assertEquals(DurationFieldType.halfdays(), DateTimeFieldType.halfdayOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.halfdayOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().halfdayOfDay(), DateTimeFieldType.halfdayOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().halfdayOfDay().isSupported(), DateTimeFieldType.halfdayOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.halfdayOfDay()); } public void test_clockhourOfDay() throws Exception { assertEquals(DateTimeFieldType.clockhourOfDay(), DateTimeFieldType.clockhourOfDay()); assertEquals("clockhourOfDay", DateTimeFieldType.clockhourOfDay().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.clockhourOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.clockhourOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().clockhourOfDay(), DateTimeFieldType.clockhourOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().clockhourOfDay().isSupported(), DateTimeFieldType.clockhourOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.clockhourOfDay()); } public void test_clockhourOfHalfday() throws Exception { assertEquals(DateTimeFieldType.clockhourOfHalfday(), DateTimeFieldType.clockhourOfHalfday()); assertEquals("clockhourOfHalfday", DateTimeFieldType.clockhourOfHalfday().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.clockhourOfHalfday().getDurationType()); assertEquals(DurationFieldType.halfdays(), DateTimeFieldType.clockhourOfHalfday().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().clockhourOfHalfday(), DateTimeFieldType.clockhourOfHalfday().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().clockhourOfHalfday().isSupported(), DateTimeFieldType.clockhourOfHalfday().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.clockhourOfHalfday()); } public void test_hourOfHalfday() throws Exception { assertEquals(DateTimeFieldType.hourOfHalfday(), DateTimeFieldType.hourOfHalfday()); assertEquals("hourOfHalfday", DateTimeFieldType.hourOfHalfday().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.hourOfHalfday().getDurationType()); assertEquals(DurationFieldType.halfdays(), DateTimeFieldType.hourOfHalfday().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().hourOfHalfday(), DateTimeFieldType.hourOfHalfday().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().hourOfHalfday().isSupported(), DateTimeFieldType.hourOfHalfday().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.hourOfHalfday()); } public void test_hourOfDay() throws Exception { assertEquals(DateTimeFieldType.hourOfDay(), DateTimeFieldType.hourOfDay()); assertEquals("hourOfDay", DateTimeFieldType.hourOfDay().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.hourOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.hourOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().hourOfDay(), DateTimeFieldType.hourOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().hourOfDay().isSupported(), DateTimeFieldType.hourOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.hourOfDay()); } public void test_minuteOfDay() throws Exception { assertEquals(DateTimeFieldType.minuteOfDay(), DateTimeFieldType.minuteOfDay()); assertEquals("minuteOfDay", DateTimeFieldType.minuteOfDay().getName()); assertEquals(DurationFieldType.minutes(), DateTimeFieldType.minuteOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.minuteOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().minuteOfDay(), DateTimeFieldType.minuteOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().minuteOfDay().isSupported(), DateTimeFieldType.minuteOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.minuteOfDay()); } public void test_minuteOfHour() throws Exception { assertEquals(DateTimeFieldType.minuteOfHour(), DateTimeFieldType.minuteOfHour()); assertEquals("minuteOfHour", DateTimeFieldType.minuteOfHour().getName()); assertEquals(DurationFieldType.minutes(), DateTimeFieldType.minuteOfHour().getDurationType()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.minuteOfHour().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().minuteOfHour(), DateTimeFieldType.minuteOfHour().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().minuteOfHour().isSupported(), DateTimeFieldType.minuteOfHour().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.minuteOfHour()); } public void test_secondOfDay() throws Exception { assertEquals(DateTimeFieldType.secondOfDay(), DateTimeFieldType.secondOfDay()); assertEquals("secondOfDay", DateTimeFieldType.secondOfDay().getName()); assertEquals(DurationFieldType.seconds(), DateTimeFieldType.secondOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.secondOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().secondOfDay(), DateTimeFieldType.secondOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().secondOfDay().isSupported(), DateTimeFieldType.secondOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.secondOfDay()); } public void test_secondOfMinute() throws Exception { assertEquals(DateTimeFieldType.secondOfMinute(), DateTimeFieldType.secondOfMinute()); assertEquals("secondOfMinute", DateTimeFieldType.secondOfMinute().getName()); assertEquals(DurationFieldType.seconds(), DateTimeFieldType.secondOfMinute().getDurationType()); assertEquals(DurationFieldType.minutes(), DateTimeFieldType.secondOfMinute().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().secondOfMinute(), DateTimeFieldType.secondOfMinute().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().secondOfMinute().isSupported(), DateTimeFieldType.secondOfMinute().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.secondOfMinute()); } public void test_millisOfDay() throws Exception { assertEquals(DateTimeFieldType.millisOfDay(), DateTimeFieldType.millisOfDay()); assertEquals("millisOfDay", DateTimeFieldType.millisOfDay().getName()); assertEquals(DurationFieldType.millis(), DateTimeFieldType.millisOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.millisOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().millisOfDay(), DateTimeFieldType.millisOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().millisOfDay().isSupported(), DateTimeFieldType.millisOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.millisOfDay()); } public void test_millisOfSecond() throws Exception { assertEquals(DateTimeFieldType.millisOfSecond(), DateTimeFieldType.millisOfSecond()); assertEquals("millisOfSecond", DateTimeFieldType.millisOfSecond().getName()); assertEquals(DurationFieldType.millis(), DateTimeFieldType.millisOfSecond().getDurationType()); assertEquals(DurationFieldType.seconds(), DateTimeFieldType.millisOfSecond().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().millisOfSecond(), DateTimeFieldType.millisOfSecond().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().millisOfSecond().isSupported(), DateTimeFieldType.millisOfSecond().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.millisOfSecond()); } public void test_other() throws Exception { assertEquals(1, DateTimeFieldType.class.getDeclaredClasses().length); Class cls = DateTimeFieldType.class.getDeclaredClasses()[0]; assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; Object[] params = new Object[] { "other", new Byte((byte) 128), DurationFieldType.hours(), DurationFieldType.months()}; con.setAccessible(true); // for Apache Harmony JVM DateTimeFieldType type = (DateTimeFieldType) con.newInstance(params); assertEquals("other", type.getName()); assertSame(DurationFieldType.hours(), type.getDurationType()); assertSame(DurationFieldType.months(), type.getRangeDurationType()); try { type.getField(CopticChronology.getInstanceUTC()); fail(); } catch (InternalError ex) {} DateTimeFieldType result = doSerialization(type); assertEquals(type.getName(), result.getName()); assertNotSame(type, result); } //----------------------------------------------------------------------- private void assertSerialization(DateTimeFieldType type) throws Exception { DateTimeFieldType result = doSerialization(type); assertSame(type, result); } private DateTimeFieldType doSerialization(DateTimeFieldType type) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(type); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeFieldType result = (DateTimeFieldType) ois.readObject(); ois.close(); return result; } } joda-time-2.3/src/test/java/org/joda/time/TestBaseSingleFieldPeriod.java0000644000175000017500000003165412200501234025534 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.BaseSingleFieldPeriod; /** * This class is a Junit unit test for BaseSingleFieldPeriod. * * @author Stephen Colebourne */ public class TestBaseSingleFieldPeriod extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestBaseSingleFieldPeriod.class); } public TestBaseSingleFieldPeriod(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testFactory_between_RInstant() { // test using Days DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 12, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 15, 18, 0, 0, 0, PARIS); assertEquals(3, Single.between(start, end1, DurationFieldType.days())); assertEquals(0, Single.between(start, start, DurationFieldType.days())); assertEquals(0, Single.between(end1, end1, DurationFieldType.days())); assertEquals(-3, Single.between(end1, start, DurationFieldType.days())); assertEquals(6, Single.between(start, end2, DurationFieldType.days())); try { Single.between(start, (ReadableInstant) null, DurationFieldType.days()); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between((ReadableInstant) null, end1, DurationFieldType.days()); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between((ReadableInstant) null, (ReadableInstant) null, DurationFieldType.days()); fail(); } catch (IllegalArgumentException ex) { // expected } } @SuppressWarnings("deprecation") public void testFactory_between_RPartial() { LocalDate start = new LocalDate(2006, 6, 9); LocalDate end1 = new LocalDate(2006, 6, 12); YearMonthDay end2 = new YearMonthDay(2006, 6, 15); Single zero = new Single(0); assertEquals(3, Single.between(start, end1, zero)); assertEquals(0, Single.between(start, start, zero)); assertEquals(0, Single.between(end1, end1, zero)); assertEquals(-3, Single.between(end1, start, zero)); assertEquals(6, Single.between(start, end2, zero)); try { Single.between(start, (ReadablePartial) null, zero); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between((ReadablePartial) null, end1, zero); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between((ReadablePartial) null, (ReadablePartial) null, zero); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between(start, new LocalTime(), zero); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between(new Partial(DateTimeFieldType.dayOfWeek(), 2), new Partial(DateTimeFieldType.dayOfMonth(), 3), zero); fail(); } catch (IllegalArgumentException ex) { // expected } Partial p = new Partial( new DateTimeFieldType[] {DateTimeFieldType.year(), DateTimeFieldType.hourOfDay()}, new int[] {1, 2}); try { Single.between(p, p, zero); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testFactory_standardPeriodIn_RPeriod() { assertEquals(0, Single.standardPeriodIn((ReadablePeriod) null, DateTimeConstants.MILLIS_PER_DAY)); assertEquals(0, Single.standardPeriodIn(Period.ZERO, DateTimeConstants.MILLIS_PER_DAY)); assertEquals(1, Single.standardPeriodIn(new Period(0, 0, 0, 1, 0, 0, 0, 0), DateTimeConstants.MILLIS_PER_DAY)); assertEquals(123, Single.standardPeriodIn(Period.days(123), DateTimeConstants.MILLIS_PER_DAY)); assertEquals(-987, Single.standardPeriodIn(Period.days(-987), DateTimeConstants.MILLIS_PER_DAY)); assertEquals(1, Single.standardPeriodIn(Period.hours(47), DateTimeConstants.MILLIS_PER_DAY)); assertEquals(2, Single.standardPeriodIn(Period.hours(48), DateTimeConstants.MILLIS_PER_DAY)); assertEquals(2, Single.standardPeriodIn(Period.hours(49), DateTimeConstants.MILLIS_PER_DAY)); assertEquals(14, Single.standardPeriodIn(Period.weeks(2), DateTimeConstants.MILLIS_PER_DAY)); try { Single.standardPeriodIn(Period.months(1), DateTimeConstants.MILLIS_PER_DAY); fail(); } catch (IllegalArgumentException ex) { // expeceted } } //----------------------------------------------------------------------- public void testValueIndexMethods() { Single test = new Single(20); assertEquals(1, test.size()); assertEquals(20, test.getValue(0)); try { test.getValue(1); fail(); } catch (IndexOutOfBoundsException ex) { // expected } } public void testFieldTypeIndexMethods() { Single test = new Single(20); assertEquals(1, test.size()); assertEquals(DurationFieldType.days(), test.getFieldType(0)); try { test.getFieldType(1); fail(); } catch (IndexOutOfBoundsException ex) { // expected } } public void testIsSupported() { Single test = new Single(20); assertEquals(false, test.isSupported(DurationFieldType.years())); assertEquals(false, test.isSupported(DurationFieldType.months())); assertEquals(false, test.isSupported(DurationFieldType.weeks())); assertEquals(true, test.isSupported(DurationFieldType.days())); assertEquals(false, test.isSupported(DurationFieldType.hours())); assertEquals(false, test.isSupported(DurationFieldType.minutes())); assertEquals(false, test.isSupported(DurationFieldType.seconds())); assertEquals(false, test.isSupported(DurationFieldType.millis())); } public void testGet() { Single test = new Single(20); assertEquals(0, test.get(DurationFieldType.years())); assertEquals(0, test.get(DurationFieldType.months())); assertEquals(0, test.get(DurationFieldType.weeks())); assertEquals(20, test.get(DurationFieldType.days())); assertEquals(0, test.get(DurationFieldType.hours())); assertEquals(0, test.get(DurationFieldType.minutes())); assertEquals(0, test.get(DurationFieldType.seconds())); assertEquals(0, test.get(DurationFieldType.millis())); } //----------------------------------------------------------------------- public void testEqualsHashCode() { Single testA = new Single(20); Single testB = new Single(20); assertEquals(true, testA.equals(testB)); assertEquals(true, testB.equals(testA)); assertEquals(true, testA.equals(testA)); assertEquals(true, testB.equals(testB)); assertEquals(true, testA.hashCode() == testB.hashCode()); assertEquals(true, testA.hashCode() == testA.hashCode()); assertEquals(true, testB.hashCode() == testB.hashCode()); Single testC = new Single(30); assertEquals(false, testA.equals(testC)); assertEquals(false, testB.equals(testC)); assertEquals(false, testC.equals(testA)); assertEquals(false, testC.equals(testB)); assertEquals(false, testA.hashCode() == testC.hashCode()); assertEquals(false, testB.hashCode() == testC.hashCode()); assertEquals(true, testA.equals(Days.days(20))); assertEquals(true, testA.equals(new Period(0, 0, 0, 20, 0, 0, 0, 0, PeriodType.days()))); assertEquals(false, testA.equals(Period.days(2))); assertEquals(false, testA.equals("Hello")); assertEquals(false, testA.equals(Hours.hours(2))); assertEquals(false, testA.equals(null)); } public void testCompareTo() { Single test1 = new Single(21); Single test2 = new Single(22); Single test3 = new Single(23); assertEquals(true, test1.compareTo(test1) == 0); assertEquals(true, test1.compareTo(test2) < 0); assertEquals(true, test1.compareTo(test3) < 0); assertEquals(true, test2.compareTo(test1) > 0); assertEquals(true, test2.compareTo(test2) == 0); assertEquals(true, test2.compareTo(test3) < 0); assertEquals(true, test3.compareTo(test1) > 0); assertEquals(true, test3.compareTo(test2) > 0); assertEquals(true, test3.compareTo(test3) == 0); // try { // test1.compareTo("Hello"); // fail(); // } catch (ClassCastException ex) { // // expected // } // try { // test1.compareTo(new Period(0, 0, 0, 21, 0, 0, 0, 0, PeriodType.days())); // fail(); // } catch (ClassCastException ex) { // // expected // } try { test1.compareTo(null); fail(); } catch (NullPointerException ex) { // expected } } //----------------------------------------------------------------------- public void testToPeriod() { Single test = new Single(20); Period expected = Period.days(20); assertEquals(expected, test.toPeriod()); } public void testToMutablePeriod() { Single test = new Single(20); MutablePeriod expected = new MutablePeriod(0, 0, 0, 20, 0, 0, 0, 0); assertEquals(expected, test.toMutablePeriod()); } // public void testToDurationFrom() { // Period test = new Period(123L); // assertEquals(new Duration(123L), test.toDurationFrom(new Instant(0L))); // } // // public void testToDurationTo() { // Period test = new Period(123L); // assertEquals(new Duration(123L), test.toDurationTo(new Instant(123L))); // } // //----------------------------------------------------------------------- public void testGetSetValue() { Single test = new Single(20); assertEquals(20, test.getValue()); test.setValue(10); assertEquals(10, test.getValue()); } //----------------------------------------------------------------------- /** Test class. */ static class Single extends BaseSingleFieldPeriod { public Single(int period) { super(period); } public static int between(ReadableInstant start, ReadableInstant end, DurationFieldType field) { return BaseSingleFieldPeriod.between(start, end, field); } public static int between(ReadablePartial start, ReadablePartial end, ReadablePeriod zeroInstance) { return BaseSingleFieldPeriod.between(start, end, zeroInstance); } public static int standardPeriodIn(ReadablePeriod period, long millisPerUnit) { return BaseSingleFieldPeriod.standardPeriodIn(period, millisPerUnit); } public DurationFieldType getFieldType() { return DurationFieldType.days(); } public PeriodType getPeriodType() { return PeriodType.days(); } public int getValue() { return super.getValue(); } public void setValue(int value) { super.setValue(value); } } } joda-time-2.3/src/test/java/org/joda/time/TestDurationFieldType.java0000644000175000017500000002353411564251363025023 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Constructor; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; /** * This class is a Junit unit test for DurationFieldType. * * @author Stephen Colebourne */ public class TestDurationFieldType extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDurationFieldType.class); } public TestDurationFieldType(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_eras() throws Exception { assertEquals(DurationFieldType.eras(), DurationFieldType.eras()); assertEquals("eras", DurationFieldType.eras().getName()); assertEquals(CopticChronology.getInstanceUTC().eras(), DurationFieldType.eras().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().eras().isSupported(), DurationFieldType.eras().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.eras()); } public void test_centuries() throws Exception { assertEquals(DurationFieldType.centuries(), DurationFieldType.centuries()); assertEquals("centuries", DurationFieldType.centuries().getName()); assertEquals(CopticChronology.getInstanceUTC().centuries(), DurationFieldType.centuries().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().centuries().isSupported(), DurationFieldType.centuries().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.centuries()); } public void test_years() throws Exception { assertEquals(DurationFieldType.years(), DurationFieldType.years()); assertEquals("years", DurationFieldType.years().getName()); assertEquals(CopticChronology.getInstanceUTC().years(), DurationFieldType.years().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().years().isSupported(), DurationFieldType.years().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.years()); } public void test_months() throws Exception { assertEquals(DurationFieldType.months(), DurationFieldType.months()); assertEquals("months", DurationFieldType.months().getName()); assertEquals(CopticChronology.getInstanceUTC().months(), DurationFieldType.months().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().months().isSupported(), DurationFieldType.months().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.months()); } public void test_weekyears() throws Exception { assertEquals(DurationFieldType.weekyears(), DurationFieldType.weekyears()); assertEquals("weekyears", DurationFieldType.weekyears().getName()); assertEquals(CopticChronology.getInstanceUTC().weekyears(), DurationFieldType.weekyears().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weekyears().isSupported(), DurationFieldType.weekyears().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.weekyears()); } public void test_weeks() throws Exception { assertEquals(DurationFieldType.weeks(), DurationFieldType.weeks()); assertEquals("weeks", DurationFieldType.weeks().getName()); assertEquals(CopticChronology.getInstanceUTC().weeks(), DurationFieldType.weeks().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weeks().isSupported(), DurationFieldType.weeks().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.weeks()); } public void test_days() throws Exception { assertEquals(DurationFieldType.days(), DurationFieldType.days()); assertEquals("days", DurationFieldType.days().getName()); assertEquals(CopticChronology.getInstanceUTC().days(), DurationFieldType.days().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().days().isSupported(), DurationFieldType.days().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.days()); } public void test_halfdays() throws Exception { assertEquals(DurationFieldType.halfdays(), DurationFieldType.halfdays()); assertEquals("halfdays", DurationFieldType.halfdays().getName()); assertEquals(CopticChronology.getInstanceUTC().halfdays(), DurationFieldType.halfdays().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().halfdays().isSupported(), DurationFieldType.halfdays().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.halfdays()); } public void test_hours() throws Exception { assertEquals(DurationFieldType.hours(), DurationFieldType.hours()); assertEquals("hours", DurationFieldType.hours().getName()); assertEquals(CopticChronology.getInstanceUTC().hours(), DurationFieldType.hours().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().hours().isSupported(), DurationFieldType.hours().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.hours()); } public void test_minutes() throws Exception { assertEquals(DurationFieldType.minutes(), DurationFieldType.minutes()); assertEquals("minutes", DurationFieldType.minutes().getName()); assertEquals(CopticChronology.getInstanceUTC().minutes(), DurationFieldType.minutes().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().minutes().isSupported(), DurationFieldType.minutes().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.minutes()); } public void test_seconds() throws Exception { assertEquals(DurationFieldType.seconds(), DurationFieldType.seconds()); assertEquals("seconds", DurationFieldType.seconds().getName()); assertEquals(CopticChronology.getInstanceUTC().seconds(), DurationFieldType.seconds().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().seconds().isSupported(), DurationFieldType.seconds().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.seconds()); } public void test_millis() throws Exception { assertEquals(DurationFieldType.millis(), DurationFieldType.millis()); assertEquals("millis", DurationFieldType.millis().getName()); assertEquals(CopticChronology.getInstanceUTC().millis(), DurationFieldType.millis().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().millis().isSupported(), DurationFieldType.millis().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DurationFieldType.millis()); } public void test_other() throws Exception { assertEquals(1, DurationFieldType.class.getDeclaredClasses().length); Class cls = DurationFieldType.class.getDeclaredClasses()[0]; assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; Object[] params = new Object[] {"other", new Byte((byte) 128)}; DurationFieldType type = (DurationFieldType) con.newInstance(params); assertEquals("other", type.getName()); try { type.getField(CopticChronology.getInstanceUTC()); fail(); } catch (InternalError ex) {} DurationFieldType result = doSerialization(type); assertEquals(type.getName(), result.getName()); assertNotSame(type, result); } //----------------------------------------------------------------------- private void assertSerialization(DurationFieldType type) throws Exception { DurationFieldType result = doSerialization(type); assertSame(type, result); } private DurationFieldType doSerialization(DurationFieldType type) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(type); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DurationFieldType result = (DurationFieldType) ois.readObject(); ois.close(); return result; } } joda-time-2.3/src/test/java/org/joda/time/TestLocalDateTime_Properties.java0000644000175000017500000014152611564251363026315 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; /** * This class is a Junit unit test for LocalDateTime. * * @author Stephen Colebourne */ public class TestLocalDateTime_Properties extends TestCase { private static final CopticChronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private int MILLIS_OF_DAY = (int) (10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY + MILLIS_OF_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 1L * DateTimeConstants.MILLIS_PER_HOUR + 2L * DateTimeConstants.MILLIS_PER_MINUTE + 3L * DateTimeConstants.MILLIS_PER_SECOND + 4L; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 4L * DateTimeConstants.MILLIS_PER_HOUR + 5L * DateTimeConstants.MILLIS_PER_MINUTE + 6L * DateTimeConstants.MILLIS_PER_SECOND + 7L; private DateTimeZone zone = null; private Locale systemDefaultLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalDateTime_Properties.class); } public TestLocalDateTime_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); systemDefaultLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; Locale.setDefault(systemDefaultLocale); systemDefaultLocale = null; } //----------------------------------------------------------------------- public void testPropertyGetYear() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertSame(test, test.year().getLocalDateTime()); assertEquals(1972, test.year().get()); assertEquals("1972", test.year().getAsString()); assertEquals("1972", test.year().getAsText()); assertEquals("1972", test.year().getAsText(Locale.FRENCH)); assertEquals("1972", test.year().getAsShortText()); assertEquals("1972", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesYear() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292278993, test.year().getMaximumValue()); assertEquals(292278993, test.year().getMaximumValueOverall()); } public void testPropertyAddToCopyYear() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.year().addToCopy(9); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1981, 6, 9, 10, 20, 30, 40); copy = test.year().addToCopy(0); check(copy, 1972, 6, 9, 10, 20, 30, 40); copy = test.year().addToCopy(292278993 - 1972); check(copy, 292278993, 6, 9, 10, 20, 30, 40); try { test.year().addToCopy(292278993 - 1972 + 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9, 10, 20, 30, 40); copy = test.year().addToCopy(-1972); check(copy, 0, 6, 9, 10, 20, 30, 40); copy = test.year().addToCopy(-1973); check(copy, -1, 6, 9, 10, 20, 30, 40); try { test.year().addToCopy(-292275054 - 1972 - 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9, 10, 20, 30, 40); } public void testPropertyAddWrapFieldToCopyYear() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.year().addWrapFieldToCopy(9); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1981, 6, 9, 10, 20, 30, 40); copy = test.year().addWrapFieldToCopy(0); check(copy, 1972, 6, 9, 10, 20, 30, 40); copy = test.year().addWrapFieldToCopy(292278993 - 1972 + 1); check(copy, -292275054, 6, 9, 10, 20, 30, 40); copy = test.year().addWrapFieldToCopy(-292275054 - 1972 - 1); check(copy, 292278993, 6, 9, 10, 20, 30, 40); } public void testPropertySetCopyYear() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.year().setCopy(12); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 12, 6, 9, 10, 20, 30, 40); } public void testPropertySetCopyTextYear() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.year().setCopy("12"); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 12, 6, 9, 10, 20, 30, 40); } public void testPropertyCompareToYear() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.year().compareTo(test2) < 0); assertEquals(true, test2.year().compareTo(test1) > 0); assertEquals(true, test1.year().compareTo(test1) == 0); try { test1.year().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.year().compareTo(dt2) < 0); assertEquals(true, test2.year().compareTo(dt1) > 0); assertEquals(true, test1.year().compareTo(dt1) == 0); try { test1.year().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getLocalDateTime()); assertEquals(6, test.monthOfYear().get()); assertEquals("6", test.monthOfYear().getAsString()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new LocalDateTime(1972, 7, 9, 10, 20, 30, 40); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); } public void testPropertyGetMaxMinValuesMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyAddToCopyMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.monthOfYear().addToCopy(6); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 12, 9, 10, 20, 30, 40); copy = test.monthOfYear().addToCopy(7); check(copy, 1973, 1, 9, 10, 20, 30, 40); copy = test.monthOfYear().addToCopy(-5); check(copy, 1972, 1, 9, 10, 20, 30, 40); copy = test.monthOfYear().addToCopy(-6); check(copy, 1971, 12, 9, 10, 20, 30, 40); test = new LocalDateTime(1972, 1, 31, 10, 20, 30, 40); copy = test.monthOfYear().addToCopy(1); check(copy, 1972, 2, 29, 10, 20, 30, 40); copy = test.monthOfYear().addToCopy(2); check(copy, 1972, 3, 31, 10, 20, 30, 40); copy = test.monthOfYear().addToCopy(3); check(copy, 1972, 4, 30, 10, 20, 30, 40); test = new LocalDateTime(1971, 1, 31, 10, 20, 30, 40); copy = test.monthOfYear().addToCopy(1); check(copy, 1971, 2, 28, 10, 20, 30, 40); } public void testPropertyAddWrapFieldToCopyMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.monthOfYear().addWrapFieldToCopy(4); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 10, 9, 10, 20, 30, 40); copy = test.monthOfYear().addWrapFieldToCopy(8); check(copy, 1972, 2, 9, 10, 20, 30, 40); copy = test.monthOfYear().addWrapFieldToCopy(-8); check(copy, 1972, 10, 9, 10, 20, 30, 40); test = new LocalDateTime(1972, 1, 31, 10, 20, 30, 40); copy = test.monthOfYear().addWrapFieldToCopy(1); check(copy, 1972, 2, 29, 10, 20, 30, 40); copy = test.monthOfYear().addWrapFieldToCopy(2); check(copy, 1972, 3, 31, 10, 20, 30, 40); copy = test.monthOfYear().addWrapFieldToCopy(3); check(copy, 1972, 4, 30, 10, 20, 30, 40); test = new LocalDateTime(1971, 1, 31, 10, 20, 30, 40); copy = test.monthOfYear().addWrapFieldToCopy(1); check(copy, 1971, 2, 28, 10, 20, 30, 40); } public void testPropertySetCopyMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.monthOfYear().setCopy(12); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 12, 9, 10, 20, 30, 40); test = new LocalDateTime(1972, 1, 31, 10, 20, 30, 40); copy = test.monthOfYear().setCopy(2); check(copy, 1972, 2, 29, 10, 20, 30, 40); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetCopyTextMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.monthOfYear().setCopy("12"); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 12, 9, 10, 20, 30, 40); copy = test.monthOfYear().setCopy("December"); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 12, 9, 10, 20, 30, 40); copy = test.monthOfYear().setCopy("Dec"); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 12, 9, 10, 20, 30, 40); } public void testPropertyCompareToMonth() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetDay() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertSame(test, test.dayOfMonth().getLocalDateTime()); assertEquals(9, test.dayOfMonth().get()); assertEquals("9", test.dayOfMonth().getAsString()); assertEquals("9", test.dayOfMonth().getAsText()); assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("9", test.dayOfMonth().getAsShortText()); assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesDay() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); test = new LocalDateTime(1972, 7, 9, 10, 20, 30, 40); assertEquals(31, test.dayOfMonth().getMaximumValue()); test = new LocalDateTime(1972, 2, 9, 10, 20, 30, 40); assertEquals(29, test.dayOfMonth().getMaximumValue()); test = new LocalDateTime(1971, 2, 9, 10, 20, 30, 40); assertEquals(28, test.dayOfMonth().getMaximumValue()); } public void testPropertyAddToCopyDay() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.dayOfMonth().addToCopy(9); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 6, 18, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(21); check(copy, 1972, 6, 30, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(22); check(copy, 1972, 7, 1, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(22 + 30); check(copy, 1972, 7, 31, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(22 + 31); check(copy, 1972, 8, 1, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); check(copy, 1972, 12, 31, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); check(copy, 1973, 1, 1, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(-8); check(copy, 1972, 6, 1, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(-9); check(copy, 1972, 5, 31, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); check(copy, 1972, 1, 1, 10, 20, 30, 40); copy = test.dayOfMonth().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); check(copy, 1971, 12, 31, 10, 20, 30, 40); } public void testPropertyAddWrapFieldToCopyDay() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.dayOfMonth().addWrapFieldToCopy(21); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 6, 30, 10, 20, 30, 40); copy = test.dayOfMonth().addWrapFieldToCopy(22); check(copy, 1972, 6, 1, 10, 20, 30, 40); copy = test.dayOfMonth().addWrapFieldToCopy(-12); check(copy, 1972, 6, 27, 10, 20, 30, 40); test = new LocalDateTime(1972, 7, 9, 10, 20, 30, 40); copy = test.dayOfMonth().addWrapFieldToCopy(21); check(copy, 1972, 7, 30, 10, 20, 30, 40); copy = test.dayOfMonth().addWrapFieldToCopy(22); check(copy, 1972, 7, 31, 10, 20, 30, 40); copy = test.dayOfMonth().addWrapFieldToCopy(23); check(copy, 1972, 7, 1, 10, 20, 30, 40); copy = test.dayOfMonth().addWrapFieldToCopy(-12); check(copy, 1972, 7, 28, 10, 20, 30, 40); } public void testPropertySetCopyDay() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.dayOfMonth().setCopy(12); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 6, 12, 10, 20, 30, 40); try { test.dayOfMonth().setCopy(31); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfMonth().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetCopyTextDay() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.dayOfMonth().setCopy("12"); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 6, 12, 10, 20, 30, 40); } public void testPropertyWithMaximumValueDayOfMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.dayOfMonth().withMaximumValue(); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 6, 30, 10, 20, 30, 40); } public void testPropertyWithMinimumValueDayOfMonth() { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.dayOfMonth().withMinimumValue(); check(test, 1972, 6, 9, 10, 20, 30, 40); check(copy, 1972, 6, 1, 10, 20, 30, 40); } public void testPropertyCompareToDay() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0); try { test1.dayOfMonth().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyEquals() { LocalDateTime test1 = new LocalDateTime(2005, 11, 8, 10, 20, 30, 40); LocalDateTime test2 = new LocalDateTime(2005, 11, 9, 10, 20, 30, 40); LocalDateTime test3 = new LocalDateTime(2005, 11, 8, 10, 20, 30, 40, COPTIC_UTC); assertEquals(false, test1.dayOfMonth().equals(test1.year())); assertEquals(false, test1.dayOfMonth().equals(test1.monthOfYear())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(test2.year())); assertEquals(false, test1.dayOfMonth().equals(test2.monthOfYear())); assertEquals(false, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(false, test1.monthOfYear().equals(test1.year())); assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test1.dayOfMonth())); assertEquals(false, test1.monthOfYear().equals(test2.year())); assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test2.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(null)); assertEquals(false, test1.dayOfMonth().equals("any")); // chrono assertEquals(false, test1.dayOfMonth().equals(test3.dayOfMonth())); } public void testPropertyHashCode() { LocalDateTime test1 = new LocalDateTime(2005, 11, 8, 10, 20, 30, 40); LocalDateTime test2 = new LocalDateTime(2005, 11, 9, 10, 20, 30, 40); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(false, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); } //----------------------------------------------------------------------- public void testPropertyGetHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertSame(test.getChronology().hourOfDay(), test.hourOfDay().getField()); assertEquals("hourOfDay", test.hourOfDay().getName()); assertEquals("Property[hourOfDay]", test.hourOfDay().toString()); assertSame(test, test.hourOfDay().getLocalDateTime()); assertEquals(10, test.hourOfDay().get()); assertEquals("10", test.hourOfDay().getAsString()); assertEquals("10", test.hourOfDay().getAsText()); assertEquals("10", test.hourOfDay().getAsText(Locale.FRENCH)); assertEquals("10", test.hourOfDay().getAsShortText()); assertEquals("10", test.hourOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().hours(), test.hourOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.hourOfDay().getRangeDurationField()); assertEquals(2, test.hourOfDay().getMaximumTextLength(null)); assertEquals(2, test.hourOfDay().getMaximumShortTextLength(null)); } public void testPropertyRoundHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20); check(test.hourOfDay().roundCeilingCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 2005, 6, 9, 10, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 2005, 6, 9, 10, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 2005, 6, 9, 10, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 2005, 6, 9, 10, 0, 0, 0); test = new LocalDateTime(2005, 6, 9, 10, 40); check(test.hourOfDay().roundCeilingCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 2005, 6, 9, 10, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 2005, 6, 9, 11, 0, 0, 0); test = new LocalDateTime(2005, 6, 9, 10, 30); check(test.hourOfDay().roundCeilingCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 2005, 6, 9, 10, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 2005, 6, 9, 10, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 2005, 6, 9, 10, 0, 0, 0); test = new LocalDateTime(2005, 6, 9, 11, 30); check(test.hourOfDay().roundCeilingCopy(), 2005, 6, 9, 12, 0, 0, 0); check(test.hourOfDay().roundFloorCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundHalfCeilingCopy(), 2005, 6, 9, 12, 0, 0, 0); check(test.hourOfDay().roundHalfFloorCopy(), 2005, 6, 9, 11, 0, 0, 0); check(test.hourOfDay().roundHalfEvenCopy(), 2005, 6, 9, 12, 0, 0, 0); } public void testPropertyGetMaxMinValuesHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertEquals(0, test.hourOfDay().getMinimumValue()); assertEquals(0, test.hourOfDay().getMinimumValueOverall()); assertEquals(23, test.hourOfDay().getMaximumValue()); assertEquals(23, test.hourOfDay().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 0, 20, 30, 40); check(test.hourOfDay().withMaximumValue(), 2005, 6, 9, 23, 20, 30, 40); check(test.hourOfDay().withMinimumValue(), 2005, 6, 9, 0, 20, 30, 40); } public void testPropertyAddToCopyHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.hourOfDay().addToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 19, 20, 30, 40); copy = test.hourOfDay().addToCopy(0); check(copy, 2005, 6, 9, 10, 20, 30, 40); copy = test.hourOfDay().addToCopy(13); check(copy, 2005, 6, 9, 23, 20, 30, 40); copy = test.hourOfDay().addToCopy(14); check(copy, 2005, 6, 10, 0, 20, 30, 40); copy = test.hourOfDay().addToCopy(-10); check(copy, 2005, 6, 9, 0, 20, 30, 40); copy = test.hourOfDay().addToCopy(-11); check(copy, 2005, 6, 8, 23, 20, 30, 40); } public void testPropertyAddWrapFieldToCopyHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.hourOfDay().addWrapFieldToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 19, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(0); check(copy, 2005, 6, 9, 10, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(18); check(copy, 2005, 6, 9, 4, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(-15); check(copy, 2005, 6, 9, 19, 20, 30, 40); } public void testPropertySetHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.hourOfDay().setCopy(12); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 12, 20, 30, 40); try { test.hourOfDay().setCopy(24); fail(); } catch (IllegalArgumentException ex) {} try { test.hourOfDay().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.hourOfDay().setCopy("12"); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 12, 20, 30, 40); } public void testPropertyWithMaximumValueHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.hourOfDay().withMaximumValue(); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 23, 20, 30, 40); } public void testPropertyWithMinimumValueHour() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.hourOfDay().withMinimumValue(); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 0, 20, 30, 40); } public void testPropertyCompareToHour() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(test2) < 0); assertEquals(true, test2.hourOfDay().compareTo(test1) > 0); assertEquals(true, test1.hourOfDay().compareTo(test1) == 0); try { test1.hourOfDay().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(dt2) < 0); assertEquals(true, test2.hourOfDay().compareTo(dt1) > 0); assertEquals(true, test1.hourOfDay().compareTo(dt1) == 0); try { test1.hourOfDay().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertSame(test.getChronology().minuteOfHour(), test.minuteOfHour().getField()); assertEquals("minuteOfHour", test.minuteOfHour().getName()); assertEquals("Property[minuteOfHour]", test.minuteOfHour().toString()); assertSame(test, test.minuteOfHour().getLocalDateTime()); assertEquals(20, test.minuteOfHour().get()); assertEquals("20", test.minuteOfHour().getAsString()); assertEquals("20", test.minuteOfHour().getAsText()); assertEquals("20", test.minuteOfHour().getAsText(Locale.FRENCH)); assertEquals("20", test.minuteOfHour().getAsShortText()); assertEquals("20", test.minuteOfHour().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.minuteOfHour().getDurationField()); assertEquals(test.getChronology().hours(), test.minuteOfHour().getRangeDurationField()); assertEquals(2, test.minuteOfHour().getMaximumTextLength(null)); assertEquals(2, test.minuteOfHour().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertEquals(0, test.minuteOfHour().getMinimumValue()); assertEquals(0, test.minuteOfHour().getMinimumValueOverall()); assertEquals(59, test.minuteOfHour().getMaximumValue()); assertEquals(59, test.minuteOfHour().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); check(test.minuteOfHour().withMaximumValue(), 2005, 6, 9, 10, 59, 30, 40); check(test.minuteOfHour().withMinimumValue(), 2005, 6, 9, 10, 0, 30, 40); } public void testPropertyAddToCopyMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.minuteOfHour().addToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 29, 30, 40); copy = test.minuteOfHour().addToCopy(39); check(copy, 2005, 6, 9, 10, 59, 30, 40); copy = test.minuteOfHour().addToCopy(40); check(copy, 2005, 6, 9, 11, 0, 30, 40); copy = test.minuteOfHour().addToCopy(1 * 60 + 45); check(copy, 2005, 6, 9, 12, 5, 30, 40); copy = test.minuteOfHour().addToCopy(13 * 60 + 39); check(copy, 2005, 6, 9, 23, 59, 30, 40); copy = test.minuteOfHour().addToCopy(13 * 60 + 40); check(copy, 2005, 6, 10, 0, 0, 30, 40); copy = test.minuteOfHour().addToCopy(-9); check(copy, 2005, 6, 9, 10, 11, 30, 40); copy = test.minuteOfHour().addToCopy(-19); check(copy, 2005, 6, 9, 10, 1, 30, 40); copy = test.minuteOfHour().addToCopy(-20); check(copy, 2005, 6, 9, 10, 0, 30, 40); copy = test.minuteOfHour().addToCopy(-21); check(copy, 2005, 6, 9, 9, 59, 30, 40); copy = test.minuteOfHour().addToCopy(-(10 * 60 + 20)); check(copy, 2005, 6, 9, 0, 0, 30, 40); copy = test.minuteOfHour().addToCopy(-(10 * 60 + 21)); check(copy, 2005, 6, 8, 23, 59, 30, 40); } public void testPropertyAddWrapFieldToCopyMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.minuteOfHour().addWrapFieldToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 29, 30, 40); copy = test.minuteOfHour().addWrapFieldToCopy(49); check(copy, 2005, 6, 9, 10, 9, 30, 40); copy = test.minuteOfHour().addWrapFieldToCopy(-47); check(copy, 2005, 6, 9, 10, 33, 30, 40); } public void testPropertySetMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.minuteOfHour().setCopy(12); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 12, 30, 40); try { test.minuteOfHour().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.minuteOfHour().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.minuteOfHour().setCopy("12"); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 12, 30, 40); } public void testPropertyCompareToMinute() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.minuteOfHour().compareTo(test2) < 0); assertEquals(true, test2.minuteOfHour().compareTo(test1) > 0); assertEquals(true, test1.minuteOfHour().compareTo(test1) == 0); try { test1.minuteOfHour().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.minuteOfHour().compareTo(dt2) < 0); assertEquals(true, test2.minuteOfHour().compareTo(dt1) > 0); assertEquals(true, test1.minuteOfHour().compareTo(dt1) == 0); try { test1.minuteOfHour().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetSecond() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertSame(test.getChronology().secondOfMinute(), test.secondOfMinute().getField()); assertEquals("secondOfMinute", test.secondOfMinute().getName()); assertEquals("Property[secondOfMinute]", test.secondOfMinute().toString()); assertSame(test, test.secondOfMinute().getLocalDateTime()); assertEquals(30, test.secondOfMinute().get()); assertEquals("30", test.secondOfMinute().getAsString()); assertEquals("30", test.secondOfMinute().getAsText()); assertEquals("30", test.secondOfMinute().getAsText(Locale.FRENCH)); assertEquals("30", test.secondOfMinute().getAsShortText()); assertEquals("30", test.secondOfMinute().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().seconds(), test.secondOfMinute().getDurationField()); assertEquals(test.getChronology().minutes(), test.secondOfMinute().getRangeDurationField()); assertEquals(2, test.secondOfMinute().getMaximumTextLength(null)); assertEquals(2, test.secondOfMinute().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesSecond() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertEquals(0, test.secondOfMinute().getMinimumValue()); assertEquals(0, test.secondOfMinute().getMinimumValueOverall()); assertEquals(59, test.secondOfMinute().getMaximumValue()); assertEquals(59, test.secondOfMinute().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueSecond() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); check(test.secondOfMinute().withMaximumValue(), 2005, 6, 9, 10, 20, 59, 40); check(test.secondOfMinute().withMinimumValue(), 2005, 6, 9, 10, 20, 0, 40); } public void testPropertyAddToCopySecond() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.secondOfMinute().addToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 39, 40); copy = test.secondOfMinute().addToCopy(29); check(copy, 2005, 6, 9, 10, 20, 59, 40); copy = test.secondOfMinute().addToCopy(30); check(copy, 2005, 6, 9, 10, 21, 0, 40); copy = test.secondOfMinute().addToCopy(39 * 60 + 29); check(copy, 2005, 6, 9, 10, 59, 59, 40); copy = test.secondOfMinute().addToCopy(39 * 60 + 30); check(copy, 2005, 6, 9, 11, 0, 0, 40); copy = test.secondOfMinute().addToCopy(13 * 60 * 60 + 39 * 60 + 30); check(copy, 2005, 6, 10, 0, 0, 0, 40); copy = test.secondOfMinute().addToCopy(-9); check(copy, 2005, 6, 9, 10, 20, 21, 40); copy = test.secondOfMinute().addToCopy(-30); check(copy, 2005, 6, 9, 10, 20, 0, 40); copy = test.secondOfMinute().addToCopy(-31); check(copy, 2005, 6, 9, 10, 19, 59, 40); copy = test.secondOfMinute().addToCopy(-(10 * 60 * 60 + 20 * 60 + 30)); check(copy, 2005, 6, 9, 0, 0, 0, 40); copy = test.secondOfMinute().addToCopy(-(10 * 60 * 60 + 20 * 60 + 31)); check(copy, 2005, 6, 8, 23, 59, 59, 40); } public void testPropertyAddWrapFieldToCopySecond() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.secondOfMinute().addWrapFieldToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 39, 40); copy = test.secondOfMinute().addWrapFieldToCopy(49); check(copy, 2005, 6, 9, 10, 20, 19, 40); copy = test.secondOfMinute().addWrapFieldToCopy(-47); check(copy, 2005, 6, 9, 10, 20, 43, 40); } public void testPropertySetSecond() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.secondOfMinute().setCopy(12); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 12, 40); try { test.secondOfMinute().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.secondOfMinute().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextSecond() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.secondOfMinute().setCopy("12"); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 12, 40); } public void testPropertyCompareToSecond() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.secondOfMinute().compareTo(test2) < 0); assertEquals(true, test2.secondOfMinute().compareTo(test1) > 0); assertEquals(true, test1.secondOfMinute().compareTo(test1) == 0); try { test1.secondOfMinute().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.secondOfMinute().compareTo(dt2) < 0); assertEquals(true, test2.secondOfMinute().compareTo(dt1) > 0); assertEquals(true, test1.secondOfMinute().compareTo(dt1) == 0); try { test1.secondOfMinute().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMilli() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertSame(test.getChronology().millisOfSecond(), test.millisOfSecond().getField()); assertEquals("millisOfSecond", test.millisOfSecond().getName()); assertEquals("Property[millisOfSecond]", test.millisOfSecond().toString()); assertSame(test, test.millisOfSecond().getLocalDateTime()); assertEquals(40, test.millisOfSecond().get()); assertEquals("40", test.millisOfSecond().getAsString()); assertEquals("40", test.millisOfSecond().getAsText()); assertEquals("40", test.millisOfSecond().getAsText(Locale.FRENCH)); assertEquals("40", test.millisOfSecond().getAsShortText()); assertEquals("40", test.millisOfSecond().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().millis(), test.millisOfSecond().getDurationField()); assertEquals(test.getChronology().seconds(), test.millisOfSecond().getRangeDurationField()); assertEquals(3, test.millisOfSecond().getMaximumTextLength(null)); assertEquals(3, test.millisOfSecond().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMilli() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertEquals(0, test.millisOfSecond().getMinimumValue()); assertEquals(0, test.millisOfSecond().getMinimumValueOverall()); assertEquals(999, test.millisOfSecond().getMaximumValue()); assertEquals(999, test.millisOfSecond().getMaximumValueOverall()); } public void testPropertyWithMaxMinValueMilli() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); check(test.millisOfSecond().withMaximumValue(), 2005, 6, 9, 10, 20, 30, 999); check(test.millisOfSecond().withMinimumValue(), 2005, 6, 9, 10, 20, 30, 0); } public void testPropertyAddToCopyMilli() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.millisOfSecond().addToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 30, 49); copy = test.millisOfSecond().addToCopy(959); check(copy, 2005, 6, 9, 10, 20, 30, 999); copy = test.millisOfSecond().addToCopy(960); check(copy, 2005, 6, 9, 10, 20, 31, 0); copy = test.millisOfSecond().addToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 959); check(copy, 2005, 6, 9, 23, 59, 59, 999); copy = test.millisOfSecond().addToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 960); check(copy, 2005, 6, 10, 0, 0, 0, 0); copy = test.millisOfSecond().addToCopy(-9); check(copy, 2005, 6, 9, 10, 20, 30, 31); copy = test.millisOfSecond().addToCopy(-40); check(copy, 2005, 6, 9, 10, 20, 30, 0); copy = test.millisOfSecond().addToCopy(-41); check(copy, 2005, 6, 9, 10, 20, 29, 999); copy = test.millisOfSecond().addToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 40)); check(copy, 2005, 6, 9, 0, 0, 0, 0); copy = test.millisOfSecond().addToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 41)); check(copy, 2005, 6, 8, 23, 59, 59, 999); } public void testPropertyAddWrapFieldToCopyMilli() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.millisOfSecond().addWrapFieldToCopy(9); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 30, 49); copy = test.millisOfSecond().addWrapFieldToCopy(995); check(copy, 2005, 6, 9, 10, 20, 30, 35); copy = test.millisOfSecond().addWrapFieldToCopy(-47); check(copy, 2005, 6, 9, 10, 20, 30, 993); } public void testPropertySetMilli() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.millisOfSecond().setCopy(12); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 30, 12); try { test.millisOfSecond().setCopy(1000); fail(); } catch (IllegalArgumentException ex) {} try { test.millisOfSecond().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMilli() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.millisOfSecond().setCopy("12"); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 20, 30, 12); } public void testPropertyCompareToMilli() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.millisOfSecond().compareTo(test2) < 0); assertEquals(true, test2.millisOfSecond().compareTo(test1) > 0); assertEquals(true, test1.millisOfSecond().compareTo(test1) == 0); try { test1.millisOfSecond().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.millisOfSecond().compareTo(dt2) < 0); assertEquals(true, test2.millisOfSecond().compareTo(dt1) > 0); assertEquals(true, test1.millisOfSecond().compareTo(dt1) == 0); try { test1.millisOfSecond().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- private void check(LocalDateTime test, int year, int month, int day, int hour, int min, int sec, int mil) { assertEquals(year, test.getYear()); assertEquals(month, test.getMonthOfYear()); assertEquals(day, test.getDayOfMonth()); assertEquals(hour, test.getHourOfDay()); assertEquals(min, test.getMinuteOfHour()); assertEquals(sec, test.getSecondOfMinute()); assertEquals(mil, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/TestDateTimeUtils.java0000644000175000017500000005254612200501234024131 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.lang.reflect.Modifier; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeUtils.MillisProvider; import org.joda.time.base.AbstractInstant; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for DateTimeUtils. * * @author Stephen Colebourne */ public class TestDateTimeUtils extends TestCase { private static final GJChronology GJ = GJChronology.getInstance(); private static final boolean OLD_JDK; static { String str = System.getProperty("java.version"); boolean old = true; if (str.length() > 3 && str.charAt(0) == '1' && str.charAt(1) == '.' && (str.charAt(2) == '4' || str.charAt(2) == '5' || str.charAt(2) == '6')) { old = false; } OLD_JDK = old; } // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private static final Policy RESTRICT; private static final Policy ALLOW; static { // don't call Policy.getPolicy() RESTRICT = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } public boolean implies(ProtectionDomain domain, Permission permission) { if (permission instanceof JodaTimePermission) { return false; } return true; // return super.implies(domain, permission); } }; ALLOW = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } }; } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeUtils.class); } public TestDateTimeUtils(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testClass() { Class cls = DateTimeUtils.class; assertEquals(true, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isFinal(cls.getModifiers())); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(cls.getDeclaredConstructors()[0].getModifiers())); new DateTimeUtils() {}; } //----------------------------------------------------------------------- public void testSystemMillis() { long nowSystem = System.currentTimeMillis(); long now = DateTimeUtils.currentTimeMillis(); assertTrue((now >= nowSystem)); assertTrue((now - nowSystem) < 10000L); } //----------------------------------------------------------------------- public void testSystemMillisSecurity() { if (OLD_JDK) { return; } try { try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeUtils.setCurrentMillisSystem(); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } } finally { DateTimeUtils.setCurrentMillisSystem(); } } //----------------------------------------------------------------------- public void testFixedMillis() { try { DateTimeUtils.setCurrentMillisFixed(0L); assertEquals(0L, DateTimeUtils.currentTimeMillis()); assertEquals(0L, DateTimeUtils.currentTimeMillis()); assertEquals(0L, DateTimeUtils.currentTimeMillis()); } finally { DateTimeUtils.setCurrentMillisSystem(); } long nowSystem = System.currentTimeMillis(); long now = DateTimeUtils.currentTimeMillis(); assertTrue((now >= nowSystem)); assertTrue((now - nowSystem) < 10000L); } //----------------------------------------------------------------------- public void testFixedMillisSecurity() { if (OLD_JDK) { return; } try { try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeUtils.setCurrentMillisFixed(0L); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } } finally { DateTimeUtils.setCurrentMillisSystem(); } } //----------------------------------------------------------------------- public void testOffsetMillis() { try { // set time to one day ago DateTimeUtils.setCurrentMillisOffset(-24 * 60 * 60 * 1000); long nowSystem = System.currentTimeMillis(); long now = DateTimeUtils.currentTimeMillis(); long nowAdjustDay = now + (24 * 60 * 60 * 1000); assertTrue((now < nowSystem)); assertTrue((nowAdjustDay >= nowSystem)); assertTrue((nowAdjustDay - nowSystem) < 10000L); } finally { DateTimeUtils.setCurrentMillisSystem(); } long nowSystem = System.currentTimeMillis(); long now = DateTimeUtils.currentTimeMillis(); assertTrue((now >= nowSystem)); assertTrue((now - nowSystem) < 10000L); } //----------------------------------------------------------------------- public void testOffsetMillisToZero() { long now1 = 0L; try { // set time to one day ago DateTimeUtils.setCurrentMillisOffset(0); now1 = DateTimeUtils.currentTimeMillis(); } finally { DateTimeUtils.setCurrentMillisSystem(); } long now2 = DateTimeUtils.currentTimeMillis(); assertEquals(now1, now2); } //----------------------------------------------------------------------- public void testOffsetMillisSecurity() { if (OLD_JDK) { return; } try { try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeUtils.setCurrentMillisOffset(-24 * 60 * 60 * 1000); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } } finally { DateTimeUtils.setCurrentMillisSystem(); } } //----------------------------------------------------------------------- public void testMillisProvider() { try { DateTimeUtils.setCurrentMillisProvider(new MillisProvider() { public long getMillis() { return 1L; } }); assertEquals(1L, DateTimeUtils.currentTimeMillis()); } finally { DateTimeUtils.setCurrentMillisSystem(); } } public void testMillisProvider_null() { try { DateTimeUtils.setCurrentMillisProvider(null); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- public void testMillisProviderSecurity() { if (OLD_JDK) { return; } try { try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeUtils.setCurrentMillisProvider(new MillisProvider() { public long getMillis() { return 0L; } }); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } } finally { DateTimeUtils.setCurrentMillisSystem(); } } //----------------------------------------------------------------------- public void testGetInstantMillis_RI() { Instant i = new Instant(123L); assertEquals(123L, DateTimeUtils.getInstantMillis(i)); try { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); assertEquals(TEST_TIME_NOW, DateTimeUtils.getInstantMillis(null)); } finally { DateTimeUtils.setCurrentMillisSystem(); } } //----------------------------------------------------------------------- public void testGetInstantChronology_RI() { DateTime dt = new DateTime(123L, BuddhistChronology.getInstance()); assertEquals(BuddhistChronology.getInstance(), DateTimeUtils.getInstantChronology(dt)); Instant i = new Instant(123L); assertEquals(ISOChronology.getInstanceUTC(), DateTimeUtils.getInstantChronology(i)); AbstractInstant ai = new AbstractInstant() { public long getMillis() { return 0L; } public Chronology getChronology() { return null; // testing for this } }; assertEquals(ISOChronology.getInstance(), DateTimeUtils.getInstantChronology(ai)); assertEquals(ISOChronology.getInstance(), DateTimeUtils.getInstantChronology(null)); } //----------------------------------------------------------------------- public void testGetIntervalChronology_RInterval() { Interval dt = new Interval(123L, 456L, BuddhistChronology.getInstance()); assertEquals(BuddhistChronology.getInstance(), DateTimeUtils.getIntervalChronology(dt)); assertEquals(ISOChronology.getInstance(), DateTimeUtils.getIntervalChronology(null)); MutableInterval ai = new MutableInterval() { private static final long serialVersionUID = 1L; public Chronology getChronology() { return null; // testing for this } }; assertEquals(ISOChronology.getInstance(), DateTimeUtils.getIntervalChronology(ai)); } //----------------------------------------------------------------------- public void testGetIntervalChronology_RI_RI() { DateTime dt1 = new DateTime(123L, BuddhistChronology.getInstance()); DateTime dt2 = new DateTime(123L, CopticChronology.getInstance()); assertEquals(BuddhistChronology.getInstance(), DateTimeUtils.getIntervalChronology(dt1, dt2)); assertEquals(BuddhistChronology.getInstance(), DateTimeUtils.getIntervalChronology(dt1, null)); assertEquals(CopticChronology.getInstance(), DateTimeUtils.getIntervalChronology(null, dt2)); assertEquals(ISOChronology.getInstance(), DateTimeUtils.getIntervalChronology(null, null)); } //----------------------------------------------------------------------- public void testGetReadableInterval_ReadableInterval() { ReadableInterval input = new Interval(0, 100L); assertEquals(input, DateTimeUtils.getReadableInterval(input)); try { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME_NOW), DateTimeUtils.getReadableInterval(null)); } finally { DateTimeUtils.setCurrentMillisSystem(); } } //----------------------------------------------------------------------- public void testGetChronology_Chronology() { assertEquals(BuddhistChronology.getInstance(), DateTimeUtils.getChronology(BuddhistChronology.getInstance())); assertEquals(ISOChronology.getInstance(), DateTimeUtils.getChronology(null)); } //----------------------------------------------------------------------- public void testGetZone_Zone() { assertEquals(PARIS, DateTimeUtils.getZone(PARIS)); assertEquals(DateTimeZone.getDefault(), DateTimeUtils.getZone(null)); } //----------------------------------------------------------------------- public void testGetPeriodType_PeriodType() { assertEquals(PeriodType.dayTime(), DateTimeUtils.getPeriodType(PeriodType.dayTime())); assertEquals(PeriodType.standard(), DateTimeUtils.getPeriodType(null)); } //----------------------------------------------------------------------- public void testGetDurationMillis_RI() { Duration dur = new Duration(123L); assertEquals(123L, DateTimeUtils.getDurationMillis(dur)); assertEquals(0L, DateTimeUtils.getDurationMillis(null)); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testIsContiguous_RP() { YearMonthDay ymd = new YearMonthDay(2005, 6, 9); assertEquals(true, DateTimeUtils.isContiguous(ymd)); TimeOfDay tod = new TimeOfDay(12, 20, 30, 0); assertEquals(true, DateTimeUtils.isContiguous(tod)); Partial year = new Partial(DateTimeFieldType.year(), 2005); assertEquals(true, DateTimeUtils.isContiguous(year)); Partial hourOfDay = new Partial(DateTimeFieldType.hourOfDay(), 12); assertEquals(true, DateTimeUtils.isContiguous(hourOfDay)); Partial yearHour = year.with(DateTimeFieldType.hourOfDay(), 12); assertEquals(false, DateTimeUtils.isContiguous(yearHour)); Partial ymdd = new Partial(ymd).with(DateTimeFieldType.dayOfWeek(), 2); assertEquals(false, DateTimeUtils.isContiguous(ymdd)); Partial dd = new Partial(DateTimeFieldType.dayOfMonth(), 13).with(DateTimeFieldType.dayOfWeek(), 5); assertEquals(false, DateTimeUtils.isContiguous(dd)); try { DateTimeUtils.isContiguous((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testIsContiguous_RP_GJChronology() { YearMonthDay ymd = new YearMonthDay(2005, 6, 9, GJ); assertEquals(true, DateTimeUtils.isContiguous(ymd)); TimeOfDay tod = new TimeOfDay(12, 20, 30, 0, GJ); assertEquals(true, DateTimeUtils.isContiguous(tod)); Partial year = new Partial(DateTimeFieldType.year(), 2005, GJ); assertEquals(true, DateTimeUtils.isContiguous(year)); Partial hourOfDay = new Partial(DateTimeFieldType.hourOfDay(), 12, GJ); assertEquals(true, DateTimeUtils.isContiguous(hourOfDay)); Partial yearHour = year.with(DateTimeFieldType.hourOfDay(), 12); assertEquals(false, DateTimeUtils.isContiguous(yearHour)); Partial ymdd = new Partial(ymd).with(DateTimeFieldType.dayOfWeek(), 2); assertEquals(false, DateTimeUtils.isContiguous(ymdd)); Partial dd = new Partial(DateTimeFieldType.dayOfMonth(), 13).with(DateTimeFieldType.dayOfWeek(), 5); assertEquals(false, DateTimeUtils.isContiguous(dd)); try { DateTimeUtils.isContiguous((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_julianDay() { DateTime base = new DateTime(1970, 1, 1, 0, 0, DateTimeZone.UTC); assertEquals(2440587.5d, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(2440588, DateTimeUtils.toJulianDayNumber(base.getMillis())); assertEquals(base.getMillis(), DateTimeUtils.fromJulianDay(2440587.5d)); base = base.plusHours(6); assertEquals(2440587.75d, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(2440588, DateTimeUtils.toJulianDayNumber(base.getMillis())); assertEquals(base.getMillis(), DateTimeUtils.fromJulianDay(2440587.75d)); base = base.plusHours(6); assertEquals(2440588d, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(2440588, DateTimeUtils.toJulianDayNumber(base.getMillis())); assertEquals(base.getMillis(), DateTimeUtils.fromJulianDay(2440588d)); base = base.plusHours(6); assertEquals(2440588.25d, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(2440588, DateTimeUtils.toJulianDayNumber(base.getMillis())); assertEquals(base.getMillis(), DateTimeUtils.fromJulianDay(2440588.25d)); base = base.plusHours(6); assertEquals(2440588.5d, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(2440589, DateTimeUtils.toJulianDayNumber(base.getMillis())); assertEquals(base.getMillis(), DateTimeUtils.fromJulianDay(2440588.5d)); base = new DateTime(2012, 8, 31, 23, 50, DateTimeZone.UTC); assertEquals(2456171.4930555555, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(2456171, DateTimeUtils.toJulianDayNumber(base.getMillis())); base = new DateTime(-4713, 1, 1, 12, 0, JulianChronology.getInstanceUTC()); assertEquals(0d, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(0, DateTimeUtils.toJulianDayNumber(base.getMillis())); assertEquals(base.getMillis(), DateTimeUtils.fromJulianDay(0d)); base = new DateTime(-4713, 1, 1, 0, 0, JulianChronology.getInstanceUTC()); assertEquals(-0.5d, DateTimeUtils.toJulianDay(base.getMillis()), 0.0001d); assertEquals(0, DateTimeUtils.toJulianDayNumber(base.getMillis())); assertEquals(base.getMillis(), DateTimeUtils.fromJulianDay(-0.5d)); } } joda-time-2.3/src/test/java/org/joda/time/TestPartial_Basics.java0000644000175000017500000010560412200501234024266 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for Partial. * * @author Stephen Colebourne */ public class TestPartial_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPartial_Basics.class); } public TestPartial_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testGet() { Partial test = createHourMinPartial(); assertEquals(10, test.get(DateTimeFieldType.hourOfDay())); assertEquals(20, test.get(DateTimeFieldType.minuteOfHour())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.secondOfMinute()); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { Partial test = createHourMinPartial(); assertEquals(2, test.size()); } public void testGetFieldType() { Partial test = createHourMinPartial(); assertSame(DateTimeFieldType.hourOfDay(), test.getFieldType(0)); assertSame(DateTimeFieldType.minuteOfHour(), test.getFieldType(1)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { Partial test = createHourMinPartial(); DateTimeFieldType[] fields = test.getFieldTypes(); assertEquals(2, fields.length); assertSame(DateTimeFieldType.hourOfDay(), fields[0]); assertSame(DateTimeFieldType.minuteOfHour(), fields[1]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField() { Partial test = createHourMinPartial(COPTIC_PARIS); assertSame(CopticChronology.getInstanceUTC().hourOfDay(), test.getField(0)); assertSame(CopticChronology.getInstanceUTC().minuteOfHour(), test.getField(1)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(5); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { Partial test = createHourMinPartial(COPTIC_PARIS); DateTimeField[] fields = test.getFields(); assertEquals(2, fields.length); assertSame(CopticChronology.getInstanceUTC().hourOfDay(), fields[0]); assertSame(CopticChronology.getInstanceUTC().minuteOfHour(), fields[1]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue() { Partial test = createHourMinPartial(COPTIC_PARIS); assertEquals(10, test.getValue(0)); assertEquals(20, test.getValue(1)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { Partial test = createHourMinPartial(COPTIC_PARIS); int[] values = test.getValues(); assertEquals(2, values.length); assertEquals(10, values[0]); assertEquals(20, values[1]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported() { Partial test = createHourMinPartial(COPTIC_PARIS); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(false, test.isSupported(DateTimeFieldType.secondOfMinute())); assertEquals(false, test.isSupported(DateTimeFieldType.millisOfSecond())); assertEquals(false, test.isSupported(DateTimeFieldType.dayOfMonth())); } @SuppressWarnings("deprecation") public void testEqualsHashCode() { Partial test1 = createHourMinPartial(COPTIC_PARIS); Partial test2 = createHourMinPartial(COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); Partial test3 = createHourMinPartial2(COPTIC_PARIS); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); assertEquals(new TimeOfDay(10, 20, 30, 40), createTODPartial(ISO_UTC)); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testCompareTo() { Partial test1 = createHourMinPartial(); Partial test1a = createHourMinPartial(); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); Partial test2 = createHourMinPartial2(ISO_UTC); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); Partial test3 = createHourMinPartial2(COPTIC_UTC); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); assertEquals(0, new TimeOfDay(10, 20, 30, 40).compareTo(createTODPartial(ISO_UTC))); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} try { test1.compareTo(new YearMonthDay()); fail(); } catch (ClassCastException ex) {} try { createTODPartial(ISO_UTC).without(DateTimeFieldType.hourOfDay()).compareTo(new YearMonthDay()); fail(); } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_TOD() { Partial test1 = createHourMinPartial(); Partial test1a = createHourMinPartial(); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); Partial test2 = createHourMinPartial2(ISO_UTC); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); Partial test3 = createHourMinPartial2(COPTIC_UTC); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { createHourMinPartial().isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_TOD() { Partial test1 = createHourMinPartial(); Partial test1a = createHourMinPartial(); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); Partial test2 = createHourMinPartial2(ISO_UTC); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); Partial test3 = createHourMinPartial2(COPTIC_UTC); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { createHourMinPartial().isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_TOD() { Partial test1 = createHourMinPartial(); Partial test1a = createHourMinPartial(); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); Partial test2 = createHourMinPartial2(ISO_UTC); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); Partial test3 = createHourMinPartial2(COPTIC_UTC); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { createHourMinPartial().isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithChronologyRetainFields_Chrono() { Partial base = createHourMinPartial(COPTIC_PARIS); Partial test = base.withChronologyRetainFields(BUDDHIST_TOKYO); check(base, 10, 20); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 10, 20); assertEquals(BUDDHIST_UTC, test.getChronology()); } public void testWithChronologyRetainFields_sameChrono() { Partial base = createHourMinPartial(COPTIC_PARIS); Partial test = base.withChronologyRetainFields(COPTIC_TOKYO); assertSame(base, test); } public void testWithChronologyRetainFields_nullChrono() { Partial base = createHourMinPartial(COPTIC_PARIS); Partial test = base.withChronologyRetainFields(null); check(base, 10, 20); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 10, 20); assertEquals(ISO_UTC, test.getChronology()); } //----------------------------------------------------------------------- public void testWith1() { Partial test = createHourMinPartial(); Partial result = test.with(DateTimeFieldType.hourOfDay(), 15); check(test, 10, 20); check(result, 15, 20); } public void testWith2() { Partial test = createHourMinPartial(); try { test.with(null, 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWith3a() { Partial test = createHourMinPartial(); Partial result = test.with(DateTimeFieldType.secondOfMinute(), 15); check(test, 10, 20); assertEquals(3, result.size()); assertEquals(true, result.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, result.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(true, result.isSupported(DateTimeFieldType.secondOfMinute())); assertEquals(DateTimeFieldType.hourOfDay(), result.getFieldType(0)); assertEquals(DateTimeFieldType.minuteOfHour(), result.getFieldType(1)); assertEquals(DateTimeFieldType.secondOfMinute(), result.getFieldType(2)); assertEquals(10, result.get(DateTimeFieldType.hourOfDay())); assertEquals(20, result.get(DateTimeFieldType.minuteOfHour())); assertEquals(15, result.get(DateTimeFieldType.secondOfMinute())); } public void testWith3b() { Partial test = createHourMinPartial(); Partial result = test.with(DateTimeFieldType.minuteOfDay(), 15); check(test, 10, 20); assertEquals(3, result.size()); assertEquals(true, result.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, result.isSupported(DateTimeFieldType.minuteOfDay())); assertEquals(true, result.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(DateTimeFieldType.hourOfDay(), result.getFieldType(0)); assertEquals(DateTimeFieldType.minuteOfDay(), result.getFieldType(1)); assertEquals(DateTimeFieldType.minuteOfHour(), result.getFieldType(2)); assertEquals(10, result.get(DateTimeFieldType.hourOfDay())); assertEquals(20, result.get(DateTimeFieldType.minuteOfHour())); assertEquals(15, result.get(DateTimeFieldType.minuteOfDay())); } public void testWith3c() { Partial test = createHourMinPartial(); Partial result = test.with(DateTimeFieldType.dayOfMonth(), 15); check(test, 10, 20); assertEquals(3, result.size()); assertEquals(true, result.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(true, result.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, result.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(DateTimeFieldType.dayOfMonth(), result.getFieldType(0)); assertEquals(DateTimeFieldType.hourOfDay(), result.getFieldType(1)); assertEquals(DateTimeFieldType.minuteOfHour(), result.getFieldType(2)); assertEquals(10, result.get(DateTimeFieldType.hourOfDay())); assertEquals(20, result.get(DateTimeFieldType.minuteOfHour())); assertEquals(15, result.get(DateTimeFieldType.dayOfMonth())); } public void testWith3d() { Partial test = new Partial(DateTimeFieldType.year(), 2005); Partial result = test.with(DateTimeFieldType.monthOfYear(), 6); assertEquals(2, result.size()); assertEquals(2005, result.get(DateTimeFieldType.year())); assertEquals(6, result.get(DateTimeFieldType.monthOfYear())); } public void testWith3e() { Partial test = new Partial(DateTimeFieldType.era(), 1); Partial result = test.with(DateTimeFieldType.halfdayOfDay(), 0); assertEquals(2, result.size()); assertEquals(1, result.get(DateTimeFieldType.era())); assertEquals(0, result.get(DateTimeFieldType.halfdayOfDay())); assertEquals(0, result.indexOf(DateTimeFieldType.era())); assertEquals(1, result.indexOf(DateTimeFieldType.halfdayOfDay())); } public void testWith3f() { Partial test = new Partial(DateTimeFieldType.halfdayOfDay(), 0); Partial result = test.with(DateTimeFieldType.era(), 1); assertEquals(2, result.size()); assertEquals(1, result.get(DateTimeFieldType.era())); assertEquals(0, result.get(DateTimeFieldType.halfdayOfDay())); assertEquals(0, result.indexOf(DateTimeFieldType.era())); assertEquals(1, result.indexOf(DateTimeFieldType.halfdayOfDay())); } public void testWith4() { Partial test = createHourMinPartial(); Partial result = test.with(DateTimeFieldType.hourOfDay(), 10); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithout1() { Partial test = createHourMinPartial(); Partial result = test.without(DateTimeFieldType.year()); check(test, 10, 20); check(result, 10, 20); } public void testWithout2() { Partial test = createHourMinPartial(); Partial result = test.without((DateTimeFieldType) null); check(test, 10, 20); check(result, 10, 20); } public void testWithout3() { Partial test = createHourMinPartial(); Partial result = test.without(DateTimeFieldType.hourOfDay()); check(test, 10, 20); assertEquals(1, result.size()); assertEquals(false, result.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, result.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(DateTimeFieldType.minuteOfHour(), result.getFieldType(0)); } public void testWithout4() { Partial test = createHourMinPartial(); Partial result = test.without(DateTimeFieldType.minuteOfHour()); check(test, 10, 20); assertEquals(1, result.size()); assertEquals(true, result.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(false, result.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(DateTimeFieldType.hourOfDay(), result.getFieldType(0)); } public void testWithout5() { Partial test = new Partial(DateTimeFieldType.hourOfDay(), 12); Partial result = test.without(DateTimeFieldType.hourOfDay()); assertEquals(0, result.size()); assertEquals(false, result.isSupported(DateTimeFieldType.hourOfDay())); } //----------------------------------------------------------------------- public void testWithField1() { Partial test = createHourMinPartial(); Partial result = test.withField(DateTimeFieldType.hourOfDay(), 15); check(test, 10, 20); check(result, 15, 20); } public void testWithField2() { Partial test = createHourMinPartial(); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithField3() { Partial test = createHourMinPartial(); try { test.withField(DateTimeFieldType.dayOfMonth(), 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithField4() { Partial test = createHourMinPartial(); Partial result = test.withField(DateTimeFieldType.hourOfDay(), 10); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded1() { Partial test = createHourMinPartial(); Partial result = test.withFieldAdded(DurationFieldType.hours(), 6); assertEquals(createHourMinPartial(), test); check(test, 10, 20); check(result, 16, 20); } public void testWithFieldAdded2() { Partial test = createHourMinPartial(); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithFieldAdded3() { Partial test = createHourMinPartial(); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithFieldAdded4() { Partial test = createHourMinPartial(); Partial result = test.withFieldAdded(DurationFieldType.hours(), 0); assertSame(test, result); } public void testWithFieldAdded5() { Partial test = createHourMinPartial(); try { test.withFieldAdded(DurationFieldType.days(), 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithFieldAdded6() { Partial test = createHourMinPartial(); try { test.withFieldAdded(DurationFieldType.hours(), 16); fail(); } catch (IllegalArgumentException ex) { // expected } check(test, 10, 20); } public void testWithFieldAdded7() { Partial test = createHourMinPartial(23, 59, ISO_UTC); try { test.withFieldAdded(DurationFieldType.minutes(), 1); fail(); } catch (IllegalArgumentException ex) { // expected } check(test, 23, 59); test = createHourMinPartial(23, 59, ISO_UTC); try { test.withFieldAdded(DurationFieldType.hours(), 1); fail(); } catch (IllegalArgumentException ex) { // expected } check(test, 23, 59); } public void testWithFieldAdded8() { Partial test = createHourMinPartial(0, 0, ISO_UTC); try { test.withFieldAdded(DurationFieldType.minutes(), -1); fail(); } catch (IllegalArgumentException ex) { // expected } check(test, 0, 0); test = createHourMinPartial(0, 0, ISO_UTC); try { test.withFieldAdded(DurationFieldType.hours(), -1); fail(); } catch (IllegalArgumentException ex) { // expected } check(test, 0, 0); } //----------------------------------------------------------------------- public void testWithFieldAddWrapped1() { Partial test = createHourMinPartial(); Partial result = test.withFieldAddWrapped(DurationFieldType.hours(), 6); assertEquals(createHourMinPartial(), test); check(test, 10, 20); check(result, 16, 20); } public void testWithFieldAddWrapped2() { Partial test = createHourMinPartial(); try { test.withFieldAddWrapped(null, 0); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithFieldAddWrapped3() { Partial test = createHourMinPartial(); try { test.withFieldAddWrapped(null, 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithFieldAddWrapped4() { Partial test = createHourMinPartial(); Partial result = test.withFieldAddWrapped(DurationFieldType.hours(), 0); assertSame(test, result); } public void testWithFieldAddWrapped5() { Partial test = createHourMinPartial(); try { test.withFieldAddWrapped(DurationFieldType.days(), 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); } public void testWithFieldAddWrapped6() { Partial test = createHourMinPartial(); Partial result = test.withFieldAddWrapped(DurationFieldType.hours(), 16); assertEquals(createHourMinPartial(), test); check(test, 10, 20); check(result, 2, 20); } public void testWithFieldAddWrapped7() { Partial test = createHourMinPartial(23, 59, ISO_UTC); Partial result = test.withFieldAddWrapped(DurationFieldType.minutes(), 1); check(test, 23, 59); check(result, 0, 0); test = createHourMinPartial(23, 59, ISO_UTC); result = test.withFieldAddWrapped(DurationFieldType.hours(), 1); check(test, 23, 59); check(result, 0, 59); } public void testWithFieldAddWrapped8() { Partial test = createHourMinPartial(0, 0, ISO_UTC); Partial result = test.withFieldAddWrapped(DurationFieldType.minutes(), -1); check(test, 0, 0); check(result, 23, 59); test = createHourMinPartial(0, 0, ISO_UTC); result = test.withFieldAddWrapped(DurationFieldType.hours(), -1); check(test, 0, 0); check(result, 23, 0); } //----------------------------------------------------------------------- public void testPlus_RP() { Partial test = createHourMinPartial(BUDDHIST_LONDON); Partial result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8)); check(test, 10, 20); check(result, 15, 26); result = test.plus((ReadablePeriod) null); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { Partial test = createHourMinPartial(BUDDHIST_LONDON); Partial result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); check(test, 10, 20); check(result, 9, 19); result = test.minus((ReadablePeriod) null); assertSame(test, result); } //----------------------------------------------------------------------- public void testToDateTime_RI() { Partial base = createHourMinPartial(COPTIC_PARIS); DateTime dt = new DateTime(0L); // LONDON zone assertEquals("1970-01-01T01:00:00.000+01:00", dt.toString()); DateTime test = base.toDateTime(dt); check(base, 10, 20); assertEquals("1970-01-01T01:00:00.000+01:00", dt.toString()); assertEquals("1970-01-01T10:20:00.000+01:00", test.toString()); } public void testToDateTime_nullRI() { Partial base = createHourMinPartial(1, 2, ISO_UTC); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 1, 2); assertEquals("1970-01-02T01:02:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testProperty() { Partial test = createHourMinPartial(); assertNotNull(test.property(DateTimeFieldType.hourOfDay())); assertNotNull(test.property(DateTimeFieldType.minuteOfHour())); try { test.property(DateTimeFieldType.secondOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Partial test = createHourMinPartial(COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Partial result = (Partial) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); } //----------------------------------------------------------------------- public void testGetFormatter1() { Partial test = new Partial(DateTimeFieldType.year(), 2005); assertEquals("2005", test.getFormatter().print(test)); test = test.with(DateTimeFieldType.monthOfYear(), 6); assertEquals("2005-06", test.getFormatter().print(test)); test = test.with(DateTimeFieldType.dayOfMonth(), 25); assertEquals("2005-06-25", test.getFormatter().print(test)); test = test.without(DateTimeFieldType.monthOfYear()); assertEquals("2005--25", test.getFormatter().print(test)); } public void testGetFormatter2() { Partial test = new Partial(); assertEquals(null, test.getFormatter()); test = test.with(DateTimeFieldType.era(), 1); assertEquals(null, test.getFormatter()); test = test.with(DateTimeFieldType.halfdayOfDay(), 0); assertEquals(null, test.getFormatter()); } public void testGetFormatter3() { Partial test = new Partial(DateTimeFieldType.dayOfWeek(), 5); assertEquals("-W-5", test.getFormatter().print(test)); // contrast with testToString5 test = test.with(DateTimeFieldType.dayOfMonth(), 13); assertEquals("---13", test.getFormatter().print(test)); } //----------------------------------------------------------------------- public void testToString1() { Partial test = createHourMinPartial(); assertEquals("10:20", test.toString()); } public void testToString2() { Partial test = new Partial(); assertEquals("[]", test.toString()); } public void testToString3() { Partial test = new Partial(DateTimeFieldType.year(), 2005); assertEquals("2005", test.toString()); test = test.with(DateTimeFieldType.monthOfYear(), 6); assertEquals("2005-06", test.toString()); test = test.with(DateTimeFieldType.dayOfMonth(), 25); assertEquals("2005-06-25", test.toString()); test = test.without(DateTimeFieldType.monthOfYear()); assertEquals("2005--25", test.toString()); } public void testToString4() { Partial test = new Partial(DateTimeFieldType.dayOfWeek(), 5); assertEquals("-W-5", test.toString()); test = test.with(DateTimeFieldType.dayOfMonth(), 13); assertEquals("[dayOfMonth=13, dayOfWeek=5]", test.toString()); } public void testToString5() { Partial test = new Partial(DateTimeFieldType.era(), 1); assertEquals("[era=1]", test.toString()); test = test.with(DateTimeFieldType.halfdayOfDay(), 0); assertEquals("[era=1, halfdayOfDay=0]", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { Partial test = createHourMinPartial(); assertEquals("\ufffd\ufffd\ufffd\ufffd 10", test.toString("yyyy HH")); assertEquals("10:20", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { Partial test = createHourMinPartial(); assertEquals("10 20", test.toString("H m", Locale.ENGLISH)); assertEquals("10:20", test.toString(null, Locale.ENGLISH)); assertEquals("10 20", test.toString("H m", null)); assertEquals("10:20", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { Partial test = createHourMinPartial(); assertEquals("\ufffd\ufffd\ufffd\ufffd 10", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("10:20", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private Partial createHourMinPartial() { return createHourMinPartial(ISO_UTC); } private Partial createHourMinPartial(Chronology chrono) { return createHourMinPartial(10, 20, chrono); } private Partial createHourMinPartial2(Chronology chrono) { return createHourMinPartial(15, 20, chrono); } private Partial createHourMinPartial(int hour, int min, Chronology chrono) { return new Partial( new DateTimeFieldType[] {DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour()}, new int[] {hour, min}, chrono); } private Partial createTODPartial(Chronology chrono) { return new Partial( new DateTimeFieldType[] { DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour(), DateTimeFieldType.secondOfMinute(), DateTimeFieldType.millisOfSecond()}, new int[] {10, 20, 30, 40}, chrono); } private void check(Partial test, int hour, int min) { assertEquals(test.toString(), hour, test.get(DateTimeFieldType.hourOfDay())); assertEquals(test.toString(), min, test.get(DateTimeFieldType.minuteOfHour())); } } joda-time-2.3/src/test/java/org/joda/time/format/0000755000175000017500000000000012205344143021176 5ustar ebourgebourgjoda-time-2.3/src/test/java/org/joda/time/format/TestISODateTimeFormatParsing.java0000644000175000017500000012652411564251364027470 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; /** * This class is a Junit unit test for ISODateTimeFormat parsing. * * @author Stephen Colebourne */ public class TestISODateTimeFormatParsing extends TestCase { private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestISODateTimeFormatParsing.class); } public TestISODateTimeFormatParsing(String name) { super(name); } protected void setUp() throws Exception { originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(DateTimeZone.forID("Europe/London")); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void test_dateParser() { DateTimeFormatter parser = ISODateTimeFormat.dateParser(); assertParse(parser, true, "2006-06-09"); assertParse(parser, true, "2006-W27-3"); assertParse(parser, true, "2006-123"); assertParse(parser, true, "2006-06-09T+02:00"); assertParse(parser, true, "2006-W27-3T+02:00"); assertParse(parser, true, "2006-123T+02:00"); assertParse(parser, false, "2006-06-09T10:20:30.040"); assertParse(parser, false, "2006-W27-3T10:20:30.040"); assertParse(parser, false, "2006-123T10:20:30.040"); assertParse(parser, false, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, false, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, false, "2006-123T10:20:30.040+02:00"); assertParse(parser, false, "T10:20:30.040"); assertParse(parser, false, "T10.5"); assertParse(parser, false, "T10:20:30.040+02:00"); assertParse(parser, false, "T10.5+02:00"); assertParse(parser, false, "10:20:30.040"); assertParse(parser, false, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); } //----------------------------------------------------------------------- public void test_localDateParser() { DateTimeFormatter parser = ISODateTimeFormat.localDateParser(); assertEquals(DateTimeZone.UTC, parser.getZone()); assertParse(parser, true, "2006-06-09"); assertParse(parser, true, "2006-W27-3"); assertParse(parser, true, "2006-123"); assertParse(parser, false, "2006-06-09T+02:00"); assertParse(parser, false, "2006-W27-3T+02:00"); assertParse(parser, false, "2006-123T+02:00"); assertParse(parser, false, "2006-06-09T10:20:30.040"); assertParse(parser, false, "2006-W27-3T10:20:30.040"); assertParse(parser, false, "2006-123T10:20:30.040"); assertParse(parser, false, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, false, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, false, "2006-123T10:20:30.040+02:00"); assertParse(parser, false, "T10:20:30.040"); assertParse(parser, false, "T10.5"); assertParse(parser, false, "T10:20:30.040+02:00"); assertParse(parser, false, "T10.5+02:00"); assertParse(parser, false, "10:20:30.040"); assertParse(parser, false, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); } //----------------------------------------------------------------------- public void test_dateElementParser() { DateTimeFormatter parser = ISODateTimeFormat.dateElementParser(); assertParse(parser, "2006-06-09", new DateTime(2006, 6, 9, 0, 0, 0, 0)); assertParse(parser, "2006-06-9", new DateTime(2006, 6, 9, 0, 0, 0, 0)); assertParse(parser, "2006-6-09", new DateTime(2006, 6, 9, 0, 0, 0, 0)); assertParse(parser, "2006-6-9", new DateTime(2006, 6, 9, 0, 0, 0, 0)); assertParse(parser, true, "2006-W27-3"); assertParse(parser, true, "2006-123"); assertParse(parser, false, "2006-06-09T+02:00"); assertParse(parser, false, "2006-W27-3T+02:00"); assertParse(parser, false, "2006-123T+02:00"); assertParse(parser, false, "2006-06-09T10:20:30.040"); assertParse(parser, false, "2006-W27-3T10:20:30.040"); assertParse(parser, false, "2006-123T10:20:30.040"); assertParse(parser, false, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, false, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, false, "2006-123T10:20:30.040+02:00"); assertParse(parser, false, "T10:20:30.040"); assertParse(parser, false, "T10.5"); assertParse(parser, false, "T10:20:30.040+02:00"); assertParse(parser, false, "T10.5+02:00"); assertParse(parser, false, "10:20:30.040"); assertParse(parser, false, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); } //----------------------------------------------------------------------- public void test_timeParser() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.timeParser(); assertParse(parser, false, "2006-06-09"); assertParse(parser, false, "2006-W27-3"); assertParse(parser, false, "2006-123"); assertParse(parser, false, "2006-06-09T+02:00"); assertParse(parser, false, "2006-W27-3T+02:00"); assertParse(parser, false, "2006-123T+02:00"); assertParse(parser, false, "2006-06-09T10:20:30.040"); assertParse(parser, false, "2006-W27-3T10:20:30.040"); assertParse(parser, false, "2006-123T10:20:30.040"); assertParse(parser, false, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, false, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, false, "2006-123T10:20:30.040+02:00"); assertParse(parser, "T10:20:30.040000000", new DateTime(1970, 1, 1, 10, 20, 30, 40)); assertParse(parser, "T10:20:30.004", new DateTime(1970, 1, 1, 10, 20, 30, 4)); assertParse(parser, "T10:20:30.040", new DateTime(1970, 1, 1, 10, 20, 30, 40)); assertParse(parser, "T10:20:30.400", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T10.5", new DateTime(1970, 1, 1, 10, 30, 0, 0)); assertParse(parser, "T10:20:30.040+02:00", new DateTime(1970, 1, 1, 8, 20, 30, 40)); assertParse(parser, "T10.5+02:00", new DateTime(1970, 1, 1, 8, 30, 0, 0)); assertParse(parser, true, "10:20:30.040"); assertParse(parser, true, "10.5"); assertParse(parser, true, "10:20:30.040+02:00"); assertParse(parser, true, "10.5+02:00"); } //----------------------------------------------------------------------- public void test_localTimeParser() { DateTimeFormatter parser = ISODateTimeFormat.localTimeParser(); assertEquals(DateTimeZone.UTC, parser.getZone()); assertParse(parser, false, "2006-06-09"); assertParse(parser, false, "2006-W27-3"); assertParse(parser, false, "2006-123"); assertParse(parser, false, "2006-06-09T+02:00"); assertParse(parser, false, "2006-W27-3T+02:00"); assertParse(parser, false, "2006-123T+02:00"); assertParse(parser, false, "2006-06-09T10:20:30.040"); assertParse(parser, false, "2006-W27-3T10:20:30.040"); assertParse(parser, false, "2006-123T10:20:30.040"); assertParse(parser, false, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, false, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, false, "2006-123T10:20:30.040+02:00"); assertParse(parser, true, "T10:20:30.040"); assertParse(parser, true, "T10.5"); assertParse(parser, false, "T10:20:30.040+02:00"); assertParse(parser, false, "T10.5+02:00"); assertParse(parser, true, "10:20:30.040"); assertParse(parser, true, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); assertParse(parser, true, "00:00:10.512345678"); assertEquals(10512, parser.parseMillis("00:00:10.512345678")); } //----------------------------------------------------------------------- public void test_timeElementParser() { DateTimeFormatter parser = ISODateTimeFormat.timeElementParser(); assertParse(parser, false, "2006-06-09"); assertParse(parser, false, "2006-W27-3"); assertParse(parser, false, "2006-123"); assertParse(parser, false, "2006-06-09T+02:00"); assertParse(parser, false, "2006-W27-3T+02:00"); assertParse(parser, false, "2006-123T+02:00"); assertParse(parser, false, "2006-06-09T10:20:30.040"); assertParse(parser, false, "2006-W27-3T10:20:30.040"); assertParse(parser, false, "2006-123T10:20:30.040"); assertParse(parser, false, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, false, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, false, "2006-123T10:20:30.040+02:00"); assertParse(parser, false, "T10:20:30.040"); assertParse(parser, false, "T10.5"); assertParse(parser, false, "T10:20:30.040+02:00"); assertParse(parser, false, "T10.5+02:00"); assertParse(parser, true, "10:20:30.040"); assertParse(parser, true, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); assertParse(parser, true, "00:00:10.512345678"); // result is offset by London DST in 1970-01-01 assertEquals(10512, parser.parseMillis("00:00:10.512345678") + DateTimeZone.getDefault().getOffset(0L)); } //----------------------------------------------------------------------- public void test_dateTimeParser() { DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser(); assertParse(parser, true, "2006-06-09"); assertParse(parser, true, "2006-W27-3"); assertParse(parser, true, "2006-123"); assertParse(parser, true, "2006-06-09T+02:00"); assertParse(parser, true, "2006-W27-3T+02:00"); assertParse(parser, true, "2006-123T+02:00"); assertParse(parser, true, "2006-06-09T10:20:30.040"); assertParse(parser, true, "2006-W27-3T10:20:30.040"); assertParse(parser, true, "2006-123T10:20:30.040"); assertParse(parser, true, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, true, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, true, "2006-123T10:20:30.040+02:00"); assertParse(parser, true, "T10:20:30.040"); assertParse(parser, true, "T10.5"); assertParse(parser, true, "T10:20:30.040+02:00"); assertParse(parser, true, "T10.5+02:00"); assertParse(parser, false, "10:20:30.040"); assertParse(parser, false, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); } //----------------------------------------------------------------------- public void test_dateOptionalTimeParser() { DateTimeFormatter parser = ISODateTimeFormat.dateOptionalTimeParser(); assertParse(parser, true, "2006-06-09"); assertParse(parser, true, "2006-W27-3"); assertParse(parser, true, "2006-123"); assertParse(parser, true, "2006-06-09T+02:00"); assertParse(parser, true, "2006-W27-3T+02:00"); assertParse(parser, true, "2006-123T+02:00"); assertParse(parser, true, "2006-06-09T10:20:30.040"); assertParse(parser, true, "2006-W27-3T10:20:30.040"); assertParse(parser, true, "2006-123T10:20:30.040"); assertParse(parser, true, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, true, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, true, "2006-123T10:20:30.040+02:00"); assertParse(parser, false, "T10:20:30.040"); assertParse(parser, false, "T10.5"); assertParse(parser, false, "T10:20:30.040+02:00"); assertParse(parser, false, "T10.5+02:00"); assertParse(parser, false, "10:20:30.040"); assertParse(parser, false, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); } //----------------------------------------------------------------------- public void test_localDateOptionalTimeParser() { DateTimeFormatter parser = ISODateTimeFormat.localDateOptionalTimeParser(); assertEquals(DateTimeZone.UTC, parser.getZone()); assertParse(parser, true, "2006-06-09"); assertParse(parser, true, "2006-W27-3"); assertParse(parser, true, "2006-123"); assertParse(parser, false, "2006-06-09T+02:00"); assertParse(parser, false, "2006-W27-3T+02:00"); assertParse(parser, false, "2006-123T+02:00"); assertParse(parser, true, "2006-06-09T10:20:30.040"); assertParse(parser, true, "2006-W27-3T10:20:30.040"); assertParse(parser, true, "2006-123T10:20:30.040"); assertParse(parser, false, "2006-06-09T10:20:30.040+02:00"); assertParse(parser, false, "2006-W27-3T10:20:30.040+02:00"); assertParse(parser, false, "2006-123T10:20:30.040+02:00"); assertParse(parser, false, "T10:20:30.040"); assertParse(parser, false, "T10.5"); assertParse(parser, false, "T10:20:30.040+02:00"); assertParse(parser, false, "T10.5+02:00"); assertParse(parser, false, "10:20:30.040"); assertParse(parser, false, "10.5"); assertParse(parser, false, "10:20:30.040+02:00"); assertParse(parser, false, "10.5+02:00"); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_date() { DateTimeFormatter parser = ISODateTimeFormat.date(); assertParse(parser, "2006-02-04", new DateTime(2006, 2, 4, 0, 0, 0, 0)); assertParse(parser, "2006-2-04", new DateTime(2006, 2, 4, 0, 0, 0, 0)); assertParse(parser, "2006-02-4", new DateTime(2006, 2, 4, 0, 0, 0, 0)); assertParse(parser, "2006-2-4", new DateTime(2006, 2, 4, 0, 0, 0, 0)); assertParse(parser, false, "2006-02-"); assertParse(parser, false, "2006-02"); assertParse(parser, false, "2006--4"); assertParse(parser, false, "2006-1"); assertParse(parser, false, "2006"); } //----------------------------------------------------------------------- public void test_time() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.time(); assertParse(parser, "10:20:30.400999999Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.400Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.40Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.4Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "5:6:7.8Z", new DateTime(1970, 1, 1, 5, 6, 7, 800)); assertParse(parser, false, "10:20.400Z"); assertParse(parser, false, "10:2.400Z"); assertParse(parser, false, "10.400Z"); assertParse(parser, false, "1.400Z"); } //----------------------------------------------------------------------- public void test_timeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.timeNoMillis(); assertParse(parser, "10:20:30Z", new DateTime(1970, 1, 1, 10, 20, 30, 0)); assertParse(parser, "5:6:7Z", new DateTime(1970, 1, 1, 5, 6, 7, 0)); assertParse(parser, false, "10:20Z"); assertParse(parser, false, "10:2Z"); assertParse(parser, false, "10Z"); assertParse(parser, false, "1Z"); } //----------------------------------------------------------------------- public void test_tTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.tTime(); assertParse(parser, "T10:20:30.400999999Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T10:20:30.400Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T10:20:30.40Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T10:20:30.4Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T5:6:7.8Z", new DateTime(1970, 1, 1, 5, 6, 7, 800)); assertParse(parser, false, "T10:20.400Z"); assertParse(parser, false, "T102.400Z"); assertParse(parser, false, "T10.400Z"); assertParse(parser, false, "T1.400Z"); } //----------------------------------------------------------------------- public void test_tTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.tTimeNoMillis(); assertParse(parser, "T10:20:30Z", new DateTime(1970, 1, 1, 10, 20, 30, 0)); assertParse(parser, "T5:6:7Z", new DateTime(1970, 1, 1, 5, 6, 7, 0)); assertParse(parser, false, "T10:20Z"); assertParse(parser, false, "T10:2Z"); assertParse(parser, false, "T10Z"); assertParse(parser, false, "T1Z"); } //----------------------------------------------------------------------- public void test_dateTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.dateTime(); assertParse(parser, "2006-02-04T10:20:30.400999999Z", new DateTime(2006, 2, 4, 10, 20, 30, 400)); assertParse(parser, "2006-02-04T10:20:30.400Z", new DateTime(2006, 2, 4, 10, 20, 30, 400)); assertParse(parser, "2006-02-04T10:20:30.40Z", new DateTime(2006, 2, 4, 10, 20, 30, 400)); assertParse(parser, "2006-02-04T10:20:30.4Z", new DateTime(2006, 2, 4, 10, 20, 30, 400)); assertParse(parser, "2006-02-4T10:20:30.400Z", new DateTime(2006, 2, 4, 10, 20, 30, 400)); assertParse(parser, "2006-2-04T10:20:30.400Z", new DateTime(2006, 2, 4, 10, 20, 30, 400)); assertParse(parser, "2006-2-4T10:20:30.400Z", new DateTime(2006, 2, 4, 10, 20, 30, 400)); assertParse(parser, "2006-02-04T5:6:7.800Z", new DateTime(2006, 2, 4, 5, 6, 7, 800)); assertParse(parser, false, "2006-02-T10:20:30.400Z"); assertParse(parser, false, "2006-12T10:20:30.400Z"); assertParse(parser, false, "2006-1T10:20:30.400Z"); assertParse(parser, false, "2006T10:20:30.400Z"); assertParse(parser, false, "200T10:20:30.400Z"); assertParse(parser, false, "20T10:20:30.400Z"); assertParse(parser, false, "2T10:20:30.400Z"); assertParse(parser, false, "2006-02-04T10:20.400Z"); assertParse(parser, false, "2006-02-04T10:2.400Z"); assertParse(parser, false, "2006-02-04T10.400Z"); assertParse(parser, false, "2006-02-04T1.400Z"); } //----------------------------------------------------------------------- public void test_dateTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.dateTimeNoMillis(); assertParse(parser, "2006-02-04T10:20:30Z", new DateTime(2006, 2, 4, 10, 20, 30, 0)); assertParse(parser, "2006-02-4T10:20:30Z", new DateTime(2006, 2, 4, 10, 20, 30, 0)); assertParse(parser, "2006-2-04T10:20:30Z", new DateTime(2006, 2, 4, 10, 20, 30, 0)); assertParse(parser, "2006-2-4T10:20:30Z", new DateTime(2006, 2, 4, 10, 20, 30, 0)); assertParse(parser, "2006-02-04T5:6:7Z", new DateTime(2006, 2, 4, 5, 6, 7, 0)); assertParse(parser, false, "2006-02-T10:20:30Z"); assertParse(parser, false, "2006-12T10:20:30Z"); assertParse(parser, false, "2006-1T10:20:30Z"); assertParse(parser, false, "2006T10:20:30Z"); assertParse(parser, false, "200T10:20:30Z"); assertParse(parser, false, "20T10:20:30Z"); assertParse(parser, false, "2T10:20:30Z"); assertParse(parser, false, "2006-02-04T10:20Z"); assertParse(parser, false, "2006-02-04T10:2Z"); assertParse(parser, false, "2006-02-04T10Z"); assertParse(parser, false, "2006-02-04T1Z"); } //----------------------------------------------------------------------- public void test_ordinalDate() { DateTimeFormatter parser = ISODateTimeFormat.ordinalDate(); assertParse(parser, "2006-123", new DateTime(2006, 1, 1, 0, 0, 0, 0).withDayOfYear(123)); assertParse(parser, "2006-12", new DateTime(2006, 1, 1, 0, 0, 0, 0).withDayOfYear(12)); assertParse(parser, "2006-1", new DateTime(2006, 1, 1, 0, 0, 0, 0).withDayOfYear(1)); assertParse(parser, false, "2006-"); assertParse(parser, false, "2006"); } //----------------------------------------------------------------------- public void test_ordinalDateTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.ordinalDateTime(); assertParse(parser, "2006-123T10:20:30.400999999Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, "2006-123T10:20:30.400Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, "2006-123T10:20:30.40Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, "2006-123T10:20:30.4Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, "2006-12T10:20:30.400Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(12)); assertParse(parser, "2006-1T10:20:30.400Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(1)); assertParse(parser, "2006-123T5:6:7.800Z", new DateTime(2006, 1, 1, 5, 6, 7, 800).withDayOfYear(123)); assertParse(parser, false, "2006-T10:20:30.400Z"); assertParse(parser, false, "2006T10:20:30.400Z"); assertParse(parser, false, "2006-123T10:20.400Z"); assertParse(parser, false, "2006-123T10:2.400Z"); assertParse(parser, false, "2006-123T10.400Z"); assertParse(parser, false, "2006-123T1.400Z"); } //----------------------------------------------------------------------- public void test_ordinalDateTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.ordinalDateTimeNoMillis(); assertParse(parser, "2006-123T10:20:30Z", new DateTime(2006, 1, 1, 10, 20, 30, 0).withDayOfYear(123)); assertParse(parser, "2006-12T10:20:30Z", new DateTime(2006, 1, 1, 10, 20, 30, 0).withDayOfYear(12)); assertParse(parser, "2006-1T10:20:30Z", new DateTime(2006, 1, 1, 10, 20, 30, 0).withDayOfYear(1)); assertParse(parser, "2006-123T5:6:7Z", new DateTime(2006, 1, 1, 5, 6, 7, 0).withDayOfYear(123)); assertParse(parser, false, "2006-T10:20:30Z"); assertParse(parser, false, "2006T10:20:30Z"); assertParse(parser, false, "2006-123T10:20Z"); assertParse(parser, false, "2006-123T10:2Z"); assertParse(parser, false, "2006-123T10Z"); assertParse(parser, false, "2006-123T1Z"); } //----------------------------------------------------------------------- public void test_weekDate() { DateTimeFormatter parser = ISODateTimeFormat.weekDate(); assertParse(parser, "2006-W27-3", new DateTime(2006, 6, 1, 0, 0, 0, 0).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006-W2-3", new DateTime(2006, 6, 1, 0, 0, 0, 0).withWeekOfWeekyear(2).withDayOfWeek(3)); assertParse(parser, false, "2006-W-3"); assertParse(parser, false, "2006-W27-"); assertParse(parser, false, "2006-W27"); assertParse(parser, false, "2006-W2"); assertParse(parser, false, "2006-W"); } //----------------------------------------------------------------------- public void test_weekDateTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.weekDateTime(); assertParse(parser, "2006-W27-3T10:20:30.400999999Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006-W27-3T10:20:30.400Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006-W27-3T10:20:30.40Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006-W27-3T10:20:30.4Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006-W2-3T10:20:30.400Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(2).withDayOfWeek(3)); assertParse(parser, "2006-W27-3T5:6:7.800Z", new DateTime(2006, 6, 1, 5, 6, 7, 800).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, false, "2006-W27-T10:20:30.400Z"); assertParse(parser, false, "2006-W27T10:20:30.400Z"); assertParse(parser, false, "2006-W2T10:20:30.400Z"); assertParse(parser, false, "2006-W-3T10:20:30.400Z"); assertParse(parser, false, "2006-W27-3T10:20.400Z"); assertParse(parser, false, "2006-W27-3T10:2.400Z"); assertParse(parser, false, "2006-W27-3T10.400Z"); assertParse(parser, false, "2006-W27-3T1.400Z"); } //----------------------------------------------------------------------- public void test_weekDateTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.weekDateTimeNoMillis(); assertParse(parser, "2006-W27-3T10:20:30Z", new DateTime(2006, 6, 1, 10, 20, 30, 0).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006-W2-3T10:20:30Z", new DateTime(2006, 6, 1, 10, 20, 30, 0).withWeekOfWeekyear(2).withDayOfWeek(3)); assertParse(parser, "2006-W27-3T5:6:7Z", new DateTime(2006, 6, 1, 5, 6, 7, 0).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, false, "2006-W27-T10:20:30Z"); assertParse(parser, false, "2006-W27T10:20:30Z"); assertParse(parser, false, "2006-W2T10:20:30Z"); assertParse(parser, false, "2006-W-3T10:20:30Z"); assertParse(parser, false, "2006-W27-3T10:20Z"); assertParse(parser, false, "2006-W27-3T10:2Z"); assertParse(parser, false, "2006-W27-3T10Z"); assertParse(parser, false, "2006-W27-3T1Z"); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_basicDate() { DateTimeFormatter parser = ISODateTimeFormat.basicDate(); assertParse(parser, "20060204", new DateTime(2006, 2, 4, 0, 0, 0, 0)); assertParse(parser, false, "2006024"); assertParse(parser, false, "200602"); assertParse(parser, false, "20061"); assertParse(parser, false, "2006"); } //----------------------------------------------------------------------- public void test_basicTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicTime(); assertParse(parser, "102030.400999999Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "102030.400Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "102030.40Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "102030.4Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, false, "10203.400Z"); assertParse(parser, false, "1020.400Z"); assertParse(parser, false, "102.400Z"); assertParse(parser, false, "10.400Z"); assertParse(parser, false, "1.400Z"); } //----------------------------------------------------------------------- public void test_basicTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicTimeNoMillis(); assertParse(parser, "102030Z", new DateTime(1970, 1, 1, 10, 20, 30, 0)); assertParse(parser, false, "10203Z"); assertParse(parser, false, "1020Z"); assertParse(parser, false, "102Z"); assertParse(parser, false, "10Z"); assertParse(parser, false, "1Z"); } //----------------------------------------------------------------------- public void test_basicTTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicTTime(); assertParse(parser, "T102030.400999999Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T102030.400Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T102030.40Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "T102030.4Z", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, false, "T10203.400Z"); assertParse(parser, false, "T1020.400Z"); assertParse(parser, false, "T102.400Z"); assertParse(parser, false, "T10.400Z"); assertParse(parser, false, "T1.400Z"); } //----------------------------------------------------------------------- public void test_basicTTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicTTimeNoMillis(); assertParse(parser, "T102030Z", new DateTime(1970, 1, 1, 10, 20, 30, 0)); assertParse(parser, false, "T10203Z"); assertParse(parser, false, "T1020Z"); assertParse(parser, false, "T102Z"); assertParse(parser, false, "T10Z"); assertParse(parser, false, "T1Z"); } //----------------------------------------------------------------------- public void test_basicDateTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicDateTime(); assertParse(parser, "20061204T102030.400999999Z", new DateTime(2006, 12, 4, 10, 20, 30, 400)); assertParse(parser, "20061204T102030.400Z", new DateTime(2006, 12, 4, 10, 20, 30, 400)); assertParse(parser, "20061204T102030.40Z", new DateTime(2006, 12, 4, 10, 20, 30, 400)); assertParse(parser, "20061204T102030.4Z", new DateTime(2006, 12, 4, 10, 20, 30, 400)); assertParse(parser, false, "2006120T102030.400Z"); assertParse(parser, false, "200612T102030.400Z"); assertParse(parser, false, "20061T102030.400Z"); assertParse(parser, false, "2006T102030.400Z"); assertParse(parser, false, "200T102030.400Z"); assertParse(parser, false, "20T102030.400Z"); assertParse(parser, false, "2T102030.400Z"); assertParse(parser, false, "20061204T10203.400Z"); assertParse(parser, false, "20061204T1020.400Z"); assertParse(parser, false, "20061204T102.400Z"); assertParse(parser, false, "20061204T10.400Z"); assertParse(parser, false, "20061204T1.400Z"); } //----------------------------------------------------------------------- public void test_basicDateTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicDateTimeNoMillis(); assertParse(parser, "20061204T102030Z", new DateTime(2006, 12, 4, 10, 20, 30, 0)); assertParse(parser, false, "2006120T102030Z"); assertParse(parser, false, "200612T102030Z"); assertParse(parser, false, "20061T102030Z"); assertParse(parser, false, "2006T102030Z"); assertParse(parser, false, "200T102030Z"); assertParse(parser, false, "20T102030Z"); assertParse(parser, false, "2T102030Z"); assertParse(parser, false, "20061204T10203Z"); assertParse(parser, false, "20061204T1020Z"); assertParse(parser, false, "20061204T102Z"); assertParse(parser, false, "20061204T10Z"); assertParse(parser, false, "20061204T1Z"); } //----------------------------------------------------------------------- public void test_basicOrdinalDate() { DateTimeFormatter parser = ISODateTimeFormat.basicOrdinalDate(); assertParse(parser, "2006123", new DateTime(2006, 1, 1, 0, 0, 0, 0).withDayOfYear(123)); assertParse(parser, false, "200612"); assertParse(parser, false, "20061"); assertParse(parser, false, "2006"); } //----------------------------------------------------------------------- public void test_basicOrdinalDateTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicOrdinalDateTime(); assertParse(parser, "2006123T102030.400999999Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, "2006123T102030.400Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, "2006123T102030.40Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, "2006123T102030.4Z", new DateTime(2006, 1, 1, 10, 20, 30, 400).withDayOfYear(123)); assertParse(parser, false, "200612T102030.400Z"); assertParse(parser, false, "20061T102030.400Z"); assertParse(parser, false, "2006T102030.400Z"); assertParse(parser, false, "200T102030.400Z"); assertParse(parser, false, "20T102030.400Z"); assertParse(parser, false, "2T102030.400Z"); assertParse(parser, false, "2006123T10203.400Z"); assertParse(parser, false, "2006123T1020.400Z"); assertParse(parser, false, "2006123T102.400Z"); assertParse(parser, false, "2006123T10.400Z"); assertParse(parser, false, "2006123T1.400Z"); } //----------------------------------------------------------------------- public void test_basicOrdinalDateTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicOrdinalDateTimeNoMillis(); assertParse(parser, "2006123T102030Z", new DateTime(2006, 1, 1, 10, 20, 30, 0).withDayOfYear(123)); assertParse(parser, false, "200612T102030Z"); assertParse(parser, false, "20061T102030Z"); assertParse(parser, false, "2006T102030Z"); assertParse(parser, false, "200T102030Z"); assertParse(parser, false, "20T102030Z"); assertParse(parser, false, "2T102030Z"); assertParse(parser, false, "2006123T10203Z"); assertParse(parser, false, "2006123T1020Z"); assertParse(parser, false, "2006123T102Z"); assertParse(parser, false, "2006123T10Z"); assertParse(parser, false, "2006123T1Z"); } //----------------------------------------------------------------------- public void test_basicWeekDate() { DateTimeFormatter parser = ISODateTimeFormat.basicWeekDate(); assertParse(parser, "2006W273", new DateTime(2006, 6, 1, 0, 0, 0, 0).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, false, "2006W27"); assertParse(parser, false, "2006W2"); assertParse(parser, false, "2006W"); } //----------------------------------------------------------------------- public void test_basicWeekDateTime() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicWeekDateTime(); assertParse(parser, "2006W273T102030.400999999Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006W273T102030.400Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006W273T102030.40Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, "2006W273T102030.4Z", new DateTime(2006, 6, 1, 10, 20, 30, 400).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, false, "2006W27T102030.400Z"); assertParse(parser, false, "2006W2T102030.400Z"); assertParse(parser, false, "2006W273T10203.400Z"); assertParse(parser, false, "2006W273T1020.400Z"); assertParse(parser, false, "2006W273T102.400Z"); assertParse(parser, false, "2006W273T10.400Z"); assertParse(parser, false, "2006W273T1.400Z"); } //----------------------------------------------------------------------- public void test_basicWeekDateTimeNoMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.basicWeekDateTimeNoMillis(); assertParse(parser, "2006W273T102030Z", new DateTime(2006, 6, 1, 10, 20, 30, 0).withWeekOfWeekyear(27).withDayOfWeek(3)); assertParse(parser, false, "2006W27T102030Z"); assertParse(parser, false, "2006W2T102030Z"); assertParse(parser, false, "2006W273T10203Z"); assertParse(parser, false, "2006W273T1020Z"); assertParse(parser, false, "2006W273T102Z"); assertParse(parser, false, "2006W273T10Z"); assertParse(parser, false, "2006W273T1Z"); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_hourMinute() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.hourMinute(); assertParse(parser, "10:20", new DateTime(1970, 1, 1, 10, 20, 0, 0)); assertParse(parser, "5:6", new DateTime(1970, 1, 1, 5, 6, 0, 0)); assertParse(parser, false, "10:20:30.400999999"); assertParse(parser, false, "10:20:30.400"); assertParse(parser, false, "10:20:30"); assertParse(parser, false, "10:20.400"); assertParse(parser, false, "10:2.400"); assertParse(parser, false, "10.400"); assertParse(parser, false, "1.400"); } //----------------------------------------------------------------------- public void test_hourMinuteSecond() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.hourMinuteSecond(); assertParse(parser, "10:20:30", new DateTime(1970, 1, 1, 10, 20, 30, 0)); assertParse(parser, "5:6:7", new DateTime(1970, 1, 1, 5, 6, 7, 0)); assertParse(parser, false, "10:20:30.400999999"); assertParse(parser, false, "10:20:30.400"); assertParse(parser, false, "10:20:30.4"); assertParse(parser, false, "10:20.400"); assertParse(parser, false, "10:2.400"); assertParse(parser, false, "10.400"); assertParse(parser, false, "1.400"); } //----------------------------------------------------------------------- public void test_hourMinuteSecondMillis() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.hourMinuteSecondMillis(); assertParse(parser, "10:20:30.400", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.40", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.4", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "5:6:7.8", new DateTime(1970, 1, 1, 5, 6, 7, 800)); assertParse(parser, false, "10:20:30.400999999"); assertParse(parser, false, "10:20.400"); assertParse(parser, false, "10:2.400"); assertParse(parser, false, "10.400"); assertParse(parser, false, "1.400"); } //----------------------------------------------------------------------- public void test_hourMinuteSecondFraction() { DateTimeZone.setDefault(DateTimeZone.UTC); DateTimeFormatter parser = ISODateTimeFormat.hourMinuteSecondFraction(); assertParse(parser, "10:20:30.400999999", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.400", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.40", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "10:20:30.4", new DateTime(1970, 1, 1, 10, 20, 30, 400)); assertParse(parser, "5:6:7.8", new DateTime(1970, 1, 1, 5, 6, 7, 800)); assertParse(parser, false, "10:20.400"); assertParse(parser, false, "10:2.400"); assertParse(parser, false, "10.400"); assertParse(parser, false, "1.400"); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- private void assertParse(DateTimeFormatter parser, boolean expected, String str) { if (expected) { parser.parseMillis(str); } else { try { parser.parseMillis(str); fail(); } catch (IllegalArgumentException ex) { // expected } } } private void assertParse(DateTimeFormatter parser, String str, DateTime expected) { DateTime dt = parser.parseDateTime(str); assertEquals(expected, dt); } } joda-time-2.3/src/test/java/org/joda/time/format/TestDateTimeFormatStyle.java0000644000175000017500000004506411564251364026611 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.text.DateFormat; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; /** * This class is a Junit unit test for DateTimeFormat styles. * * @author Stephen Colebourne */ public class TestDateTimeFormatStyle extends TestCase { private static final Locale UK = Locale.UK; private static final Locale US = Locale.US; private static final Locale FRANCE = Locale.FRANCE; private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final DateTimeZone NEWYORK = DateTimeZone.forID("America/New_York"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFormatStyle.class); } public TestDateTimeFormatStyle(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testForStyle_stringLengths() { try { DateTimeFormat.forStyle(null); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forStyle(""); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forStyle("S"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forStyle("SSS"); fail(); } catch (IllegalArgumentException ex) {} } public void testForStyle_invalidStrings() { try { DateTimeFormat.forStyle("AA"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forStyle("--"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forStyle("ss"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testForStyle_shortDate() throws Exception { DateTimeFormatter f = DateTimeFormat.shortDate(); DateTimeFormatter g = DateTimeFormat.forStyle("S-"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateInstance(DateFormat.SHORT, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateInstance(DateFormat.SHORT, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateInstance(DateFormat.SHORT, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); DateTime date = new DateTime( DateFormat.getDateInstance(DateFormat.SHORT, FRANCE).parse(expect)); assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect)); } public void testForStyle_shortTime() throws Exception { DateTimeFormatter f = DateTimeFormat.shortTime(); DateTimeFormatter g = DateTimeFormat.forStyle("-S"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getTimeInstance(DateFormat.SHORT, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getTimeInstance(DateFormat.SHORT, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); if (TimeZone.getDefault() instanceof SimpleTimeZone) { // skip test, as it needs historical time zone info } else { DateTime date = new DateTime( DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).parse(expect)); assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect)); } } public void testForStyle_shortDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.shortDateTime(); DateTimeFormatter g = DateTimeFormat.forStyle("SS"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); DateTime date = new DateTime( DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, FRANCE).parse(expect)); assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect)); } //----------------------------------------------------------------------- public void testForStyle_mediumDate() throws Exception { DateTimeFormatter f = DateTimeFormat.mediumDate(); DateTimeFormatter g = DateTimeFormat.forStyle("M-"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateInstance(DateFormat.MEDIUM, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateInstance(DateFormat.MEDIUM, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateInstance(DateFormat.MEDIUM, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_mediumTime() throws Exception { DateTimeFormatter f = DateTimeFormat.mediumTime(); DateTimeFormatter g = DateTimeFormat.forStyle("-M"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getTimeInstance(DateFormat.MEDIUM, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getTimeInstance(DateFormat.MEDIUM, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getTimeInstance(DateFormat.MEDIUM, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_mediumDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.mediumDateTime(); DateTimeFormatter g = DateTimeFormat.forStyle("MM"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } //----------------------------------------------------------------------- public void testForStyle_longDate() throws Exception { DateTimeFormatter f = DateTimeFormat.longDate(); DateTimeFormatter g = DateTimeFormat.forStyle("L-"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateInstance(DateFormat.LONG, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateInstance(DateFormat.LONG, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateInstance(DateFormat.LONG, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_longTime() throws Exception { DateTimeFormatter f = DateTimeFormat.longTime(); DateTimeFormatter g = DateTimeFormat.forStyle("-L"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getTimeInstance(DateFormat.LONG, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getTimeInstance(DateFormat.LONG, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getTimeInstance(DateFormat.LONG, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_longDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.longDateTime(); DateTimeFormatter g = DateTimeFormat.forStyle("LL"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } //----------------------------------------------------------------------- public void testForStyle_fullDate() throws Exception { DateTimeFormatter f = DateTimeFormat.fullDate(); DateTimeFormatter g = DateTimeFormat.forStyle("F-"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateInstance(DateFormat.FULL, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateInstance(DateFormat.FULL, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateInstance(DateFormat.FULL, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_fullTime() throws Exception { DateTimeFormatter f = DateTimeFormat.fullTime(); DateTimeFormatter g = DateTimeFormat.forStyle("-F"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getTimeInstance(DateFormat.FULL, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getTimeInstance(DateFormat.FULL, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getTimeInstance(DateFormat.FULL, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_fullDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.fullDateTime(); DateTimeFormatter g = DateTimeFormat.forStyle("FF"); assertSame(g, f); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } //----------------------------------------------------------------------- public void testForStyle_shortMediumDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.forStyle("SM"); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_shortLongDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.forStyle("SL"); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_shortFullDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.forStyle("SF"); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } //----------------------------------------------------------------------- public void testForStyle_mediumShortDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.forStyle("MS"); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_mediumLongDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.forStyle("ML"); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } public void testForStyle_mediumFullDateTime() throws Exception { DateTimeFormatter f = DateTimeFormat.forStyle("MF"); DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0); String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL, UK).format(dt.toDate()); assertEquals(expect, f.print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL, US).format(dt.toDate()); assertEquals(expect, f.withLocale(US).print(dt)); expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL, FRANCE).format(dt.toDate()); assertEquals(expect, f.withLocale(FRANCE).print(dt)); } } joda-time-2.3/src/test/java/org/joda/time/format/TestDateTimeFormatter.java0000644000175000017500000014042212200501234026253 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.CharArrayWriter; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; import org.joda.time.MutableDateTime; import org.joda.time.ReadablePartial; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for DateTime Formating. * * @author Stephen Colebourne */ public class TestDateTimeFormatter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final DateTimeZone NEWYORK = DateTimeZone.forID("America/New_York"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; private DateTimeFormatter f = null; private DateTimeFormatter g = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFormatter.class); } public TestDateTimeFormatter(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); f = new DateTimeFormatterBuilder() .appendDayOfWeekShortText() .appendLiteral(' ') .append(ISODateTimeFormat.dateTimeNoMillis()) .toFormatter(); g = ISODateTimeFormat.dateTimeNoMillis(); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; f = null; g = null; } //----------------------------------------------------------------------- public void testPrint_simple() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T10:20:30Z", f.print(dt)); dt = dt.withZone(PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.print(dt)); } //----------------------------------------------------------------------- public void testPrint_locale() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("mer. 2004-06-09T10:20:30Z", f.withLocale(Locale.FRENCH).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withLocale(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_zone() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withZone(null).print(dt)); dt = dt.withZone(NEWYORK); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withZoneUTC().print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_chrono() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(BUDDHIST_PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(null).print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(BUDDHIST_PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(ISO_UTC).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_bufferMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); StringBuffer buf = new StringBuffer(); f.printTo(buf, dt); assertEquals("Wed 2004-06-09T10:20:30Z", buf.toString()); buf = new StringBuffer(); f.printTo(buf, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", buf.toString()); buf = new StringBuffer(); ISODateTimeFormat.yearMonthDay().printTo(buf, dt.toYearMonthDay()); assertEquals("2004-06-09", buf.toString()); buf = new StringBuffer(); try { ISODateTimeFormat.yearMonthDay().printTo(buf, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_writerMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); CharArrayWriter out = new CharArrayWriter(); f.printTo(out, dt); assertEquals("Wed 2004-06-09T10:20:30Z", out.toString()); out = new CharArrayWriter(); f.printTo(out, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", out.toString()); out = new CharArrayWriter(); ISODateTimeFormat.yearMonthDay().printTo(out, dt.toYearMonthDay()); assertEquals("2004-06-09", out.toString()); out = new CharArrayWriter(); try { ISODateTimeFormat.yearMonthDay().printTo(out, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_appendableMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); StringBuilder buf = new StringBuilder(); f.printTo(buf, dt); assertEquals("Wed 2004-06-09T10:20:30Z", buf.toString()); buf = new StringBuilder(); f.printTo(buf, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", buf.toString()); buf = new StringBuilder(); ISODateTimeFormat.yearMonthDay().printTo(buf, dt.toLocalDate()); assertEquals("2004-06-09", buf.toString()); buf = new StringBuilder(); try { ISODateTimeFormat.yearMonthDay().printTo(buf, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_chrono_and_zone() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); dt = dt.withChronology(ISO_PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2547-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); } public void testWithGetLocale() { DateTimeFormatter f2 = f.withLocale(Locale.FRENCH); assertEquals(Locale.FRENCH, f2.getLocale()); assertSame(f2, f2.withLocale(Locale.FRENCH)); f2 = f.withLocale(null); assertEquals(null, f2.getLocale()); assertSame(f2, f2.withLocale(null)); } public void testWithGetZone() { DateTimeFormatter f2 = f.withZone(PARIS); assertEquals(PARIS, f2.getZone()); assertSame(f2, f2.withZone(PARIS)); f2 = f.withZone(null); assertEquals(null, f2.getZone()); assertSame(f2, f2.withZone(null)); } public void testWithGetChronology() { DateTimeFormatter f2 = f.withChronology(BUDDHIST_PARIS); assertEquals(BUDDHIST_PARIS, f2.getChronology()); assertSame(f2, f2.withChronology(BUDDHIST_PARIS)); f2 = f.withChronology(null); assertEquals(null, f2.getChronology()); assertSame(f2, f2.withChronology(null)); } public void testWithGetPivotYear() { DateTimeFormatter f2 = f.withPivotYear(13); assertEquals(new Integer(13), f2.getPivotYear()); assertSame(f2, f2.withPivotYear(13)); f2 = f.withPivotYear(new Integer(14)); assertEquals(new Integer(14), f2.getPivotYear()); assertSame(f2, f2.withPivotYear(new Integer(14))); f2 = f.withPivotYear(null); assertEquals(null, f2.getPivotYear()); assertSame(f2, f2.withPivotYear(null)); } public void testWithGetOffsetParsedMethods() { DateTimeFormatter f2 = f; assertEquals(false, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f.withOffsetParsed(); assertEquals(true, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f2.withZone(PARIS); assertEquals(false, f2.isOffsetParsed()); assertEquals(PARIS, f2.getZone()); f2 = f2.withOffsetParsed(); assertEquals(true, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f.withOffsetParsed(); assertNotSame(f, f2); DateTimeFormatter f3 = f2.withOffsetParsed(); assertSame(f2, f3); } public void testPrinterParserMethods() { DateTimeFormatter f2 = new DateTimeFormatter(f.getPrinter(), f.getParser()); assertEquals(f.getPrinter(), f2.getPrinter()); assertEquals(f.getParser(), f2.getParser()); assertEquals(true, f2.isPrinter()); assertEquals(true, f2.isParser()); assertNotNull(f2.print(0L)); assertNotNull(f2.parseDateTime("Thu 1970-01-01T00:00:00Z")); f2 = new DateTimeFormatter(f.getPrinter(), null); assertEquals(f.getPrinter(), f2.getPrinter()); assertEquals(null, f2.getParser()); assertEquals(true, f2.isPrinter()); assertEquals(false, f2.isParser()); assertNotNull(f2.print(0L)); try { f2.parseDateTime("Thu 1970-01-01T00:00:00Z"); fail(); } catch (UnsupportedOperationException ex) {} f2 = new DateTimeFormatter(null, f.getParser()); assertEquals(null, f2.getPrinter()); assertEquals(f.getParser(), f2.getParser()); assertEquals(false, f2.isPrinter()); assertEquals(true, f2.isParser()); try { f2.print(0L); fail(); } catch (UnsupportedOperationException ex) {} assertNotNull(f2.parseDateTime("Thu 1970-01-01T00:00:00Z")); } //----------------------------------------------------------------------- public void testParseLocalDate_simple() { assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30Z")); assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30+18:00")); assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30-18:00")); assertEquals(new LocalDate(2004, 6, 9, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalDate("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseLocalDate_yearOfEra() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("YYYY-MM GG") .withChronology(chrono) .withLocale(Locale.UK); LocalDate date = new LocalDate(2005, 10, 1, chrono); assertEquals(date, f.parseLocalDate("2005-10 AD")); assertEquals(date, f.parseLocalDate("2005-10 CE")); date = new LocalDate(-2005, 10, 1, chrono); assertEquals(date, f.parseLocalDate("2005-10 BC")); assertEquals(date, f.parseLocalDate("2005-10 BCE")); } public void testParseLocalDate_yearOfCentury() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("yy M d") .withChronology(chrono) .withLocale(Locale.UK) .withPivotYear(2050); LocalDate date = new LocalDate(2050, 8, 4, chrono); assertEquals(date, f.parseLocalDate("50 8 4")); } public void testParseLocalDate_monthDay_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d") .withChronology(chrono) .withLocale(Locale.UK); assertEquals(new LocalDate(2000, 2, 29, chrono), f.parseLocalDate("2 29")); } public void testParseLocalDate_monthDay_withDefaultYear_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d") .withChronology(chrono) .withLocale(Locale.UK) .withDefaultYear(2012); assertEquals(new LocalDate(2012, 2, 29, chrono), f.parseLocalDate("2 29")); } public void testParseLocalDate_weekyear_month_week_2010() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2010, 1, 4, chrono), f.parseLocalDate("2010-01-01")); } public void testParseLocalDate_weekyear_month_week_2011() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2011, 1, 3, chrono), f.parseLocalDate("2011-01-01")); } public void testParseLocalDate_weekyear_month_week_2012() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 1, 2, chrono), f.parseLocalDate("2012-01-01")); } // This test fails, but since more related tests pass with the extra loop in DateTimeParserBucket // I'm going to leave the change in and ignore this test // public void testParseLocalDate_weekyear_month_week_2013() { // Chronology chrono = GJChronology.getInstanceUTC(); // DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); // assertEquals(new LocalDate(2012, 12, 31, chrono), f.parseLocalDate("2013-01-01")); // } public void testParseLocalDate_year_month_week_2010() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2010, 1, 4, chrono), f.parseLocalDate("2010-01-01")); } public void testParseLocalDate_year_month_week_2011() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2011, 1, 3, chrono), f.parseLocalDate("2011-01-01")); } public void testParseLocalDate_year_month_week_2012() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 1, 2, chrono), f.parseLocalDate("2012-01-01")); } public void testParseLocalDate_year_month_week_2013() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 12, 31, chrono), f.parseLocalDate("2013-01-01")); // 2013-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2014() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2013, 12, 30, chrono), f.parseLocalDate("2014-01-01")); // 2014-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2015() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2014, 12, 29, chrono), f.parseLocalDate("2015-01-01")); // 2015-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2016() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2016, 1, 4, chrono), f.parseLocalDate("2016-01-01")); } //----------------------------------------------------------------------- public void testParseLocalTime_simple() { assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30Z")); assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30+18:00")); assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30-18:00")); assertEquals(new LocalTime(10, 20, 30, 0, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseLocalDateTime_simple() { assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30Z")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30+18:00")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30-18:00")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30, 0, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalDateTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseLocalDateTime_monthDay_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d H m") .withChronology(chrono) .withLocale(Locale.UK); assertEquals(new LocalDateTime(2000, 2, 29, 13, 40, 0, 0, chrono), f.parseLocalDateTime("2 29 13 40")); } public void testParseLocalDateTime_monthDay_withDefaultYear_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d H m") .withChronology(chrono) .withLocale(Locale.UK) .withDefaultYear(2012); assertEquals(new LocalDateTime(2012, 2, 29, 13, 40, 0, 0, chrono), f.parseLocalDateTime("2 29 13 40")); } //----------------------------------------------------------------------- public void testParseDateTime_simple() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.parseDateTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseDateTime_zone() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseDateTime("2004-06-09T10:20:30Z")); } public void testParseDateTime_zone2() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseDateTime("2004-06-09T06:20:30-04:00")); } public void testParseDateTime_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); DateTime expect = null; expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(LONDON).parseDateTime("2004-06-09T10:20:30")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(null).parseDateTime("2004-06-09T10:20:30")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); assertEquals(expect, h.withZone(PARIS).parseDateTime("2004-06-09T10:20:30")); } public void testParseDateTime_simple_precedence() { DateTime expect = null; // use correct day of week expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, f.parseDateTime("Wed 2004-06-09T10:20:30Z")); // use wrong day of week expect = new DateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); // DayOfWeek takes precedence, because week < month in length assertEquals(expect, f.parseDateTime("Mon 2004-06-09T10:20:30Z")); } public void testParseDateTime_offsetParsed() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withZone(PARIS).withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withOffsetParsed().withZone(PARIS).parseDateTime("2004-06-09T10:20:30Z")); } public void testParseDateTime_chrono() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withChronology(ISO_PARIS).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0,LONDON); assertEquals(expect, g.withChronology(null).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2547-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); // zone is +00:09:21 in 1451 assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2004-06-09T10:20:30Z")); } //----------------------------------------------------------------------- public void testParseMutableDateTime_simple() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.parseMutableDateTime("2004-06-09T10:20:30Z")); try { g.parseMutableDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseMutableDateTime_zone() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_zone2() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseMutableDateTime("2004-06-09T06:20:30-04:00")); } public void testParseMutableDateTime_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(LONDON).parseMutableDateTime("2004-06-09T10:20:30")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(null).parseMutableDateTime("2004-06-09T10:20:30")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); assertEquals(expect, h.withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30")); } public void testParseMutableDateTime_simple_precedence() { MutableDateTime expect = null; // use correct day of week expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, f.parseDateTime("Wed 2004-06-09T10:20:30Z")); // use wrong day of week expect = new MutableDateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); // DayOfWeek takes precedence, because week < month in length assertEquals(expect, f.parseDateTime("Mon 2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_offsetParsed() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withOffsetParsed().parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); assertEquals(expect, g.withOffsetParsed().parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withZone(PARIS).withOffsetParsed().parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withOffsetParsed().withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_chrono() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withChronology(ISO_PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0,LONDON); assertEquals(expect, g.withChronology(null).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseMutableDateTime("2547-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); // zone is +00:09:21 in 1451 assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } //----------------------------------------------------------------------- public void testParseInto_simple() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); MutableDateTime result = new MutableDateTime(0L); assertEquals(20, g.parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); try { g.parseInto(null, "2004-06-09T10:20:30Z", 0); fail(); } catch (IllegalArgumentException ex) {} assertEquals(~0, g.parseInto(result, "ABC", 0)); assertEquals(~10, g.parseInto(result, "2004-06-09", 0)); assertEquals(~13, g.parseInto(result, "XX2004-06-09T", 2)); } public void testParseInto_zone() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withZone(LONDON).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withZone(null).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withZone(PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_zone2() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(25, g.withZone(LONDON).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(25, g.withZone(null).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(25, g.withZone(PARIS).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); } public void testParseInto_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(19, h.withZone(LONDON).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(19, h.withZone(null).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(19, h.withZone(PARIS).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); } public void testParseInto_simple_precedence() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); // DayOfWeek takes precedence, because week < month in length assertEquals(24, f.parseInto(result, "Mon 2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_offsetParsed() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); result = new MutableDateTime(0L); assertEquals(20, g.withOffsetParsed().parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); result = new MutableDateTime(0L); assertEquals(25, g.withOffsetParsed().parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); result = new MutableDateTime(0L); assertEquals(20, g.withZone(PARIS).withOffsetParsed().parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withOffsetParsed().withZone(PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_chrono() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(ISO_PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(null).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(BUDDHIST_PARIS).parseInto(result, "2547-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(BUDDHIST_PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_monthOnly() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 9, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthOnly_baseStartYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 1, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_parseStartYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 2, 1, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "1", 0)); assertEquals(new MutableDateTime(2004, 1, 1, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_baseEndYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 31, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_parseEndYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 31, 12, 20, 30, 0,TOKYO); assertEquals(2, f.parseInto(result, "12", 0)); assertEquals(new MutableDateTime(2004, 12, 31, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthDay_feb29() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthDay_feb29_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, LONDON), result); } public void testParseInto_monthDay_feb29_OfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, LONDON), result); } public void testParseInto_monthDay_feb29_newYork() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseInto_monthDay_feb29_newYork_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, NEWYORK), result); } public void testParseInto_monthDay_feb29_newYork_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, NEWYORK), result); } public void testParseInto_monthDay_feb29_tokyo() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthDay_feb29_tokyo_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, TOKYO), result); } public void testParseInto_monthDay_feb29_tokyo_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, TOKYO), result); } public void testParseInto_monthDay_withDefaultYear_feb29() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthDay_withDefaultYear_feb29_newYork() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseInto_monthDay_withDefaultYear_feb29_newYork_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 12, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseMillis_fractionOfSecondLong() { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendSecondOfDay(2).appendLiteral('.').appendFractionOfSecond(1, 9) .toFormatter().withZoneUTC(); assertEquals(10512, f.parseMillis("10.5123456")); assertEquals(10512, f.parseMillis("10.512999")); } //----------------------------------------------------------------------- // Ensure time zone name switches properly at the zone DST transition. public void testZoneNameNearTransition() { DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK); DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK); DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK); DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK); DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S zzzz"); assertEquals("2005-10-30 01:00:00.0 Eastern Daylight Time", fmt.print(inDST_1)); assertEquals("2005-10-30 01:59:59.9 Eastern Daylight Time", fmt.print(inDST_2)); assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(onDST)); assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(outDST)); assertEquals("2005-10-30 02:00:01.0 Eastern Standard Time", fmt.print(outDST_2)); } // Ensure time zone name switches properly at the zone DST transition. public void testZoneShortNameNearTransition() { DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK); DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK); DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK); DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK); DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S z"); assertEquals("2005-10-30 01:00:00.0 EDT", fmt.print(inDST_1)); assertEquals("2005-10-30 01:59:59.9 EDT", fmt.print(inDST_2)); assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(onDST)); assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(outDST)); assertEquals("2005-10-30 02:00:01.0 EST", fmt.print(outDST_2)); } } joda-time-2.3/src/test/java/org/joda/time/format/TestTextFields.java0000644000175000017500000001261111564251364024766 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.MutableDateTime; import org.joda.time.chrono.ISOChronology; /** * Makes sure that text fields are correct for English. * * @author Brian S O'Neill */ public class TestTextFields extends TestCase { private static final DateTimeZone[] ZONES = { DateTimeZone.UTC, DateTimeZone.forID("Europe/Paris"), DateTimeZone.forID("Europe/London"), DateTimeZone.forID("Asia/Tokyo"), DateTimeZone.forID("America/Los_Angeles"), }; private static final String[] MONTHS = { null, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; private static final String[] WEEKDAYS = { null, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; private static final String[] HALFDAYS = { "AM", "PM" }; private DateTimeZone originalDateTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestTextFields.class); } public TestTextFields(String name) { super(name); } protected void setUp() throws Exception { originalDateTimeZone = DateTimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(ZONES[0]); Locale.setDefault(Locale.ENGLISH); } protected void tearDown() throws Exception { DateTimeZone.setDefault(originalDateTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testMonthNames_monthStart() { DateTimeFormatter printer = DateTimeFormat.forPattern("MMMM"); for (int i=0; i lookup = new LinkedHashMap(); lookup.put("GMT", LONDON); lookup.put("BST", LONDON); DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneShortName(lookup); DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); assertEquals(true, f.isPrinter()); assertEquals(true, f.isParser()); DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); assertEquals("2011-01-04 12:30 GMT", f.print(dt1)); DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); assertEquals("2011-07-04 12:30 BST", f.print(dt2)); assertEquals(dt1, f.parseDateTime("2011-01-04 12:30 GMT")); assertEquals(dt2, f.parseDateTime("2011-07-04 12:30 BST")); try { f.parseDateTime("2007-03-04 12:30 EST"); fail(); } catch (IllegalArgumentException e) { } } public void test_printParseShortNameWithAutoLookup() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneShortName(null); DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); assertEquals(true, f.isPrinter()); assertEquals(true, f.isParser()); DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, NEW_YORK); assertEquals("2011-01-04 12:30 EST", f.print(dt1)); DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, NEW_YORK); assertEquals("2011-07-04 12:30 EDT", f.print(dt2)); DateTime dt3 = new DateTime(2011, 1, 4, 12, 30, 0, LOS_ANGELES); assertEquals("2011-01-04 12:30 PST", f.print(dt3)); DateTime dt4 = new DateTime(2011, 7, 4, 12, 30, 0, LOS_ANGELES); assertEquals("2011-07-04 12:30 PDT", f.print(dt4)); DateTime dt5 = new DateTime(2011, 7, 4, 12, 30, 0, DateTimeZone.UTC); assertEquals("2011-07-04 12:30 UTC", f.print(dt5)); assertEquals(dt1.getZone() + " " + f.parseDateTime("2011-01-04 12:30 EST").getZone(), dt1, f.parseDateTime("2011-01-04 12:30 EST")); assertEquals(dt2, f.parseDateTime("2011-07-04 12:30 EDT")); assertEquals(dt3, f.parseDateTime("2011-01-04 12:30 PST")); assertEquals(dt4, f.parseDateTime("2011-07-04 12:30 PDT")); assertEquals(dt5, f.parseDateTime("2011-07-04 12:30 UT")); assertEquals(dt5, f.parseDateTime("2011-07-04 12:30 UTC")); try { f.parseDateTime("2007-03-04 12:30 PPP"); fail(); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- public void test_printParseLongName() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneName(); DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); assertEquals(true, f.isPrinter()); assertEquals(false, f.isParser()); DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); assertEquals("2011-01-04 12:30 Greenwich Mean Time", f.print(dt1)); DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); assertEquals("2011-07-04 12:30 British Summer Time", f.print(dt2)); try { f.parseDateTime("2007-03-04 12:30 GMT"); fail(); } catch (UnsupportedOperationException e) { } } public void test_printParseLongNameWithLookup() { Map lookup = new LinkedHashMap(); lookup.put("Greenwich Mean Time", LONDON); lookup.put("British Summer Time", LONDON); DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneName(lookup); DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); assertEquals(true, f.isPrinter()); assertEquals(true, f.isParser()); DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); assertEquals("2011-01-04 12:30 Greenwich Mean Time", f.print(dt1)); DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); assertEquals("2011-07-04 12:30 British Summer Time", f.print(dt2)); assertEquals(dt1, f.parseDateTime("2011-01-04 12:30 Greenwich Mean Time")); assertEquals(dt2, f.parseDateTime("2011-07-04 12:30 British Summer Time")); try { f.parseDateTime("2007-03-04 12:30 EST"); fail(); } catch (IllegalArgumentException e) { } } } joda-time-2.3/src/test/java/org/joda/time/format/TestPeriodFormatParsing.java0000644000175000017500000001225611564251364026637 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.Period; import org.joda.time.PeriodType; /** * This class is a Junit unit test for PeriodFormat. * * @author Stephen Colebourne */ public class TestPeriodFormatParsing extends TestCase { private static final Period PERIOD = new Period(1, 2, 3, 4, 5, 6, 7, 8); private static final Period EMPTY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0); private static final Period YEAR_DAY_PERIOD = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); private static final Period EMPTY_YEAR_DAY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0, PeriodType.yearDayTime()); private static final Period TIME_PERIOD = new Period(0, 0, 0, 0, 5, 6, 7, 8); private static final Period DATE_PERIOD = new Period(1, 2, 3, 4, 0, 0, 0, 0); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L - 1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPeriodFormatParsing.class); } public TestPeriodFormatParsing(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testParseStandard1() { PeriodFormatter parser = PeriodFormat.getDefault(); Period p = parser.parsePeriod("6 years, 3 months and 2 days"); assertEquals(new Period(6, 3, 0, 2, 0, 0, 0, 0), p); } public void testParseCustom1() { PeriodFormatter formatter = new PeriodFormatterBuilder() .printZeroAlways() .appendHours() .appendSuffix(":") .minimumPrintedDigits(2) .appendMinutes() .toFormatter(); Period p; p = new Period(47, 55, 0, 0); assertEquals("47:55", formatter.print(p)); assertEquals(p, formatter.parsePeriod("47:55")); assertEquals(p, formatter.parsePeriod("047:055")); p = new Period(7, 5, 0, 0); assertEquals("7:05", formatter.print(p)); assertEquals(p, formatter.parsePeriod("7:05")); assertEquals(p, formatter.parsePeriod("7:5")); assertEquals(p, formatter.parsePeriod("07:05")); p = new Period(0, 5, 0, 0); assertEquals("0:05", formatter.print(p)); assertEquals(p, formatter.parsePeriod("0:05")); assertEquals(p, formatter.parsePeriod("0:5")); assertEquals(p, formatter.parsePeriod("00:005")); assertEquals(p, formatter.parsePeriod("0:005")); p = new Period(0, 0, 0, 0); assertEquals("0:00", formatter.print(p)); assertEquals(p, formatter.parsePeriod("0:00")); assertEquals(p, formatter.parsePeriod("0:0")); assertEquals(p, formatter.parsePeriod("00:00")); } } joda-time-2.3/src/test/java/org/joda/time/format/TestISODateTimeFormat.java0000644000175000017500000006237411564251364026146 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.Partial; /** * This class is a Junit unit test for ISODateTimeFormat. * * @author Stephen Colebourne */ public class TestISODateTimeFormat extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestISODateTimeFormat.class); } public TestISODateTimeFormat(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testSubclassableConstructor() { ISODateTimeFormat f = new ISODateTimeFormat() { // test constructor is protected }; assertNotNull(f); } //----------------------------------------------------------------------- public void testFormat_date() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09", ISODateTimeFormat.date().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09", ISODateTimeFormat.date().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09", ISODateTimeFormat.date().print(dt)); } public void testFormat_date_partial() { Partial dt = new Partial( new DateTimeFieldType[] {DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth()}, new int[] {2004, 6, 9}); assertEquals("2004-06-09", ISODateTimeFormat.date().print(dt)); } public void testFormat_time() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("10:20:30.040Z", ISODateTimeFormat.time().print(dt)); dt = dt.withZone(LONDON); assertEquals("11:20:30.040+01:00", ISODateTimeFormat.time().print(dt)); dt = dt.withZone(PARIS); assertEquals("12:20:30.040+02:00", ISODateTimeFormat.time().print(dt)); } public void testFormat_time_partial() { Partial dt = new Partial( new DateTimeFieldType[] {DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour(), DateTimeFieldType.secondOfMinute(), DateTimeFieldType.millisOfSecond()}, new int[] {10, 20, 30, 40}); assertEquals("10:20:30.040", ISODateTimeFormat.time().print(dt)); } public void testFormat_timeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("10:20:30Z", ISODateTimeFormat.timeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("11:20:30+01:00", ISODateTimeFormat.timeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("12:20:30+02:00", ISODateTimeFormat.timeNoMillis().print(dt)); } public void testFormat_timeNoMillis_partial() { Partial dt = new Partial( new DateTimeFieldType[] {DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour(), DateTimeFieldType.secondOfMinute(), DateTimeFieldType.millisOfSecond()}, new int[] {10, 20, 30, 40}); assertEquals("10:20:30", ISODateTimeFormat.timeNoMillis().print(dt)); } public void testFormat_tTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("T10:20:30.040Z", ISODateTimeFormat.tTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("T11:20:30.040+01:00", ISODateTimeFormat.tTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("T12:20:30.040+02:00", ISODateTimeFormat.tTime().print(dt)); } public void testFormat_tTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("T10:20:30Z", ISODateTimeFormat.tTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("T11:20:30+01:00", ISODateTimeFormat.tTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("T12:20:30+02:00", ISODateTimeFormat.tTimeNoMillis().print(dt)); } public void testFormat_dateTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09T10:20:30.040Z", ISODateTimeFormat.dateTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09T11:20:30.040+01:00", ISODateTimeFormat.dateTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09T12:20:30.040+02:00", ISODateTimeFormat.dateTime().print(dt)); // dt = dt.withZone(LONDON); // assertEquals("2004-06-09T11:20:30.040+01:00", ISODateTimeFormat.getInstance(PARIS).dateTime().print(dt)); // // dt = dt.withZone(LONDON); // assertEquals("2004-06-09T12:20:30.040+02:00", ISODateTimeFormat.dateTime().print(dt.getMillis(), PARIS)); // // dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, CopticChronology.getInstance()); // assertEquals("2288-02-19T10:20:30.040Z", ISODateTimeFormat.dateTime().print(dt)); // // dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, CopticChronology.getInstance()); // assertEquals("2004-06-09T10:20:30.040Z", ISODateTimeFormat.getInstance(CopticChronology.getInstance()).dateTime().print(dt)); } public void testFormat_dateTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09T10:20:30Z", ISODateTimeFormat.dateTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09T11:20:30+01:00", ISODateTimeFormat.dateTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09T12:20:30+02:00", ISODateTimeFormat.dateTimeNoMillis().print(dt)); } public void testFormat_ordinalDate() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-161", ISODateTimeFormat.ordinalDate().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-161", ISODateTimeFormat.ordinalDate().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-161", ISODateTimeFormat.ordinalDate().print(dt)); } public void testFormat_ordinalDateTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-161T10:20:30.040Z", ISODateTimeFormat.ordinalDateTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-161T11:20:30.040+01:00", ISODateTimeFormat.ordinalDateTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-161T12:20:30.040+02:00", ISODateTimeFormat.ordinalDateTime().print(dt)); } public void testFormat_ordinalDateTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-161T10:20:30Z", ISODateTimeFormat.ordinalDateTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-161T11:20:30+01:00", ISODateTimeFormat.ordinalDateTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-161T12:20:30+02:00", ISODateTimeFormat.ordinalDateTimeNoMillis().print(dt)); } public void testFormat_weekDate() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-W24-3", ISODateTimeFormat.weekDate().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-W24-3", ISODateTimeFormat.weekDate().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-W24-3", ISODateTimeFormat.weekDate().print(dt)); } public void testFormat_weekDateTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-W24-3T10:20:30.040Z", ISODateTimeFormat.weekDateTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-W24-3T11:20:30.040+01:00", ISODateTimeFormat.weekDateTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-W24-3T12:20:30.040+02:00", ISODateTimeFormat.weekDateTime().print(dt)); } public void testFormat_weekDateTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-W24-3T10:20:30Z", ISODateTimeFormat.weekDateTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-W24-3T11:20:30+01:00", ISODateTimeFormat.weekDateTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-W24-3T12:20:30+02:00", ISODateTimeFormat.weekDateTimeNoMillis().print(dt)); } //----------------------------------------------------------------------- public void testFormat_basicDate() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("20040609", ISODateTimeFormat.basicDate().print(dt)); dt = dt.withZone(LONDON); assertEquals("20040609", ISODateTimeFormat.basicDate().print(dt)); dt = dt.withZone(PARIS); assertEquals("20040609", ISODateTimeFormat.basicDate().print(dt)); } public void testFormat_basicTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("102030.040Z", ISODateTimeFormat.basicTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("112030.040+0100", ISODateTimeFormat.basicTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("122030.040+0200", ISODateTimeFormat.basicTime().print(dt)); } public void testFormat_basicTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("102030Z", ISODateTimeFormat.basicTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("112030+0100", ISODateTimeFormat.basicTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("122030+0200", ISODateTimeFormat.basicTimeNoMillis().print(dt)); } public void testFormat_basicTTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("T102030.040Z", ISODateTimeFormat.basicTTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("T112030.040+0100", ISODateTimeFormat.basicTTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("T122030.040+0200", ISODateTimeFormat.basicTTime().print(dt)); } public void testFormat_basicTTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("T102030Z", ISODateTimeFormat.basicTTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("T112030+0100", ISODateTimeFormat.basicTTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("T122030+0200", ISODateTimeFormat.basicTTimeNoMillis().print(dt)); } public void testFormat_basicDateTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("20040609T102030.040Z", ISODateTimeFormat.basicDateTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("20040609T112030.040+0100", ISODateTimeFormat.basicDateTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("20040609T122030.040+0200", ISODateTimeFormat.basicDateTime().print(dt)); } public void testFormat_basicDateTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("20040609T102030Z", ISODateTimeFormat.basicDateTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("20040609T112030+0100", ISODateTimeFormat.basicDateTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("20040609T122030+0200", ISODateTimeFormat.basicDateTimeNoMillis().print(dt)); } public void testFormat_basicOrdinalDate() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004161", ISODateTimeFormat.basicOrdinalDate().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004161", ISODateTimeFormat.basicOrdinalDate().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004161", ISODateTimeFormat.basicOrdinalDate().print(dt)); } public void testFormat_basicOrdinalDateTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004161T102030.040Z", ISODateTimeFormat.basicOrdinalDateTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004161T112030.040+0100", ISODateTimeFormat.basicOrdinalDateTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004161T122030.040+0200", ISODateTimeFormat.basicOrdinalDateTime().print(dt)); } public void testFormat_basicOrdinalDateTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004161T102030Z", ISODateTimeFormat.basicOrdinalDateTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004161T112030+0100", ISODateTimeFormat.basicOrdinalDateTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004161T122030+0200", ISODateTimeFormat.basicOrdinalDateTimeNoMillis().print(dt)); } public void testFormat_basicWeekDate() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004W243", ISODateTimeFormat.basicWeekDate().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004W243", ISODateTimeFormat.basicWeekDate().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004W243", ISODateTimeFormat.basicWeekDate().print(dt)); } public void testFormat_basicWeekDateTime() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004W243T102030.040Z", ISODateTimeFormat.basicWeekDateTime().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004W243T112030.040+0100", ISODateTimeFormat.basicWeekDateTime().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004W243T122030.040+0200", ISODateTimeFormat.basicWeekDateTime().print(dt)); } public void testFormat_basicWeekDateTimeNoMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004W243T102030Z", ISODateTimeFormat.basicWeekDateTimeNoMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004W243T112030+0100", ISODateTimeFormat.basicWeekDateTimeNoMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004W243T122030+0200", ISODateTimeFormat.basicWeekDateTimeNoMillis().print(dt)); } //----------------------------------------------------------------------- public void testFormat_year() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004", ISODateTimeFormat.year().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004", ISODateTimeFormat.year().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004", ISODateTimeFormat.year().print(dt)); } public void testFormat_yearMonth() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06", ISODateTimeFormat.yearMonth().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06", ISODateTimeFormat.yearMonth().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06", ISODateTimeFormat.yearMonth().print(dt)); } public void testFormat_yearMonthDay() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09", ISODateTimeFormat.yearMonthDay().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09", ISODateTimeFormat.yearMonthDay().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09", ISODateTimeFormat.yearMonthDay().print(dt)); } public void testFormat_weekyear() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004", ISODateTimeFormat.weekyear().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004", ISODateTimeFormat.weekyear().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004", ISODateTimeFormat.weekyear().print(dt)); } public void testFormat_weekyearWeek() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-W24", ISODateTimeFormat.weekyearWeek().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-W24", ISODateTimeFormat.weekyearWeek().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-W24", ISODateTimeFormat.weekyearWeek().print(dt)); } public void testFormat_weekyearWeekDay() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-W24-3", ISODateTimeFormat.weekyearWeekDay().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-W24-3", ISODateTimeFormat.weekyearWeekDay().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-W24-3", ISODateTimeFormat.weekyearWeekDay().print(dt)); } //----------------------------------------------------------------------- public void testFormat_hour() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("10", ISODateTimeFormat.hour().print(dt)); dt = dt.withZone(LONDON); assertEquals("11", ISODateTimeFormat.hour().print(dt)); dt = dt.withZone(PARIS); assertEquals("12", ISODateTimeFormat.hour().print(dt)); } public void testFormat_hourMinute() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("10:20", ISODateTimeFormat.hourMinute().print(dt)); dt = dt.withZone(LONDON); assertEquals("11:20", ISODateTimeFormat.hourMinute().print(dt)); dt = dt.withZone(PARIS); assertEquals("12:20", ISODateTimeFormat.hourMinute().print(dt)); } public void testFormat_hourMinuteSecond() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("10:20:30", ISODateTimeFormat.hourMinuteSecond().print(dt)); dt = dt.withZone(LONDON); assertEquals("11:20:30", ISODateTimeFormat.hourMinuteSecond().print(dt)); dt = dt.withZone(PARIS); assertEquals("12:20:30", ISODateTimeFormat.hourMinuteSecond().print(dt)); } public void testFormat_hourMinuteSecondMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("10:20:30.040", ISODateTimeFormat.hourMinuteSecondMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("11:20:30.040", ISODateTimeFormat.hourMinuteSecondMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("12:20:30.040", ISODateTimeFormat.hourMinuteSecondMillis().print(dt)); } public void testFormat_hourMinuteSecondFraction() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("10:20:30.040", ISODateTimeFormat.hourMinuteSecondFraction().print(dt)); dt = dt.withZone(LONDON); assertEquals("11:20:30.040", ISODateTimeFormat.hourMinuteSecondFraction().print(dt)); dt = dt.withZone(PARIS); assertEquals("12:20:30.040", ISODateTimeFormat.hourMinuteSecondFraction().print(dt)); } //----------------------------------------------------------------------- public void testFormat_dateHour() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09T10", ISODateTimeFormat.dateHour().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09T11", ISODateTimeFormat.dateHour().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09T12", ISODateTimeFormat.dateHour().print(dt)); } public void testFormat_dateHourMinute() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09T10:20", ISODateTimeFormat.dateHourMinute().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09T11:20", ISODateTimeFormat.dateHourMinute().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09T12:20", ISODateTimeFormat.dateHourMinute().print(dt)); } public void testFormat_dateHourMinuteSecond() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09T10:20:30", ISODateTimeFormat.dateHourMinuteSecond().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09T11:20:30", ISODateTimeFormat.dateHourMinuteSecond().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09T12:20:30", ISODateTimeFormat.dateHourMinuteSecond().print(dt)); } public void testFormat_dateHourMinuteSecondMillis() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09T10:20:30.040", ISODateTimeFormat.dateHourMinuteSecondMillis().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09T11:20:30.040", ISODateTimeFormat.dateHourMinuteSecondMillis().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09T12:20:30.040", ISODateTimeFormat.dateHourMinuteSecondMillis().print(dt)); } public void testFormat_dateHourMinuteSecondFraction() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("2004-06-09T10:20:30.040", ISODateTimeFormat.dateHourMinuteSecondFraction().print(dt)); dt = dt.withZone(LONDON); assertEquals("2004-06-09T11:20:30.040", ISODateTimeFormat.dateHourMinuteSecondFraction().print(dt)); dt = dt.withZone(PARIS); assertEquals("2004-06-09T12:20:30.040", ISODateTimeFormat.dateHourMinuteSecondFraction().print(dt)); } } joda-time-2.3/src/test/java/org/joda/time/format/TestPeriodFormat.java0000644000175000017500000004214012071610306025273 0ustar ebourgebourg/* * Copyright 2001-2012 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Period; /** * This class is a Junit unit test for PeriodFormat. * * @author Stephen Colebourne */ public class TestPeriodFormat extends TestCase { private static final Locale EN = new Locale("en"); private static final Locale FR = new Locale("fr"); private static final Locale PT = new Locale("pt"); private static final Locale ES = new Locale("es"); private static final Locale DE = new Locale("de"); private static final Locale NL = new Locale("nl"); private static final Locale DA = new Locale("da"); private static final Locale JA = new Locale("ja"); private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPeriodFormat.class); } public TestPeriodFormat(String name) { super(name); } protected void setUp() throws Exception { originalLocale = Locale.getDefault(); Locale.setDefault(DE); } protected void tearDown() throws Exception { Locale.setDefault(originalLocale); originalLocale = null; } //----------------------------------------------------------------------- public void testSubclassableConstructor() { PeriodFormat f = new PeriodFormat() { // test constructor is protected }; assertNotNull(f); } //----------------------------------------------------------------------- // getDefault() //----------------------------------------------------------------------- public void test_getDefault_formatStandard() { Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 day, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", PeriodFormat.getDefault().print(p)); } //----------------------------------------------------------------------- public void test_getDefault_FormatOneField() { Period p = Period.days(2); assertEquals("2 days", PeriodFormat.getDefault().print(p)); } //----------------------------------------------------------------------- public void test_getDefault_formatTwoFields() { Period p = Period.days(2).withHours(5); assertEquals("2 days and 5 hours", PeriodFormat.getDefault().print(p)); } //----------------------------------------------------------------------- public void test_getDefault_parseOneField() { Period p = Period.days(2); assertEquals(p, PeriodFormat.getDefault().parsePeriod("2 days")); } //----------------------------------------------------------------------- public void test_getDefault_parseTwoFields() { Period p = Period.days(2).withHours(5); assertEquals(p, PeriodFormat.getDefault().parsePeriod("2 days and 5 hours")); } //----------------------------------------------------------------------- public void test_getDefault_checkRedundantSeparator() { try { PeriodFormat.getDefault().parsePeriod("2 days and 5 hours "); fail("No exception was caught"); } catch (Exception e) { assertEquals(IllegalArgumentException.class, e.getClass()); } } //----------------------------------------------------------------------- public void test_getDefault_cached() { assertSame(PeriodFormat.getDefault(), PeriodFormat.getDefault()); } //----------------------------------------------------------------------- // wordBased() - default locale (de) //----------------------------------------------------------------------- public void test_wordBased_default() { Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 Tag, 5 Stunden, 6 Minuten, 7 Sekunden und 8 Millisekunden", PeriodFormat.wordBased().print(p)); } //----------------------------------------------------------------------- // wordBased(Locale.FRENCH) //----------------------------------------------------------------------- public void test_wordBased_fr_formatStandard() { Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 jour, 5 heures, 6 minutes, 7 secondes et 8 millisecondes", PeriodFormat.wordBased(FR).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_fr_FormatOneField() { Period p = Period.days(2); assertEquals("2 jours", PeriodFormat.wordBased(FR).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_fr_formatTwoFields() { Period p = Period.days(2).withHours(5); assertEquals("2 jours et 5 heures", PeriodFormat.wordBased(FR).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_fr_parseOneField() { Period p = Period.days(2); assertEquals(p, PeriodFormat.wordBased(FR).parsePeriod("2 jours")); } //----------------------------------------------------------------------- public void test_wordBased_fr_parseTwoFields() { Period p = Period.days(2).withHours(5); assertEquals(p, PeriodFormat.wordBased(FR).parsePeriod("2 jours et 5 heures")); } //----------------------------------------------------------------------- public void test_wordBased_fr_cached() { assertSame(PeriodFormat.wordBased(FR), PeriodFormat.wordBased(FR)); } //----------------------------------------------------------------------- // wordBased(Locale pt) //----------------------------------------------------------------------- public void test_wordBased_pt_formatStandard() { Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 dia, 5 horas, 6 minutos, 7 segundos e 8 milissegundos", PeriodFormat.wordBased(PT).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_pt_FormatOneField() { Period p = Period.days(2); assertEquals("2 dias", PeriodFormat.wordBased(PT).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_pt_formatTwoFields() { Period p = Period.days(2).withHours(5); assertEquals("2 dias e 5 horas", PeriodFormat.wordBased(PT).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_pt_parseOneField() { Period p = Period.days(2); assertEquals(p, PeriodFormat.wordBased(PT).parsePeriod("2 dias")); } //----------------------------------------------------------------------- public void test_wordBased_pt_parseTwoFields() { Period p = Period.days(2).withHours(5); assertEquals(p, PeriodFormat.wordBased(PT).parsePeriod("2 dias e 5 horas")); } //----------------------------------------------------------------------- public void test_wordBased_pt_cached() { assertSame(PeriodFormat.wordBased(PT), PeriodFormat.wordBased(PT)); } //----------------------------------------------------------------------- // wordBased(Locale es) //----------------------------------------------------------------------- public void test_wordBased_es_formatStandard() { Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 d\u00EDa, 5 horas, 6 minutos, 7 segundos y 8 milisegundos", PeriodFormat.wordBased(ES).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_es_FormatOneField() { Period p = Period.days(2); assertEquals("2 d\u00EDas", PeriodFormat.wordBased(ES).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_es_formatTwoFields() { Period p = Period.days(2).withHours(5); assertEquals("2 d\u00EDas y 5 horas", PeriodFormat.wordBased(ES).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_es_parseOneField() { Period p = Period.days(2); assertEquals(p, PeriodFormat.wordBased(ES).parsePeriod("2 d\u00EDas")); } //----------------------------------------------------------------------- public void test_wordBased_es_parseTwoFields() { Period p = Period.days(2).withHours(5); assertEquals(p, PeriodFormat.wordBased(ES).parsePeriod("2 d\u00EDas y 5 horas")); } //----------------------------------------------------------------------- public void test_wordBased_es_cached() { assertSame(PeriodFormat.wordBased(ES), PeriodFormat.wordBased(ES)); } //----------------------------------------------------------------------- // wordBased(Locale de) //----------------------------------------------------------------------- public void test_wordBased_de_formatStandard() { Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 Tag, 5 Stunden, 6 Minuten, 7 Sekunden und 8 Millisekunden", PeriodFormat.wordBased(DE).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_de_FormatOneField() { Period p = Period.days(2); assertEquals("2 Tage", PeriodFormat.wordBased(DE).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_de_formatTwoFields() { Period p = Period.days(2).withHours(5); assertEquals("2 Tage und 5 Stunden", PeriodFormat.wordBased(DE).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_de_parseOneField() { Period p = Period.days(2); assertEquals(p, PeriodFormat.wordBased(DE).parsePeriod("2 Tage")); } //----------------------------------------------------------------------- public void test_wordBased_de_parseTwoFields() { Period p = Period.days(2).withHours(5); assertEquals(p, PeriodFormat.wordBased(DE).parsePeriod("2 Tage und 5 Stunden")); } //----------------------------------------------------------------------- public void test_wordBased_de_cached() { assertSame(PeriodFormat.wordBased(DE), PeriodFormat.wordBased(DE)); } //----------------------------------------------------------------------- // wordBased(Locale nl) //----------------------------------------------------------------------- public void test_wordBased_nl_formatStandard() { Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 dag, 5 uur, 6 minuten, 7 seconden en 8 milliseconden", PeriodFormat.wordBased(NL).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_nl_FormatOneField() { Period p = Period.days(2); assertEquals("2 dagen", PeriodFormat.wordBased(NL).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_nl_formatTwoFields() { Period p = Period.days(2).withHours(5); assertEquals("2 dagen en 5 uur", PeriodFormat.wordBased(NL).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_nl_parseOneField() { Period p = Period.days(2); assertEquals(p, PeriodFormat.wordBased(NL).parsePeriod("2 dagen")); } //----------------------------------------------------------------------- public void test_wordBased_nl_parseTwoFields() { Period p = Period.days(2).withHours(5); assertEquals(p, PeriodFormat.wordBased(NL).parsePeriod("2 dagen en 5 uur")); } //----------------------------------------------------------------------- public void test_wordBased_nl_cached() { assertSame(PeriodFormat.wordBased(NL), PeriodFormat.wordBased(NL)); } //----------------------------------------------------------------------- // wordBased(Locale da) //----------------------------------------------------------------------- public void test_wordBased_da_formatMultiple() { Period p = new Period(2, 3, 4, 2, 5, 6 ,7, 8); assertEquals("2 \u00E5r, 3 m\u00E5neder, 4 uger, 2 dage, 5 timer, 6 minutter, 7 sekunder og 8 millisekunder", PeriodFormat.wordBased(DA).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_da_formatSinglular() { Period p = new Period(1, 1, 1, 1, 1, 1, 1, 1); assertEquals("1 \u00E5r, 1 m\u00E5ned, 1 uge, 1 dag, 1 time, 1 minut, 1 sekund og 1 millisekund", PeriodFormat.wordBased(DA).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_da_cached() { assertSame(PeriodFormat.wordBased(DA), PeriodFormat.wordBased(DA)); } //----------------------------------------------------------------------- // wordBased(Locale ja) //----------------------------------------------------------------------- public void test_wordBased_ja_formatMultiple() { Period p = new Period(2, 3, 4, 2, 5, 6 ,7, 8); assertEquals("2\u5E743\u304B\u67084\u9031\u95932\u65E55\u6642\u95936\u52067\u79D28\u30DF\u30EA\u79D2", PeriodFormat.wordBased(JA).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_ja_formatSingular() { Period p = new Period(1, 1, 1, 1, 1, 1, 1, 1); assertEquals("1\u5E741\u304B\u67081\u9031\u95931\u65E51\u6642\u95931\u52061\u79D21\u30DF\u30EA\u79D2", PeriodFormat.wordBased(JA).print(p)); } //----------------------------------------------------------------------- public void test_wordBased_ja_cached() { assertSame(PeriodFormat.wordBased(JA), PeriodFormat.wordBased(JA)); } //----------------------------------------------------------------------- public void test_wordBased_ja_parseOneField() { Period p = Period.days(2); assertEquals(p, PeriodFormat.wordBased(JA).parsePeriod("2\u65E5")); } //----------------------------------------------------------------------- public void test_wordBased_ja_parseTwoFields() { Period p = Period.days(2).withHours(5); assertEquals(p, PeriodFormat.wordBased(JA).parsePeriod("2\u65E55\u6642\u9593")); } //----------------------------------------------------------------------- public void test_wordBased_ja_checkRedundantSeparator() { try { // Spaces are not valid separators in Japanese PeriodFormat.wordBased(JA).parsePeriod("2\u65E5 "); fail("No exception was caught"); } catch (Exception e) { assertEquals(IllegalArgumentException.class, e.getClass()); } } //----------------------------------------------------------------------- // Cross check languages //----------------------------------------------------------------------- public void test_wordBased_fr_from_de() { Locale.setDefault(DE); Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 jour, 5 heures, 6 minutes, 7 secondes et 8 millisecondes", PeriodFormat.wordBased(FR).print(p)); } public void test_wordBased_fr_from_nl() { Locale.setDefault(NL); Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 jour, 5 heures, 6 minutes, 7 secondes et 8 millisecondes", PeriodFormat.wordBased(FR).print(p)); } public void test_wordBased_en_from_de() { Locale.setDefault(DE); Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 day, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", PeriodFormat.wordBased(EN).print(p)); } public void test_wordBased_en_from_nl() { Locale.setDefault(NL); Period p = new Period(0, 0, 0, 1, 5, 6 ,7, 8); assertEquals("1 day, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", PeriodFormat.wordBased(EN).print(p)); } } joda-time-2.3/src/test/java/org/joda/time/format/TestDateTimeFormat.java0000644000175000017500000013466011564251364025571 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.chrono.GJChronology; /** * This class is a Junit unit test for DateTime Formating. * * @author Stephen Colebourne * @author Fredrik Borgh */ public class TestDateTimeFormat extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final DateTimeZone NEWYORK = DateTimeZone.forID("America/New_York"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFormat.class); } public TestDateTimeFormat(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testSubclassableConstructor() { DateTimeFormat f = new DateTimeFormat() { // test constructor is protected }; assertNotNull(f); } //----------------------------------------------------------------------- public void testFormat_era() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("G").withLocale(Locale.UK); assertEquals(dt.toString(), "AD", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "AD", f.print(dt)); dt = dt.withZone(PARIS); assertEquals(dt.toString(), "AD", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_centuryOfEra() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("C").withLocale(Locale.UK); assertEquals(dt.toString(), "20", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "20", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "20", f.print(dt)); dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC); assertEquals(dt.toString(), "1", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_yearOfEra() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("Y").withLocale(Locale.UK); assertEquals(dt.toString(), "2004", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "2004", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "2004", f.print(dt)); dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC); assertEquals(dt.toString(), "124", f.print(dt)); // 124th year of BCE } public void testFormat_yearOfEra_twoDigit() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("YY").withLocale(Locale.UK); assertEquals(dt.toString(), "04", f.print(dt)); dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC); assertEquals(dt.toString(), "23", f.print(dt)); // current time set to 2002-06-09 f = f.withZoneUTC(); DateTime expect = null; expect = new DateTime(2004, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("04")); expect = new DateTime(1922, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("22")); expect = new DateTime(2021, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("21")); // Added tests to ensure single sign digit parse fails properly try { f.parseDateTime("-"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+"); fail(); } catch (IllegalArgumentException ex) {} // Added tests for pivot year setting f = f.withPivotYear(new Integer(2050)); expect = new DateTime(2000, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("00")); expect = new DateTime(2099, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("99")); // Added tests to ensure two digit parsing is lenient for DateTimeFormat f = DateTimeFormat.forPattern("YY").withLocale(Locale.UK); f = f.withZoneUTC(); f.parseDateTime("5"); f.parseDateTime("005"); f.parseDateTime("+50"); f.parseDateTime("-50"); } public void testFormat_yearOfEraParse() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("YYYY-MM GG") .withChronology(chrono) .withLocale(Locale.UK); DateTime dt = new DateTime(2005, 10, 1, 0, 0, 0, 0, chrono); assertEquals(dt, f.parseDateTime("2005-10 AD")); assertEquals(dt, f.parseDateTime("2005-10 CE")); dt = new DateTime(-2005, 10, 1, 0, 0, 0, 0, chrono); assertEquals(dt, f.parseDateTime("2005-10 BC")); assertEquals(dt, f.parseDateTime("2005-10 BCE")); } //----------------------------------------------------------------------- public void testFormat_year() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("y").withLocale(Locale.UK); assertEquals(dt.toString(), "2004", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "2004", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "2004", f.print(dt)); dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC); assertEquals(dt.toString(), "-123", f.print(dt)); // Added tests to ensure single sign digit parse fails properly try { f.parseDateTime("-"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+"); fail(); } catch (IllegalArgumentException ex) {} } public void testFormat_year_twoDigit() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("yy").withLocale(Locale.UK); assertEquals(dt.toString(), "04", f.print(dt)); dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC); assertEquals(dt.toString(), "23", f.print(dt)); // current time set to 2002-06-09 f = f.withZoneUTC(); DateTime expect = null; expect = new DateTime(2004, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("04")); expect = new DateTime(1922, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("22")); expect = new DateTime(2021, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("21")); // Added tests to ensure single sign digit parse fails properly try { f.parseDateTime("-"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+"); fail(); } catch (IllegalArgumentException ex) {} // Added tests for pivot year setting f = f.withPivotYear(new Integer(2050)); expect = new DateTime(2000, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("00")); expect = new DateTime(2099, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("99")); // Added tests to ensure two digit parsing is strict by default for // DateTimeFormatterBuilder f = new DateTimeFormatterBuilder().appendTwoDigitYear(2000).toFormatter(); f = f.withZoneUTC(); try { f.parseDateTime("5"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("005"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+50"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("-50"); fail(); } catch (IllegalArgumentException ex) {} // Added tests to ensure two digit parsing is lenient for DateTimeFormat f = DateTimeFormat.forPattern("yy").withLocale(Locale.UK); f = f.withZoneUTC(); f.parseDateTime("5"); f.parseDateTime("005"); f.parseDateTime("+50"); f.parseDateTime("-50"); // Added tests for lenient two digit parsing f = new DateTimeFormatterBuilder().appendTwoDigitYear(2000, true).toFormatter(); f = f.withZoneUTC(); expect = new DateTime(2004, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("04")); expect = new DateTime(4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("+04")); expect = new DateTime(-4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-04")); expect = new DateTime(4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("4")); expect = new DateTime(-4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-4")); expect = new DateTime(4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("004")); expect = new DateTime(4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("+004")); expect = new DateTime(-4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-004")); expect = new DateTime(3004, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("3004")); expect = new DateTime(3004, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("+3004")); expect = new DateTime(-3004, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-3004")); try { f.parseDateTime("-"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+"); fail(); } catch (IllegalArgumentException ex) {} } public void testFormat_year_long() { DateTime dt = new DateTime(278004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy"); assertEquals(dt.toString(), "278004", f.print(dt)); // for coverage f = DateTimeFormat.forPattern("yyyyMMdd"); assertEquals(dt.toString(), "2780040609", f.print(dt)); // for coverage f = DateTimeFormat.forPattern("yyyyddMM"); assertEquals(dt.toString(), "2780040906", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_weekyear() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("x").withLocale(Locale.UK); assertEquals(dt.toString(), "2004", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "2004", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "2004", f.print(dt)); dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC); assertEquals(dt.toString(), "-123", f.print(dt)); } public void testFormat_weekyearOfEra_twoDigit() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("xx").withLocale(Locale.UK); assertEquals(dt.toString(), "04", f.print(dt)); dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC); assertEquals(dt.toString(), "23", f.print(dt)); // current time set to 2002-06-09 f = f.withZoneUTC(); DateTime expect = null; expect = new DateTime(2003, 12, 29, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("04")); expect = new DateTime(1922, 1, 2, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("22")); expect = new DateTime(2021, 1, 4, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("21")); // Added tests to ensure single sign digit parse fails properly try { f.parseDateTime("-"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+"); fail(); } catch (IllegalArgumentException ex) {} // Added tests for pivot year setting f = f.withPivotYear(new Integer(2050)); expect = new DateTime(2000, 1, 3, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals(expect, f.parseDateTime("00")); expect = new DateTime(2098, 12, 29, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals(expect, f.parseDateTime("99")); // Added tests to ensure two digit parsing is strict by default for // DateTimeFormatterBuilder f = new DateTimeFormatterBuilder().appendTwoDigitWeekyear(2000).toFormatter(); f = f.withZoneUTC(); try { f.parseDateTime("5"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("005"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+50"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("-50"); fail(); } catch (IllegalArgumentException ex) {} // Added tests to ensure two digit parsing is lenient for DateTimeFormat f = DateTimeFormat.forPattern("xx").withLocale(Locale.UK); f = f.withZoneUTC(); f.parseDateTime("5"); f.parseDateTime("005"); f.parseDateTime("+50"); f.parseDateTime("-50"); // Added tests for lenient two digit parsing f = new DateTimeFormatterBuilder().appendTwoDigitWeekyear(2000, true).toFormatter(); f = f.withZoneUTC(); expect = new DateTime(2003, 12, 29, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("04")); expect = new DateTime(3, 12, 29, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("+04")); expect = new DateTime(-4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-04")); expect = new DateTime(3, 12, 29, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("4")); expect = new DateTime(-4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-4")); expect = new DateTime(3, 12, 29, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("004")); expect = new DateTime(3, 12, 29, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("+004")); expect = new DateTime(-4, 1, 1, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-004")); expect = new DateTime(3004, 1, 2, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("3004")); expect = new DateTime(3004, 1, 2, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("+3004")); expect = new DateTime(-3004, 1, 4, 0, 0, 0, 0, UTC); assertEquals(expect, f.parseDateTime("-3004")); try { f.parseDateTime("-"); fail(); } catch (IllegalArgumentException ex) {} try { f.parseDateTime("+"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFormat_weekOfWeekyear() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("w").withLocale(Locale.UK); assertEquals(dt.toString(), "24", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "24", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "24", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_dayOfWeek() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("e").withLocale(Locale.UK); assertEquals(dt.toString(), "3", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "3", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "3", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_dayOfWeekShortText() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("E").withLocale(Locale.UK); assertEquals(dt.toString(), "Wed", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "Wed", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "Wed", f.print(dt)); f = f.withLocale(Locale.FRENCH); assertEquals(dt.toString(), "mer.", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_dayOfWeekText() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("EEEE").withLocale(Locale.UK); assertEquals(dt.toString(), "Wednesday", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "Wednesday", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "Wednesday", f.print(dt)); f = f.withLocale(Locale.FRENCH); assertEquals(dt.toString(), "mercredi", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_dayOfYearText() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("D").withLocale(Locale.UK); assertEquals(dt.toString(), "161", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "161", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "161", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_monthOfYear() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); assertEquals(dt.toString(), "6", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "6", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "6", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_monthOfYearShortText() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("MMM").withLocale(Locale.UK); assertEquals(dt.toString(), "Jun", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "Jun", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "Jun", f.print(dt)); f = f.withLocale(Locale.FRENCH); assertEquals(dt.toString(), "juin", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_monthOfYearText() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("MMMM").withLocale(Locale.UK); assertEquals(dt.toString(), "June", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "June", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "June", f.print(dt)); f = f.withLocale(Locale.FRENCH); assertEquals(dt.toString(), "juin", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_dayOfMonth() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("d").withLocale(Locale.UK); assertEquals(dt.toString(), "9", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "9", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "9", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_halfdayOfDay() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("a").withLocale(Locale.UK); assertEquals(dt.toString(), "AM", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "AM", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "PM", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_hourOfHalfday() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("K").withLocale(Locale.UK); assertEquals(dt.toString(), "10", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "6", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "7", f.print(dt)); dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, UTC); assertEquals(dt.toString(), "0", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_clockhourOfHalfday() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("h").withLocale(Locale.UK); assertEquals(dt.toString(), "10", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "6", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "7", f.print(dt)); dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, UTC); assertEquals(dt.toString(), "12", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_hourOfDay() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("H").withLocale(Locale.UK); assertEquals(dt.toString(), "10", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "6", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "19", f.print(dt)); dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, UTC); assertEquals(dt.toString(), "0", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_clockhourOfDay() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("k").withLocale(Locale.UK); assertEquals(dt.toString(), "10", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "6", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "19", f.print(dt)); dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, UTC); assertEquals(dt.toString(), "24", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_minute() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("m").withLocale(Locale.UK); assertEquals(dt.toString(), "20", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "20", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "20", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_second() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("s").withLocale(Locale.UK); assertEquals(dt.toString(), "30", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "30", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "30", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_fractionOfSecond() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("SSS").withLocale(Locale.UK); assertEquals(dt.toString(), "040", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "040", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "040", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_fractionOfSecondLong() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("SSSSSS").withLocale(Locale.UK); assertEquals(dt.toString(), "040000", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "040000", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "040000", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_zoneText() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("z").withLocale(Locale.UK); assertEquals(dt.toString(), "UTC", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "EDT", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "JST", f.print(dt)); } public void testFormat_zoneLongText() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("zzzz").withLocale(Locale.UK); assertEquals(dt.toString(), "Coordinated Universal Time", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "Eastern Daylight Time", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "Japan Standard Time", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_zoneAmount() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("Z").withLocale(Locale.UK); assertEquals(dt.toString(), "+0000", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "-0400", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "+0900", f.print(dt)); } public void testFormat_zoneAmountColon() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("ZZ").withLocale(Locale.UK); assertEquals(dt.toString(), "+00:00", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "-04:00", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "+09:00", f.print(dt)); } public void testFormat_zoneAmountID() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("ZZZ").withLocale(Locale.UK); assertEquals(dt.toString(), "UTC", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals(dt.toString(), "America/New_York", f.print(dt)); dt = dt.withZone(TOKYO); assertEquals(dt.toString(), "Asia/Tokyo", f.print(dt)); } //----------------------------------------------------------------------- public void testFormat_other() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("'Hello' ''"); assertEquals("Hello '", f.print(dt)); } public void testFormat_invalid() { try { DateTimeFormat.forPattern(null); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forPattern(""); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forPattern("A"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeFormat.forPattern("dd/mm/AA"); fail(); } catch (IllegalArgumentException ex) {} } public void testFormat_samples() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH.mm.ss"); assertEquals("2004-06-09 10.20.30", f.print(dt)); } public void testFormat_shortBasicParse() { // Tests special two digit parse to make sure it properly switches // between lenient and strict parsing. DateTime dt = new DateTime(2004, 3, 9, 0, 0, 0, 0); DateTimeFormatter f = DateTimeFormat.forPattern("yyMMdd"); assertEquals(dt, f.parseDateTime("040309")); try { assertEquals(dt, f.parseDateTime("20040309")); fail(); } catch (IllegalArgumentException ex) {} f = DateTimeFormat.forPattern("yy/MM/dd"); assertEquals(dt, f.parseDateTime("04/03/09")); assertEquals(dt, f.parseDateTime("2004/03/09")); } //----------------------------------------------------------------------- public void testParse_pivotYear() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd.MM.yy").withPivotYear(2050).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("25.12.15"); assertEquals(date.getYear(), 2015); date = dateFormatter.parseDateTime("25.12.00"); assertEquals(date.getYear(), 2000); date = dateFormatter.parseDateTime("25.12.99"); assertEquals(date.getYear(), 2099); } public void testParse_pivotYear_ignored4DigitYear() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd.MM.yyyy").withPivotYear(2050).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("25.12.15"); assertEquals(date.getYear(), 15); date = dateFormatter.parseDateTime("25.12.00"); assertEquals(date.getYear(), 0); date = dateFormatter.parseDateTime("25.12.99"); assertEquals(date.getYear(), 99); } //----------------------------------------------------------------------- public void testFormatParse_textMonthJanShort_UK() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.UK).withZoneUTC(); String str = new DateTime(2007, 1, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals(str, "23 Jan 2007"); DateTime date = dateFormatter.parseDateTime(str); check(date, 2007, 1, 23); } public void testFormatParse_textMonthJanShortLowerCase_UK() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.UK).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("23 jan 2007"); check(date, 2007, 1, 23); } public void testFormatParse_textMonthJanShortUpperCase_UK() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.UK).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("23 JAN 2007"); check(date, 2007, 1, 23); } public void testParse_textMonthJanLong_UK() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.UK).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("23 January 2007"); check(date, 2007, 1, 23); } public void testFormatParse_textMonthJanLongLowerCase_UK() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.UK).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("23 january 2007"); check(date, 2007, 1, 23); } public void testFormatParse_textMonthJanLongUpperCase_UK() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.UK).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("23 JANUARY 2007"); check(date, 2007, 1, 23); } public void testFormatParse_textMonthJanShort_France() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.FRANCE).withZoneUTC(); String str = new DateTime(2007, 1, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("23 janv. 2007", str); DateTime date = dateFormatter.parseDateTime(str); check(date, 2007, 1, 23); } public void testFormatParse_textMonthJanLong_France() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.FRANCE).withZoneUTC(); DateTime date = dateFormatter.parseDateTime("23 janvier 2007"); check(date, 2007, 1, 23); } public void testFormatParse_textMonthApr_France() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM yyyy") .withLocale(Locale.FRANCE).withZoneUTC(); String str = new DateTime(2007, 2, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("23 f\u00E9vr. 2007", str); // e acute DateTime date = dateFormatter.parseDateTime(str); check(date, 2007, 2, 23); } public void testFormatParse_textMonthAtEnd_France() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM") .withLocale(Locale.FRANCE).withZoneUTC(); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("23 juin", str); DateTime date = dateFormatter.parseDateTime(str); check(date, 2000, 6, 23); } public void testFormatParse_textMonthAtEnd_France_withSpecifiedDefault() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("dd MMM") .withLocale(Locale.FRANCE).withZoneUTC().withDefaultYear(1980); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("23 juin", str); DateTime date = dateFormatter.parseDateTime(str); check(date, 1980, 6, 23); } public void testFormatParse_textMonthApr_Korean() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEEE, d MMMM yyyy HH:mm") .withLocale(Locale.KOREAN).withZoneUTC(); String str = new DateTime(2007, 3, 8, 22, 0, 0, 0, UTC).toString(dateFormatter); DateTime date = dateFormatter.parseDateTime(str); assertEquals(new DateTime(2007, 3, 8, 22, 0, 0, 0, UTC), date); } //----------------------------------------------------------------------- public void testFormatParse_textHalfdayAM_UK() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendClockhourOfHalfday(2) .appendLiteral('-') .appendHalfdayOfDayText() .appendLiteral('-') .appendYear(4, 4) .toFormatter() .withLocale(Locale.UK).withZoneUTC(); String str = new DateTime(2007, 6, 23, 18, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$06-PM-2007", str); DateTime date = dateFormatter.parseDateTime(str); check(date, 2007, 1, 1); } public void testFormatParse_textHalfdayAM_France() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendClockhourOfHalfday(2) .appendLiteral('-') .appendHalfdayOfDayText() .appendLiteral('-') .appendYear(4, 4) .toFormatter() .withLocale(Locale.FRANCE).withZoneUTC(); String str = new DateTime(2007, 6, 23, 18, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$06-PM-2007", str); DateTime date = dateFormatter.parseDateTime(str); check(date, 2007, 1, 1); } //----------------------------------------------------------------------- public void testFormatParse_textEraAD_UK() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendEraText() .appendYear(4, 4) .toFormatter() .withLocale(Locale.UK).withZoneUTC(); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$AD2007", str); DateTime date = dateFormatter.parseDateTime(str); check(date, 2007, 1, 1); } public void testFormatParse_textEraAD_France() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendEraText() .appendYear(4, 4) .toFormatter() .withLocale(Locale.FRANCE).withZoneUTC(); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$ap. J.-C.2007", str); DateTime date = dateFormatter.parseDateTime(str); check(date, 2007, 1, 1); } public void testFormatParse_textEraBC_France() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendEraText() .appendYear(4, 4) .toFormatter() .withLocale(Locale.FRANCE).withZoneUTC(); String str = new DateTime(-1, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$BC-0001", str); DateTime date = dateFormatter.parseDateTime(str); check(date, -1, 1, 1); } //----------------------------------------------------------------------- public void testFormatParse_textYear_UK() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendText(DateTimeFieldType.year()) .toFormatter() .withLocale(Locale.UK).withZoneUTC(); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$2007", str); try { dateFormatter.parseDateTime(str); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testFormatParse_textYear_France() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendText(DateTimeFieldType.year()) .toFormatter() .withLocale(Locale.FRANCE).withZoneUTC(); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$2007", str); try { dateFormatter.parseDateTime(str); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- public void testFormatParse_textAdjoiningHelloWorld_UK() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendDayOfMonth(2) .appendMonthOfYearShortText() .appendLiteral("HelloWorld") .toFormatter() .withLocale(Locale.UK).withZoneUTC(); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$23JunHelloWorld", str); dateFormatter.parseDateTime(str); } public void testFormatParse_textAdjoiningMonthDOW_UK() { DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder() .appendLiteral('$') .appendDayOfMonth(2) .appendMonthOfYearShortText() .appendDayOfWeekShortText() .toFormatter() .withLocale(Locale.UK).withZoneUTC(); String str = new DateTime(2007, 6, 23, 0, 0, 0, 0, UTC).toString(dateFormatter); assertEquals("$23JunSat", str); dateFormatter.parseDateTime(str); } //----------------------------------------------------------------------- public void testFormatParse_zoneId_noColon() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("HH:mm Z").withZoneUTC(); String str = new DateTime(2007, 6, 23, 1, 2, 0, 0, UTC).toString(dateFormatter); assertEquals("01:02 +0000", str); DateTime parsed = dateFormatter.parseDateTime(str); assertEquals(1, parsed.getHourOfDay()); assertEquals(2, parsed.getMinuteOfHour()); } public void testFormatParse_zoneId_noColon_parseZ() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("HH:mm Z").withZoneUTC(); DateTime parsed = dateFormatter.parseDateTime("01:02 Z"); assertEquals(1, parsed.getHourOfDay()); assertEquals(2, parsed.getMinuteOfHour()); } public void testFormatParse_zoneId_colon() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("HH:mm ZZ").withZoneUTC(); String str = new DateTime(2007, 6, 23, 1, 2, 0, 0, UTC).toString(dateFormatter); assertEquals("01:02 +00:00", str); DateTime parsed = dateFormatter.parseDateTime(str); assertEquals(1, parsed.getHourOfDay()); assertEquals(2, parsed.getMinuteOfHour()); } public void testFormatParse_zoneId_colon_parseZ() { DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("HH:mm ZZ").withZoneUTC(); DateTime parsed = dateFormatter.parseDateTime("01:02 Z"); assertEquals(1, parsed.getHourOfDay()); assertEquals(2, parsed.getMinuteOfHour()); } //----------------------------------------------------------------------- private void check(DateTime test, int hour, int min, int sec) { assertEquals(hour, test.getYear()); assertEquals(min, test.getMonthOfYear()); assertEquals(sec, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/format/TestISOPeriodFormat.java0000644000175000017500000002432312021106430025642 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.Period; import org.joda.time.PeriodType; /** * This class is a Junit unit test for ISOPeriodFormat. * * @author Stephen Colebourne */ public class TestISOPeriodFormat extends TestCase { private static final Period PERIOD = new Period(1, 2, 3, 4, 5, 6, 7, 8); private static final Period EMPTY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0); private static final Period YEAR_DAY_PERIOD = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); private static final Period EMPTY_YEAR_DAY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0, PeriodType.yearDayTime()); private static final Period TIME_PERIOD = new Period(0, 0, 0, 0, 5, 6, 7, 8); private static final Period DATE_PERIOD = new Period(1, 2, 3, 4, 0, 0, 0, 0); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestISOPeriodFormat.class); } public TestISOPeriodFormat(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testSubclassableConstructor() { ISOPeriodFormat f = new ISOPeriodFormat() { // test constructor is protected }; assertNotNull(f); } //----------------------------------------------------------------------- public void testFormatStandard() { Period p = new Period(1, 2, 3, 4, 5, 6, 7, 8); assertEquals("P1Y2M3W4DT5H6M7.008S", ISOPeriodFormat.standard().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P1Y2M3W4DT5H6M7S", ISOPeriodFormat.standard().print(p)); p = new Period(0); assertEquals("PT0S", ISOPeriodFormat.standard().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("PT0M", ISOPeriodFormat.standard().print(p)); assertEquals("P1Y4DT5H6M7.008S", ISOPeriodFormat.standard().print(YEAR_DAY_PERIOD)); assertEquals("PT0S", ISOPeriodFormat.standard().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P1Y2M3W4D", ISOPeriodFormat.standard().print(DATE_PERIOD)); assertEquals("PT5H6M7.008S", ISOPeriodFormat.standard().print(TIME_PERIOD)); } public void testFormatStandard_negative() { Period p = new Period(-1, -2, -3, -4, -5, -6, -7, -8); assertEquals("P-1Y-2M-3W-4DT-5H-6M-7.008S", ISOPeriodFormat.standard().print(p)); p = Period.years(-54); assertEquals("P-54Y", ISOPeriodFormat.standard().print(p)); p = Period.seconds(4).withMillis(-8); assertEquals("PT3.992S", ISOPeriodFormat.standard().print(p)); p = Period.seconds(-4).withMillis(8); assertEquals("PT-3.992S", ISOPeriodFormat.standard().print(p)); p = Period.seconds(-23); assertEquals("PT-23S", ISOPeriodFormat.standard().print(p)); p = Period.millis(-8); assertEquals("PT-0.008S", ISOPeriodFormat.standard().print(p)); } //----------------------------------------------------------------------- public void testFormatAlternate() { Period p = new Period(1, 2, 3, 4, 5, 6 ,7, 8); assertEquals("P00010204T050607.008", ISOPeriodFormat.alternate().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P00010204T050607", ISOPeriodFormat.alternate().print(p)); p = new Period(0); assertEquals("P00000000T000000", ISOPeriodFormat.alternate().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("P00000000T000000", ISOPeriodFormat.alternate().print(p)); assertEquals("P00010004T050607.008", ISOPeriodFormat.alternate().print(YEAR_DAY_PERIOD)); assertEquals("P00000000T000000", ISOPeriodFormat.alternate().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P00010204T000000", ISOPeriodFormat.alternate().print(DATE_PERIOD)); assertEquals("P00000000T050607.008", ISOPeriodFormat.alternate().print(TIME_PERIOD)); } //----------------------------------------------------------------------- public void testFormatAlternateExtended() { Period p = new Period(1, 2, 3, 4, 5, 6 ,7, 8); assertEquals("P0001-02-04T05:06:07.008", ISOPeriodFormat.alternateExtended().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P0001-02-04T05:06:07", ISOPeriodFormat.alternateExtended().print(p)); p = new Period(0); assertEquals("P0000-00-00T00:00:00", ISOPeriodFormat.alternateExtended().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("P0000-00-00T00:00:00", ISOPeriodFormat.alternateExtended().print(p)); assertEquals("P0001-00-04T05:06:07.008", ISOPeriodFormat.alternateExtended().print(YEAR_DAY_PERIOD)); assertEquals("P0000-00-00T00:00:00", ISOPeriodFormat.alternateExtended().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P0001-02-04T00:00:00", ISOPeriodFormat.alternateExtended().print(DATE_PERIOD)); assertEquals("P0000-00-00T05:06:07.008", ISOPeriodFormat.alternateExtended().print(TIME_PERIOD)); } //----------------------------------------------------------------------- public void testFormatAlternateWithWeeks() { Period p = new Period(1, 2, 3, 4, 5, 6 ,7, 8); assertEquals("P0001W0304T050607.008", ISOPeriodFormat.alternateWithWeeks().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P0001W0304T050607", ISOPeriodFormat.alternateWithWeeks().print(p)); p = new Period(0); assertEquals("P0000W0000T000000", ISOPeriodFormat.alternateWithWeeks().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("P0000W0000T000000", ISOPeriodFormat.alternateWithWeeks().print(p)); assertEquals("P0001W0004T050607.008", ISOPeriodFormat.alternateWithWeeks().print(YEAR_DAY_PERIOD)); assertEquals("P0000W0000T000000", ISOPeriodFormat.alternateWithWeeks().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P0001W0304T000000", ISOPeriodFormat.alternateWithWeeks().print(DATE_PERIOD)); assertEquals("P0000W0000T050607.008", ISOPeriodFormat.alternateWithWeeks().print(TIME_PERIOD)); } //----------------------------------------------------------------------- public void testFormatAlternateExtendedWithWeeks() { Period p = new Period(1, 2, 3, 4, 5, 6 ,7, 8); assertEquals("P0001-W03-04T05:06:07.008", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P0001-W03-04T05:06:07", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); p = new Period(0); assertEquals("P0000-W00-00T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("P0000-W00-00T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); assertEquals("P0001-W00-04T05:06:07.008", ISOPeriodFormat.alternateExtendedWithWeeks().print(YEAR_DAY_PERIOD)); assertEquals("P0000-W00-00T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P0001-W03-04T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(DATE_PERIOD)); assertEquals("P0000-W00-00T05:06:07.008", ISOPeriodFormat.alternateExtendedWithWeeks().print(TIME_PERIOD)); } } joda-time-2.3/src/test/java/org/joda/time/format/TestISOPeriodFormatParsing.java0000644000175000017500000002011511564251364027203 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.Period; import org.joda.time.PeriodType; /** * This class is a Junit unit test for ISOPeriodFormat. * * @author Stephen Colebourne */ public class TestISOPeriodFormatParsing extends TestCase { private static final Period PERIOD = new Period(1, 2, 3, 4, 5, 6, 7, 8); private static final Period EMPTY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0); private static final Period YEAR_DAY_PERIOD = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); private static final Period EMPTY_YEAR_DAY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0, PeriodType.yearDayTime()); private static final Period TIME_PERIOD = new Period(0, 0, 0, 0, 5, 6, 7, 8); private static final Period DATE_PERIOD = new Period(1, 2, 3, 4, 0, 0, 0, 0); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L - 1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestISOPeriodFormatParsing.class); } public TestISOPeriodFormatParsing(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testParseStandard1() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P1Y2M3W4DT5H6M7.008S"); assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 8), p); } //----------------------------------------------------------------------- public void testParseStandard2() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P0Y0M0W0DT5H6M7.008S"); assertEquals(new Period(0, 0, 0, 0, 5, 6, 7, 8), p); } //----------------------------------------------------------------------- public void testParseStandard3() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P0DT5H6M7.008S"); assertEquals(new Period(0, 0, 0, 0, 5, 6, 7, 8), p); } //----------------------------------------------------------------------- public void testParseStandard4() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P2Y3DT5H6M7.008S"); assertEquals(new Period(2, 0, 0, 3, 5, 6, 7, 8), p); } //----------------------------------------------------------------------- public void testParseStandard5() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P2YT5H6M7.008S"); assertEquals(new Period(2, 0, 0, 0, 5, 6, 7, 8), p); } //----------------------------------------------------------------------- public void testParseStandard6() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("PT5H6M7.008S"); assertEquals(new Period(0, 0, 0, 0, 5, 6, 7, 8), p); } //----------------------------------------------------------------------- public void testParseStandard7() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P1Y2M3W4D"); assertEquals(new Period(1, 2, 3, 4, 0, 0, 0, 0), p); } //----------------------------------------------------------------------- public void testParseStandard8() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("PT5H6M7S"); assertEquals(new Period(0, 0, 0, 0, 5, 6, 7, 0), p); } //----------------------------------------------------------------------- public void testParseStandard9() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("PT0S"); assertEquals(new Period(0, 0, 0, 0, 0, 0, 0, 0), p); } //----------------------------------------------------------------------- public void testParseStandard10() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P0D"); assertEquals(new Period(0, 0, 0, 0, 0, 0, 0, 0), p); } //----------------------------------------------------------------------- public void testParseStandard11() { PeriodFormatter parser = ISOPeriodFormat.standard(); Period p = parser.parsePeriod("P0Y"); assertEquals(new Period(0, 0, 0, 0, 0, 0, 0, 0), p); } //----------------------------------------------------------------------- public void testParseStandardFail1() { PeriodFormatter parser = ISOPeriodFormat.standard(); try { parser.parsePeriod("P1Y2S"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseStandardFail2() { PeriodFormatter parser = ISOPeriodFormat.standard(); try { parser.parsePeriod("PS"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseStandardFail3() { PeriodFormatter parser = ISOPeriodFormat.standard(); try { parser.parsePeriod("PTS"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseStandardFail4() { PeriodFormatter parser = ISOPeriodFormat.standard(); try { parser.parsePeriod("PXS"); fail(); } catch (IllegalArgumentException ex) {} } } joda-time-2.3/src/test/java/org/joda/time/TestAll.java0000644000175000017500000001277711564251363022147 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all tests in this package. * * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestChronology.suite()); suite.addTest(TestDateTimeFieldType.suite()); suite.addTest(TestDurationFieldType.suite()); suite.addTest(TestInstant_Constructors.suite()); suite.addTest(TestInstant_Basics.suite()); suite.addTest(TestDateTime_Constructors.suite()); suite.addTest(TestDateTime_Basics.suite()); suite.addTest(TestDateTime_Properties.suite()); suite.addTest(TestMutableDateTime_Constructors.suite()); suite.addTest(TestMutableDateTime_Basics.suite()); suite.addTest(TestMutableDateTime_Sets.suite()); suite.addTest(TestMutableDateTime_Adds.suite()); suite.addTest(TestMutableDateTime_Properties.suite()); suite.addTest(TestDateMidnight_Constructors.suite()); suite.addTest(TestDateMidnight_Basics.suite()); suite.addTest(TestDateMidnight_Properties.suite()); suite.addTest(TestDuration_Constructors.suite()); suite.addTest(TestDuration_Basics.suite()); suite.addTest(TestInterval_Constructors.suite()); suite.addTest(TestInterval_Basics.suite()); suite.addTest(TestLocalDateTime_Constructors.suite()); suite.addTest(TestLocalDateTime_Basics.suite()); suite.addTest(TestLocalDateTime_Properties.suite()); suite.addTest(TestLocalDate_Constructors.suite()); suite.addTest(TestLocalDate_Basics.suite()); suite.addTest(TestLocalDate_Properties.suite()); suite.addTest(TestLocalTime_Constructors.suite()); suite.addTest(TestLocalTime_Basics.suite()); suite.addTest(TestLocalTime_Properties.suite()); suite.addTest(TestMutableInterval_Constructors.suite()); suite.addTest(TestMutableInterval_Basics.suite()); suite.addTest(TestMutableInterval_Updates.suite()); suite.addTest(TestPeriod_Constructors.suite()); suite.addTest(TestPeriod_Basics.suite()); suite.addTest(TestMutablePeriod_Constructors.suite()); suite.addTest(TestMutablePeriod_Basics.suite()); suite.addTest(TestMutablePeriod_Updates.suite()); suite.addTest(TestBaseSingleFieldPeriod.suite()); suite.addTest(TestYears.suite()); suite.addTest(TestMonths.suite()); suite.addTest(TestWeeks.suite()); suite.addTest(TestDays.suite()); suite.addTest(TestHours.suite()); suite.addTest(TestMinutes.suite()); suite.addTest(TestSeconds.suite()); suite.addTest(TestTimeOfDay_Basics.suite()); suite.addTest(TestTimeOfDay_Constructors.suite()); suite.addTest(TestTimeOfDay_Properties.suite()); suite.addTest(TestYearMonthDay_Basics.suite()); suite.addTest(TestYearMonthDay_Constructors.suite()); suite.addTest(TestYearMonthDay_Properties.suite()); suite.addTest(TestYearMonth_Basics.suite()); suite.addTest(TestYearMonth_Constructors.suite()); suite.addTest(TestYearMonth_Properties.suite()); suite.addTest(TestMonthDay_Basics.suite()); suite.addTest(TestMonthDay_Constructors.suite()); suite.addTest(TestMonthDay_Properties.suite()); suite.addTest(TestPartial_Basics.suite()); suite.addTest(TestPartial_Constructors.suite()); suite.addTest(TestPartial_Properties.suite()); suite.addTest(TestPartial_Match.suite()); suite.addTest(TestAbstractPartial.suite()); suite.addTest(TestBasePartial.suite()); suite.addTest(TestDateTimeComparator.suite()); suite.addTest(TestDateTimeConstants.suite()); suite.addTest(TestDateTimeUtils.suite()); suite.addTest(TestDateTimeZone.suite()); suite.addTest(TestDateTimeZoneCutover.suite()); suite.addTest(TestPeriodType.suite()); // suite.addTest(TestParseISO.suite()); suite.addTest(TestDurationField.suite()); suite.addTest(TestStringConvert.suite()); suite.addTest(TestSerialization.suite()); suite.addTest(TestIllegalFieldValueException.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } joda-time-2.3/src/test/java/org/joda/time/TestDurationField.java0000644000175000017500000000400211564251363024146 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.time.chrono.ISOChronology; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for DurationField. * * @author Stephen Colebourne */ public class TestDurationField extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDurationField.class); } public TestDurationField(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_subtract() throws Exception { DurationField fld = ISOChronology.getInstanceUTC().millis(); assertEquals(900, fld.subtract(1000L, 100)); assertEquals(900L, fld.subtract(1000L, 100L)); assertEquals((1000L - Integer.MAX_VALUE), fld.subtract(1000L, Integer.MAX_VALUE)); assertEquals((1000L - Integer.MIN_VALUE), fld.subtract(1000L, Integer.MIN_VALUE)); assertEquals((1000L - Long.MAX_VALUE), fld.subtract(1000L, Long.MAX_VALUE)); try { fld.subtract(-1000L, Long.MIN_VALUE); fail(); } catch (ArithmeticException ex) {} } } joda-time-2.3/src/test/java/org/joda/time/TestTimeOfDay_Basics.java0000644000175000017500000011505412200501234024513 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for TimeOfDay. * * @author Stephen Colebourne */ @SuppressWarnings("deprecation") public class TestTimeOfDay_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final int OFFSET = 1; private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestTimeOfDay_Basics.class); } public TestTimeOfDay_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testGet() { TimeOfDay test = new TimeOfDay(); assertEquals(10 + OFFSET, test.get(DateTimeFieldType.hourOfDay())); assertEquals(20, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(30, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(40, test.get(DateTimeFieldType.millisOfSecond())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.dayOfMonth()); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { TimeOfDay test = new TimeOfDay(); assertEquals(4, test.size()); } public void testGetFieldType() { TimeOfDay test = new TimeOfDay(COPTIC_PARIS); assertSame(DateTimeFieldType.hourOfDay(), test.getFieldType(0)); assertSame(DateTimeFieldType.minuteOfHour(), test.getFieldType(1)); assertSame(DateTimeFieldType.secondOfMinute(), test.getFieldType(2)); assertSame(DateTimeFieldType.millisOfSecond(), test.getFieldType(3)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(5); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { TimeOfDay test = new TimeOfDay(COPTIC_PARIS); DateTimeFieldType[] fields = test.getFieldTypes(); assertSame(DateTimeFieldType.hourOfDay(), fields[0]); assertSame(DateTimeFieldType.minuteOfHour(), fields[1]); assertSame(DateTimeFieldType.secondOfMinute(), fields[2]); assertSame(DateTimeFieldType.millisOfSecond(), fields[3]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField() { TimeOfDay test = new TimeOfDay(COPTIC_PARIS); assertSame(CopticChronology.getInstanceUTC().hourOfDay(), test.getField(0)); assertSame(CopticChronology.getInstanceUTC().minuteOfHour(), test.getField(1)); assertSame(CopticChronology.getInstanceUTC().secondOfMinute(), test.getField(2)); assertSame(CopticChronology.getInstanceUTC().millisOfSecond(), test.getField(3)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(5); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { TimeOfDay test = new TimeOfDay(COPTIC_PARIS); DateTimeField[] fields = test.getFields(); assertSame(CopticChronology.getInstanceUTC().hourOfDay(), fields[0]); assertSame(CopticChronology.getInstanceUTC().minuteOfHour(), fields[1]); assertSame(CopticChronology.getInstanceUTC().secondOfMinute(), fields[2]); assertSame(CopticChronology.getInstanceUTC().millisOfSecond(), fields[3]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); assertEquals(10, test.getValue(0)); assertEquals(20, test.getValue(1)); assertEquals(30, test.getValue(2)); assertEquals(40, test.getValue(3)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(5); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); int[] values = test.getValues(); assertEquals(10, values[0]); assertEquals(20, values[1]); assertEquals(30, values[2]); assertEquals(40, values[3]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported() { TimeOfDay test = new TimeOfDay(COPTIC_PARIS); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(true, test.isSupported(DateTimeFieldType.secondOfMinute())); assertEquals(true, test.isSupported(DateTimeFieldType.millisOfSecond())); assertEquals(false, test.isSupported(DateTimeFieldType.dayOfMonth())); } public void testEqualsHashCode() { TimeOfDay test1 = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); TimeOfDay test2 = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); TimeOfDay test3 = new TimeOfDay(15, 20, 30, 40); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInstant())); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); } class MockInstant extends MockPartial { public Chronology getChronology() { return CopticChronology.getInstanceUTC(); } public DateTimeField[] getFields() { return new DateTimeField[] { CopticChronology.getInstanceUTC().hourOfDay(), CopticChronology.getInstanceUTC().minuteOfHour(), CopticChronology.getInstanceUTC().secondOfMinute(), CopticChronology.getInstanceUTC().millisOfSecond(), }; } public int[] getValues() { return new int[] {10, 20, 30, 40}; } } //----------------------------------------------------------------------- public void testCompareTo() { TimeOfDay test1 = new TimeOfDay(10, 20, 30, 40); TimeOfDay test1a = new TimeOfDay(10, 20, 30, 40); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); TimeOfDay test2 = new TimeOfDay(10, 20, 35, 40); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); TimeOfDay test3 = new TimeOfDay(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour(), DateTimeFieldType.secondOfMinute(), DateTimeFieldType.millisOfSecond(), }; int[] values = new int[] {10, 20, 30, 40}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_TOD() { TimeOfDay test1 = new TimeOfDay(10, 20, 30, 40); TimeOfDay test1a = new TimeOfDay(10, 20, 30, 40); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); TimeOfDay test2 = new TimeOfDay(10, 20, 35, 40); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); TimeOfDay test3 = new TimeOfDay(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { new TimeOfDay(10, 20, 35, 40).isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_TOD() { TimeOfDay test1 = new TimeOfDay(10, 20, 30, 40); TimeOfDay test1a = new TimeOfDay(10, 20, 30, 40); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); TimeOfDay test2 = new TimeOfDay(10, 20, 35, 40); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); TimeOfDay test3 = new TimeOfDay(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new TimeOfDay(10, 20, 35, 40).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_TOD() { TimeOfDay test1 = new TimeOfDay(10, 20, 30, 40); TimeOfDay test1a = new TimeOfDay(10, 20, 30, 40); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); TimeOfDay test2 = new TimeOfDay(10, 20, 35, 40); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); TimeOfDay test3 = new TimeOfDay(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new TimeOfDay(10, 20, 35, 40).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithChronologyRetainFields_Chrono() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); TimeOfDay test = base.withChronologyRetainFields(BUDDHIST_TOKYO); check(base, 10, 20, 30, 40); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 10, 20, 30, 40); assertEquals(BUDDHIST_UTC, test.getChronology()); } public void testWithChronologyRetainFields_sameChrono() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); TimeOfDay test = base.withChronologyRetainFields(COPTIC_TOKYO); assertSame(base, test); } public void testWithChronologyRetainFields_nullChrono() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); TimeOfDay test = base.withChronologyRetainFields(null); check(base, 10, 20, 30, 40); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 10, 20, 30, 40); assertEquals(ISO_UTC, test.getChronology()); } //----------------------------------------------------------------------- public void testWithField1() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay result = test.withField(DateTimeFieldType.hourOfDay(), 15); assertEquals(new TimeOfDay(10, 20, 30, 40), test); assertEquals(new TimeOfDay(15, 20, 30, 40), result); } public void testWithField2() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField3() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); try { test.withField(DateTimeFieldType.dayOfMonth(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField4() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay result = test.withField(DateTimeFieldType.hourOfDay(), 10); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded1() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay result = test.withFieldAdded(DurationFieldType.hours(), 6); assertEquals(new TimeOfDay(10, 20, 30, 40), test); assertEquals(new TimeOfDay(16, 20, 30, 40), result); } public void testWithFieldAdded2() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded3() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded4() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay result = test.withFieldAdded(DurationFieldType.hours(), 0); assertSame(test, result); } public void testWithFieldAdded5() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); try { test.withFieldAdded(DurationFieldType.days(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded6() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay result = test.withFieldAdded(DurationFieldType.hours(), 16); assertEquals(new TimeOfDay(10, 20, 30, 40), test); assertEquals(new TimeOfDay(2, 20, 30, 40), result); } public void testWithFieldAdded7() { TimeOfDay test = new TimeOfDay(23, 59, 59, 999); TimeOfDay result = test.withFieldAdded(DurationFieldType.millis(), 1); assertEquals(new TimeOfDay(0, 0, 0, 0), result); test = new TimeOfDay(23, 59, 59, 999); result = test.withFieldAdded(DurationFieldType.seconds(), 1); assertEquals(new TimeOfDay(0, 0, 0, 999), result); test = new TimeOfDay(23, 59, 59, 999); result = test.withFieldAdded(DurationFieldType.minutes(), 1); assertEquals(new TimeOfDay(0, 0, 59, 999), result); test = new TimeOfDay(23, 59, 59, 999); result = test.withFieldAdded(DurationFieldType.hours(), 1); assertEquals(new TimeOfDay(0, 59, 59, 999), result); } public void testWithFieldAdded8() { TimeOfDay test = new TimeOfDay(0, 0, 0, 0); TimeOfDay result = test.withFieldAdded(DurationFieldType.millis(), -1); assertEquals(new TimeOfDay(23, 59, 59, 999), result); test = new TimeOfDay(0, 0, 0, 0); result = test.withFieldAdded(DurationFieldType.seconds(), -1); assertEquals(new TimeOfDay(23, 59, 59, 0), result); test = new TimeOfDay(0, 0, 0, 0); result = test.withFieldAdded(DurationFieldType.minutes(), -1); assertEquals(new TimeOfDay(23, 59, 0, 0), result); test = new TimeOfDay(0, 0, 0, 0); result = test.withFieldAdded(DurationFieldType.hours(), -1); assertEquals(new TimeOfDay(23, 0, 0, 0), result); } //----------------------------------------------------------------------- public void testPlus_RP() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40, BuddhistChronology.getInstance()); TimeOfDay result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8)); TimeOfDay expected = new TimeOfDay(15, 26, 37, 48, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusHours_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.plusHours(1); TimeOfDay expected = new TimeOfDay(2, 2, 3, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusHours(0); assertSame(test, result); } public void testPlusMinutes_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.plusMinutes(1); TimeOfDay expected = new TimeOfDay(1, 3, 3, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusMinutes(0); assertSame(test, result); } public void testPlusSeconds_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.plusSeconds(1); TimeOfDay expected = new TimeOfDay(1, 2, 4, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusSeconds(0); assertSame(test, result); } public void testPlusMillis_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.plusMillis(1); TimeOfDay expected = new TimeOfDay(1, 2, 3, 5, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40, BuddhistChronology.getInstance()); TimeOfDay result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); TimeOfDay expected = new TimeOfDay(9, 19, 29, 39, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusHours_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.minusHours(1); TimeOfDay expected = new TimeOfDay(0, 2, 3, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusHours(0); assertSame(test, result); } public void testMinusMinutes_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.minusMinutes(1); TimeOfDay expected = new TimeOfDay(1, 1, 3, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusMinutes(0); assertSame(test, result); } public void testMinusSeconds_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.minusSeconds(1); TimeOfDay expected = new TimeOfDay(1, 2, 2, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusSeconds(0); assertSame(test, result); } public void testMinusMillis_int() { TimeOfDay test = new TimeOfDay(1, 2, 3, 4, BuddhistChronology.getInstance()); TimeOfDay result = test.minusMillis(1); TimeOfDay expected = new TimeOfDay(1, 2, 3, 3, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testToLocalTime() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_UTC); LocalTime test = base.toLocalTime(); assertEquals(new LocalTime(10, 20, 30, 40, COPTIC_UTC), test); } //----------------------------------------------------------------------- public void testToDateTimeToday() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeToday(); check(base, 10, 20, 30, 40); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.hourOfDay().setCopy(10); expected = expected.minuteOfHour().setCopy(20); expected = expected.secondOfMinute().setCopy(30); expected = expected.millisOfSecond().setCopy(40); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTimeToday_Zone() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeToday(TOKYO); check(base, 10, 20, 30, 40); DateTime expected = new DateTime(dt.getMillis(), COPTIC_TOKYO); expected = expected.hourOfDay().setCopy(10); expected = expected.minuteOfHour().setCopy(20); expected = expected.secondOfMinute().setCopy(30); expected = expected.millisOfSecond().setCopy(40); assertEquals(expected, test); } public void testToDateTimeToday_nullZone() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeToday((DateTimeZone) null); check(base, 10, 20, 30, 40); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.hourOfDay().setCopy(10); expected = expected.minuteOfHour().setCopy(20); expected = expected.secondOfMinute().setCopy(30); expected = expected.millisOfSecond().setCopy(40); assertEquals(expected, test); } // Removed as too complex // /** // * Merges two partial together, taking account of the different chronologies. // * // * @param main the main partial // * @param base the partial to use as a base to merge on top of // * @param instant the instant to start from and to use for missing fields // * @return the merged instant // */ // public long merge(ReadablePartial main, ReadablePartial base, long instant) { // DateTimeZone zone = main.getChronology().getZone(); // instant = base.getChronology().withZone(zone).set(base, instant); // return set(main, instant); // } // // //----------------------------------------------------------------------- // /** // * Converts this object to a DateTime using a YearMonthDay to fill in the // * missing fields and using the default time zone. // * This instance is immutable and unaffected by this method call. // *

// * The resulting chronology is determined by the chronology of this // * TimeOfDay plus the time zone. // *

// * This method makes use of the chronology of the specified YearMonthDay // * in the calculation. This can be significant when mixing chronologies. // * If the YearMonthDay is in the same chronology as this instance the // * method will perform exactly as you might expect. // *

// * If the chronologies differ, then both this TimeOfDay and the YearMonthDay // * are converted to the destination chronology and then merged. As a result // * it may be the case that the year, monthOfYear and dayOfMonth fields on // * the result are different from the values returned by the methods on the // * YearMonthDay. // *

// * See {@link DateTime#withFields(ReadablePartial)} for an algorithm that // * ignores the chronology. // * // * @param date the date to use, null means today // * @return the DateTime instance // */ // public DateTime toDateTime(YearMonthDay date) { // return toDateTime(date, null); // } // // /** // * Converts this object to a DateTime using a YearMonthDay to fill in the // * missing fields. // * This instance is immutable and unaffected by this method call. // *

// * The resulting chronology is determined by the chronology of this // * TimeOfDay plus the time zone. // *

// * This method makes use of the chronology of the specified YearMonthDay // * in the calculation. This can be significant when mixing chronologies. // * If the YearMonthDay is in the same chronology as this instance the // * method will perform exactly as you might expect. // *

// * If the chronologies differ, then both this TimeOfDay and the YearMonthDay // * are converted to the destination chronology and then merged. As a result // * it may be the case that the year, monthOfYear and dayOfMonth fields on // * the result are different from the values returned by the methods on the // * YearMonthDay. // *

// * See {@link DateTime#withFields(ReadablePartial)} for an algorithm that // * ignores the chronology and just assigns the fields. // * // * @param date the date to use, null means today // * @param zone the zone to get the DateTime in, null means default // * @return the DateTime instance // */ // public DateTime toDateTime(YearMonthDay date, DateTimeZone zone) { // Chronology chrono = getChronology().withZone(zone); // if (date == null) { // DateTime dt = new DateTime(chrono); // return dt.withFields(this); // } else { // long millis = chrono.merge(this, date, DateTimeUtils.currentTimeMillis()); // return new DateTime(millis, chrono); // } // } // // //----------------------------------------------------------------------- // public void testToDateTime_YMD() { // TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant // YearMonthDay ymd = new YearMonthDay(new DateMidnight(2004, 6, 9), BUDDHIST_TOKYO); // // DateTime test = base.toDateTime(ymd); // check(base, 10, 20, 30, 40); // DateTime expected = new DateTime(ymd.toDateMidnight(LONDON), COPTIC_LONDON); // expected = expected.hourOfDay().setCopy(10); // expected = expected.minuteOfHour().setCopy(20); // expected = expected.secondOfMinute().setCopy(30); // expected = expected.millisOfSecond().setCopy(40); // assertEquals(expected, test); // } // // public void testToDateTime_nullYMD() { // TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant // // DateTime test = base.toDateTime((YearMonthDay) null); // check(base, 10, 20, 30, 40); // DateTime expected = new DateTime(COPTIC_LONDON); // expected = expected.hourOfDay().setCopy(10); // expected = expected.minuteOfHour().setCopy(20); // expected = expected.secondOfMinute().setCopy(30); // expected = expected.millisOfSecond().setCopy(40); // assertEquals(expected, test); // } // // //----------------------------------------------------------------------- // public void testToDateTime_YMD_Zone() { // TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant // YearMonthDay ymd = new YearMonthDay(new DateMidnight(2004, 6, 9), BUDDHIST_LONDON); // // DateTime test = base.toDateTime(ymd, TOKYO); // check(base, 10, 20, 30, 40); // DateTime expected = new DateTime(ymd.toDateMidnight(TOKYO), COPTIC_TOKYO); // expected = expected.hourOfDay().setCopy(10); // expected = expected.minuteOfHour().setCopy(20); // expected = expected.secondOfMinute().setCopy(30); // expected = expected.millisOfSecond().setCopy(40); // assertEquals(expected, test); // } // // public void testToDateTime_YMD_nullZone() { // TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant // YearMonthDay ymd = new YearMonthDay(new DateMidnight(2004, 6, 9), BUDDHIST_LONDON); // // DateTime test = base.toDateTime(ymd, null); // check(base, 10, 20, 30, 40); // DateTime expected = new DateTime(ymd.toDateMidnight(LONDON), COPTIC_LONDON); // expected = expected.hourOfDay().setCopy(10); // expected = expected.minuteOfHour().setCopy(20); // expected = expected.secondOfMinute().setCopy(30); // expected = expected.millisOfSecond().setCopy(40); // assertEquals(expected, test); // } // // public void testToDateTime_nullYMD_Zone() { // TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); // PARIS irrelevant // // DateTime test = base.toDateTime((YearMonthDay) null, TOKYO); // check(base, 10, 20, 30, 40); // DateTime expected = new DateTime(COPTIC_TOKYO); // expected = expected.hourOfDay().setCopy(10); // expected = expected.minuteOfHour().setCopy(20); // expected = expected.secondOfMinute().setCopy(30); // expected = expected.millisOfSecond().setCopy(40); // assertEquals(expected, test); // } //----------------------------------------------------------------------- public void testToDateTime_RI() { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); DateTime dt = new DateTime(0L); // LONDON zone assertEquals("1970-01-01T01:00:00.000+01:00", dt.toString()); DateTime test = base.toDateTime(dt); check(base, 10, 20, 30, 40); assertEquals("1970-01-01T01:00:00.000+01:00", dt.toString()); assertEquals("1970-01-01T10:20:30.040+01:00", test.toString()); } public void testToDateTime_nullRI() { TimeOfDay base = new TimeOfDay(1, 2, 3, 4); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 1, 2, 3, 4); assertEquals("1970-01-02T01:02:03.004+01:00", test.toString()); } //----------------------------------------------------------------------- public void testWithers() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); check(test.withHourOfDay(6), 6, 20, 30, 40); check(test.withMinuteOfHour(6), 10, 6, 30, 40); check(test.withSecondOfMinute(6), 10, 20, 6, 40); check(test.withMillisOfSecond(6), 10, 20, 30, 6); try { test.withHourOfDay(-1); fail(); } catch (IllegalArgumentException ex) {} try { test.withHourOfDay(24); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testProperty() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals(test.hourOfDay(), test.property(DateTimeFieldType.hourOfDay())); assertEquals(test.minuteOfHour(), test.property(DateTimeFieldType.minuteOfHour())); assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute())); assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond())); try { test.property(DateTimeFieldType.millisOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { TimeOfDay test = new TimeOfDay(10, 20, 30, 40, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); TimeOfDay result = (TimeOfDay) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); } //----------------------------------------------------------------------- public void testToString() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals("T10:20:30.040", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals("\ufffd\ufffd\ufffd\ufffd 10", test.toString("yyyy HH")); assertEquals("T10:20:30.040", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals("10 20", test.toString("H m", Locale.ENGLISH)); assertEquals("T10:20:30.040", test.toString(null, Locale.ENGLISH)); assertEquals("10 20", test.toString("H m", null)); assertEquals("T10:20:30.040", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals("\ufffd\ufffd\ufffd\ufffd 10", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("T10:20:30.040", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private void check(TimeOfDay test, int hour, int min, int sec, int milli) { assertEquals(hour, test.getHourOfDay()); assertEquals(min, test.getMinuteOfHour()); assertEquals(sec, test.getSecondOfMinute()); assertEquals(milli, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutablePeriod_Updates.java0000644000175000017500000016773611564251364025667 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.ISOChronology; /** * This class is a JUnit test for MutableDuration. * * @author Stephen Colebourne */ public class TestMutablePeriod_Updates extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutablePeriod_Updates.class); } public TestMutablePeriod_Updates(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testClear() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.clear(); assertEquals(new MutablePeriod(), test); test = new MutablePeriod(1, 2, 0, 4, 5, 6, 7, 8, PeriodType.yearMonthDayTime()); test.clear(); assertEquals(new MutablePeriod(PeriodType.yearMonthDayTime()), test); } //----------------------------------------------------------------------- public void testAddYears() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addYears(10); assertEquals(11, test.getYears()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addYears(-10); assertEquals(-9, test.getYears()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addYears(0); assertEquals(1, test.getYears()); } //----------------------------------------------------------------------- public void testAddMonths() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMonths(10); assertEquals(12, test.getMonths()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMonths(-10); assertEquals(-8, test.getMonths()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMonths(0); assertEquals(2, test.getMonths()); } //----------------------------------------------------------------------- public void testAddWeeks() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addWeeks(10); assertEquals(13, test.getWeeks()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addWeeks(-10); assertEquals(-7, test.getWeeks()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addWeeks(0); assertEquals(3, test.getWeeks()); } //----------------------------------------------------------------------- public void testAddDays() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addDays(10); assertEquals(14, test.getDays()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addDays(-10); assertEquals(-6, test.getDays()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addDays(0); assertEquals(4, test.getDays()); } //----------------------------------------------------------------------- public void testAddHours() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addHours(10); assertEquals(15, test.getHours()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addHours(-10); assertEquals(-5, test.getHours()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addHours(0); assertEquals(5, test.getHours()); } //----------------------------------------------------------------------- public void testAddMinutes() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMinutes(10); assertEquals(16, test.getMinutes()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMinutes(-10); assertEquals(-4, test.getMinutes()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMinutes(0); assertEquals(6, test.getMinutes()); } //----------------------------------------------------------------------- public void testAddSeconds() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addSeconds(10); assertEquals(17, test.getSeconds()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addSeconds(-10); assertEquals(-3, test.getSeconds()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addSeconds(0); assertEquals(7, test.getSeconds()); } //----------------------------------------------------------------------- public void testAddMillis() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMillis(10); assertEquals(18, test.getMillis()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMillis(-10); assertEquals(-2, test.getMillis()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.addMillis(0); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testSetYears() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setYears(10); assertEquals(10, test.getYears()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setYears(-10); assertEquals(-10, test.getYears()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setYears(0); assertEquals(0, test.getYears()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setYears(1); assertEquals(1, test.getYears()); test = new MutablePeriod(0, 0, 0, 0, 0, 0, 0, 1, PeriodType.millis()); try { test.setYears(1); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetMonths() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMonths(10); assertEquals(10, test.getMonths()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMonths(-10); assertEquals(-10, test.getMonths()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMonths(0); assertEquals(0, test.getMonths()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMonths(2); assertEquals(2, test.getMonths()); } //----------------------------------------------------------------------- public void testSetWeeks() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setWeeks(10); assertEquals(10, test.getWeeks()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setWeeks(-10); assertEquals(-10, test.getWeeks()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setWeeks(0); assertEquals(0, test.getWeeks()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setWeeks(3); assertEquals(3, test.getWeeks()); } //----------------------------------------------------------------------- public void testSetDays() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setDays(10); assertEquals(10, test.getDays()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setDays(-10); assertEquals(-10, test.getDays()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setDays(0); assertEquals(0, test.getDays()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setDays(4); assertEquals(4, test.getDays()); } //----------------------------------------------------------------------- public void testSetHours() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setHours(10); assertEquals(10, test.getHours()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setHours(-10); assertEquals(-10, test.getHours()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setHours(0); assertEquals(0, test.getHours()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setHours(5); assertEquals(5, test.getHours()); } //----------------------------------------------------------------------- public void testSetMinutes() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMinutes(10); assertEquals(10, test.getMinutes()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMinutes(-10); assertEquals(-10, test.getMinutes()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMinutes(0); assertEquals(0, test.getMinutes()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMinutes(6); assertEquals(6, test.getMinutes()); } //----------------------------------------------------------------------- public void testSetSeconds() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setSeconds(10); assertEquals(10, test.getSeconds()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setSeconds(-10); assertEquals(-10, test.getSeconds()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setSeconds(0); assertEquals(0, test.getSeconds()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setSeconds(7); assertEquals(7, test.getSeconds()); } //----------------------------------------------------------------------- public void testSetMillis() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMillis(10); assertEquals(10, test.getMillis()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMillis(-10); assertEquals(-10, test.getMillis()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMillis(0); assertEquals(0, test.getMillis()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setMillis(8); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testSet_Field() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.set(DurationFieldType.years(), 10); assertEquals(10, test.getYears()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); try { test.set(null, 10); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testAdd_Field() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.add(DurationFieldType.years(), 10); assertEquals(11, test.getYears()); test = new MutablePeriod(0, 0, 0, 0, 0, 0, 0, 1, PeriodType.millis()); test.add(DurationFieldType.years(), 0); assertEquals(0, test.getYears()); assertEquals(1, test.getMillis()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); try { test.add(null, 0); fail(); } catch (IllegalArgumentException ex) {} test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); try { test.add(null, 10); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetPeriod_8ints1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setPeriod(11, 12, 13, 14, 15, 16, 17, 18); assertEquals(11, test.getYears()); assertEquals(12, test.getMonths()); assertEquals(13, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(15, test.getHours()); assertEquals(16, test.getMinutes()); assertEquals(17, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testSetPeriod_8ints2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.millis()); try { test.setPeriod(11, 12, 13, 14, 15, 16, 17, 18); fail(); } catch (IllegalArgumentException ex) {} assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testSetPeriod_8ints3() { MutablePeriod test = new MutablePeriod(100L, PeriodType.millis()); test.setPeriod(0, 0, 0, 0, 0, 0, 0, 18); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testSetPeriod_8ints4() { MutablePeriod test = new MutablePeriod(0, 0, 0, 0, 5, 6, 7, 8); test.setPeriod(11, 12, 13, 14, 15, 16, 17, 18); assertEquals(11, test.getYears()); assertEquals(12, test.getMonths()); assertEquals(13, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(15, test.getHours()); assertEquals(16, test.getMinutes()); assertEquals(17, test.getSeconds()); assertEquals(18, test.getMillis()); } //----------------------------------------------------------------------- public void testSetPeriod_RP1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setPeriod(new MutablePeriod(11, 12, 13, 14, 15, 16, 17, 18)); assertEquals(11, test.getYears()); assertEquals(12, test.getMonths()); assertEquals(13, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(15, test.getHours()); assertEquals(16, test.getMinutes()); assertEquals(17, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testSetPeriod_RP2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.millis()); try { test.setPeriod(new MutablePeriod(11, 12, 13, 14, 15, 16, 17, 18)); fail(); } catch (IllegalArgumentException ex) {} assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testSetPeriod_RP3() { MutablePeriod test = new MutablePeriod(100L, PeriodType.millis()); test.setPeriod(new MutablePeriod(0, 0, 0, 0, 0, 0, 0, 18)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testSetPeriod_RP4() { MutablePeriod test = new MutablePeriod(0, 0, 0, 0, 5, 6, 7, 8); test.setPeriod(new MutablePeriod(11, 12, 13, 14, 15, 16, 17, 18)); assertEquals(11, test.getYears()); assertEquals(12, test.getMonths()); assertEquals(13, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(15, test.getHours()); assertEquals(16, test.getMinutes()); assertEquals(17, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testSetPeriod_RP5() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setPeriod((ReadablePeriod) null); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testSetPeriod_long_long1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_long_long2() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt2.getMillis(), dt1.getMillis()); assertEquals(-1, test.getYears()); assertEquals(-1, test.getMonths()); assertEquals(-1, test.getWeeks()); assertEquals(-1, test.getDays()); assertEquals(-1, test.getHours()); assertEquals(-1, test.getMinutes()); assertEquals(-1, test.getSeconds()); assertEquals(-1, test.getMillis()); } public void testSetPeriod_long_long3() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); test.setPeriod(dt1.getMillis(), dt1.getMillis()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testSetPeriod_long_long_NoYears() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withYearsRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(0, test.getYears()); assertEquals(13, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_long_long_NoMonths() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withMonthsRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(5, test.getWeeks()); assertEquals(3, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_long_long_NoWeeks() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withWeeksRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(8, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_long_long_NoDays() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withDaysRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(25, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_long_long_NoHours() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withHoursRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(61, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_long_long_NoMinutes() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withMinutesRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(61, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_long_long_NoSeconds() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withSecondsRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(1001, test.getMillis()); } public void testSetPeriod_long_long_NoMillis() { MutablePeriod test = new MutablePeriod(PeriodType.standard().withMillisRemoved()); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testSetPeriod_RI_RI1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt1, dt2); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_RI_RI2() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(dt2, dt1); assertEquals(-1, test.getYears()); assertEquals(-1, test.getMonths()); assertEquals(-1, test.getWeeks()); assertEquals(-1, test.getDays()); assertEquals(-1, test.getHours()); assertEquals(-1, test.getMinutes()); assertEquals(-1, test.getSeconds()); assertEquals(-1, test.getMillis()); } public void testSetPeriod_RI_RI3() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); test.setPeriod(dt1, dt1); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testSetPeriod_RInterval1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); DateTime dt1 = new DateTime(2002, 6, 9, 13, 15, 17, 19); DateTime dt2 = new DateTime(2003, 7, 17, 14, 16, 18, 20); test.setPeriod(new Interval(dt1, dt2)); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testSetPeriod_RInterval2() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setPeriod((ReadableInterval) null); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testSetPeriod_long1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setPeriod(100L); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testSetPeriod_long2() { MutablePeriod test = new MutablePeriod(); test.setPeriod( (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L); // only time fields are precise assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } // public void testSetPeriod_long3() { // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType()); // test.setPeriod( // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L); // assertEquals(1, test.getYears()); // assertEquals(2, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(25, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(8, test.getMillis()); // } // // public void testSetPeriod_long4() { // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearWeekType()); // test.setPeriod( // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L); // assertEquals(1, test.getYears()); // assertEquals(0, test.getMonths()); // assertEquals(12, test.getWeeks()); // assertEquals(1, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(8, test.getMillis()); // } // // public void testSetPeriod_long_NoYears() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType().withYearsRemoved()); // test.setPeriod(ms); // assertEquals(0, test.getYears()); // assertEquals(15, test.getMonths()); // totalDays=365+85=450=15*30 // assertEquals(0, test.getWeeks()); // assertEquals(0, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(8, test.getMillis()); // assertEquals(ms, test.toDurationMillis()); // } // // public void testSetPeriod_long_NoMonths() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType().withMonthsRemoved()); // test.setPeriod(ms); // assertEquals(1, test.getYears()); // assertEquals(0, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(85, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(8, test.getMillis()); // assertEquals(ms, test.toDurationMillis()); // } // // public void testSetPeriod_long_NoWeeks() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearWeekType().withWeeksRemoved()); // test.setPeriod(ms); // assertEquals(1, test.getYears()); // assertEquals(0, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(85, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(8, test.getMillis()); // assertEquals(ms, test.toDurationMillis()); // } // // public void testSetPeriod_long_NoDays() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType().withDaysRemoved()); // test.setPeriod(ms); // assertEquals(1, test.getYears()); // assertEquals(2, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(0, test.getDays()); // assertEquals(5 + 25 * 24, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(8, test.getMillis()); // assertEquals(ms, test.toDurationMillis()); // } // // public void testSetPeriod_long_NoHours() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType().withHoursRemoved()); // test.setPeriod(ms); // assertEquals(1, test.getYears()); // assertEquals(2, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(25, test.getDays()); // assertEquals(0, test.getHours()); // assertEquals(6 + 5 * 60, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(8, test.getMillis()); // assertEquals(ms, test.toDurationMillis()); // } // // public void testSetPeriod_long_NoMinutes() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType().withMinutesRemoved()); // test.setPeriod(ms); // assertEquals(1, test.getYears()); // assertEquals(2, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(25, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(0, test.getMinutes()); // assertEquals(7 + 6 * 60, test.getSeconds()); // assertEquals(8, test.getMillis()); // assertEquals(ms, test.toDurationMillis()); // } // // public void testSetPeriod_long_NoSeconds() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType().withSecondsRemoved()); // test.setPeriod(ms); // assertEquals(1, test.getYears()); // assertEquals(2, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(25, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(0, test.getSeconds()); // assertEquals(8 + 7 * 1000, test.getMillis()); // assertEquals(ms, test.toDurationMillis()); // } // // public void testSetPeriod_long_NoMillis() { // long ms = // (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + // 5L * DateTimeConstants.MILLIS_PER_HOUR + // 6L * DateTimeConstants.MILLIS_PER_MINUTE + // 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; // MutablePeriod test = new MutablePeriod(PeriodType.getPreciseYearMonthType().withMillisRemoved()); // test.setPeriod(ms); // assertEquals(1, test.getYears()); // assertEquals(2, test.getMonths()); // assertEquals(0, test.getWeeks()); // assertEquals(25, test.getDays()); // assertEquals(5, test.getHours()); // assertEquals(6, test.getMinutes()); // assertEquals(7, test.getSeconds()); // assertEquals(0, test.getMillis()); // assertEquals(ms - 8, test.toDurationMillis()); // } //----------------------------------------------------------------------- public void testSetPeriod_RD1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setPeriod(new Duration(100L)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testSetPeriod_RD2() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; test.setPeriod(new Duration(length)); // only time fields are precise assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testSetPeriod_RD3() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.setPeriod((ReadableDuration) null); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testAdd_8ints1() { MutablePeriod test = new MutablePeriod(100L); test.add(1, 2, 3, 4, 5, 6, 7, 8); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(108, test.getMillis()); } public void testAdd_8ints2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.yearMonthDayTime()); try { test.add(1, 2, 3, 4, 5, 6, 7, 8); fail(); } catch (IllegalArgumentException ex) {} assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } //----------------------------------------------------------------------- public void testAdd_long1() { MutablePeriod test = new MutablePeriod(100L); test.add(100L); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(200, test.getMillis()); } public void testAdd_long2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.standard()); long ms = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; test.add(ms); // only time fields are precise assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(108, test.getMillis()); } public void testAdd_long3() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.add(2100L); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(9, test.getSeconds()); assertEquals(108, test.getMillis()); } //----------------------------------------------------------------------- public void testAdd_long_Chronology1() { MutablePeriod test = new MutablePeriod(100L); test.add(100L, ISOChronology.getInstance()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(200, test.getMillis()); } public void testAdd_long_Chronology2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.standard()); long ms = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; test.add(ms, ISOChronology.getInstance()); // only time fields are precise assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 days assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(108, test.getMillis()); } public void testAdd_long_Chronology3() { MutablePeriod test = new MutablePeriod(100L, PeriodType.standard()); long ms = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; test.add(ms, ISOChronology.getInstanceUTC()); // UTC, so weeks and day also precise assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 days assertEquals(0, test.getMonths()); assertEquals(64, test.getWeeks()); assertEquals(2, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(108, test.getMillis()); } //----------------------------------------------------------------------- public void testAdd_RD1() { MutablePeriod test = new MutablePeriod(100L); test.add(new Duration(100L)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(200, test.getMillis()); } public void testAdd_RD2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.yearMonthDayTime()); long ms = (4L + (3L * 7L)) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; test.add(new Duration(ms)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 + (3 * 7)) * 24 + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(108, test.getMillis()); } public void testAdd_RD3() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.add((ReadableDuration) null); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testAdd_RP1() { MutablePeriod test = new MutablePeriod(100L); test.add(new Period(100L)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(200, test.getMillis()); } public void testAdd_RP2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.standard()); // All type test.add(new Period(1, 2, 3, 4, 5, 6, 7, 0, PeriodType.standard().withMillisRemoved())); // add field value, ignore different types assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testAdd_RP3() { MutablePeriod test = new MutablePeriod(100L, PeriodType.standard()); test.add(new Period(0L)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testAdd_RP4() { MutablePeriod test = new MutablePeriod(1, 2, 0, 4, 5, 6, 7, 8, PeriodType.yearMonthDayTime()); try { test.add(new Period(1, 2, 3, 4, 5, 6, 7, 8)); // cannot set weeks fail(); } catch (IllegalArgumentException ex) {} assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testAdd_RP5() { MutablePeriod test = new MutablePeriod(1, 2, 0, 4, 5, 6, 7, 8, PeriodType.yearMonthDayTime()); test.add(new Period(1, 2, 0, 4, 5, 6, 7, 8)); // can set weeks as zero assertEquals(2, test.getYears()); assertEquals(4, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(8, test.getDays()); assertEquals(10, test.getHours()); assertEquals(12, test.getMinutes()); assertEquals(14, test.getSeconds()); assertEquals(16, test.getMillis()); } public void testAdd_RP6() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.add((ReadablePeriod) null); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testAdd_RInterval1() { MutablePeriod test = new MutablePeriod(100L); test.add(new Interval(100L, 200L)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(200, test.getMillis()); } public void testAdd_RInterval2() { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 12, 18, 0, 0, 0, 8); MutablePeriod test = new MutablePeriod(100L); // All type test.add(new Interval(dt1, dt2)); assertEquals(1, test.getYears()); // add field value from interval assertEquals(6, test.getMonths()); // add field value from interval assertEquals(1, test.getWeeks()); // add field value from interval assertEquals(2, test.getDays()); // add field value from interval assertEquals(0, test.getHours()); // time zone OK assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(108, test.getMillis()); } public void testAdd_RInterval3() { MutablePeriod test = new MutablePeriod(100L, PeriodType.yearMonthDayTime()); test.add(new Interval(0L, 0L)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testAdd_RInterval4() { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 17, 0, 0, 0, 8); MutablePeriod test = new MutablePeriod(100L, PeriodType.yearMonthDayTime()); test.add(new Interval(dt1, dt2)); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); // no weeks assertEquals(8, test.getDays()); // week added to days assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(108, test.getMillis()); } public void testAdd_RInterval5() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.add((ReadableInterval) null); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testMergePeriod_RP1() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.mergePeriod(new MutablePeriod(0, 0, 0, 14, 15, 16, 17, 18, PeriodType.dayTime())); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(15, test.getHours()); assertEquals(16, test.getMinutes()); assertEquals(17, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testMergePeriod_RP2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.millis()); try { test.mergePeriod(new MutablePeriod(11, 12, 13, 14, 15, 16, 17, 18)); fail(); } catch (IllegalArgumentException ex) {} assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); } public void testMergePeriod_RP3() { MutablePeriod test = new MutablePeriod(100L, PeriodType.millis()); test.mergePeriod(new MutablePeriod(0, 0, 0, 0, 0, 0, 0, 18)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testMergePeriod_RP4() { MutablePeriod test = new MutablePeriod(0, 0, 0, 0, 5, 6, 7, 8); test.mergePeriod(new MutablePeriod(11, 12, 13, 14, 15, 16, 17, 18)); assertEquals(11, test.getYears()); assertEquals(12, test.getMonths()); assertEquals(13, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(15, test.getHours()); assertEquals(16, test.getMinutes()); assertEquals(17, test.getSeconds()); assertEquals(18, test.getMillis()); } public void testMergePeriod_RP5() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.mergePeriod((ReadablePeriod) null); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } } joda-time-2.3/src/test/java/org/joda/time/TestHours.java0000644000175000017500000003507112200501234022506 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for Hours. * * @author Stephen Colebourne */ public class TestHours extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestHours.class); } public TestHours(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testConstants() { assertEquals(0, Hours.ZERO.getHours()); assertEquals(1, Hours.ONE.getHours()); assertEquals(2, Hours.TWO.getHours()); assertEquals(3, Hours.THREE.getHours()); assertEquals(4, Hours.FOUR.getHours()); assertEquals(5, Hours.FIVE.getHours()); assertEquals(6, Hours.SIX.getHours()); assertEquals(7, Hours.SEVEN.getHours()); assertEquals(8, Hours.EIGHT.getHours()); assertEquals(Integer.MAX_VALUE, Hours.MAX_VALUE.getHours()); assertEquals(Integer.MIN_VALUE, Hours.MIN_VALUE.getHours()); } //----------------------------------------------------------------------- public void testFactory_hours_int() { assertSame(Hours.ZERO, Hours.hours(0)); assertSame(Hours.ONE, Hours.hours(1)); assertSame(Hours.TWO, Hours.hours(2)); assertSame(Hours.THREE, Hours.hours(3)); assertSame(Hours.FOUR, Hours.hours(4)); assertSame(Hours.FIVE, Hours.hours(5)); assertSame(Hours.SIX, Hours.hours(6)); assertSame(Hours.SEVEN, Hours.hours(7)); assertSame(Hours.EIGHT, Hours.hours(8)); assertSame(Hours.MAX_VALUE, Hours.hours(Integer.MAX_VALUE)); assertSame(Hours.MIN_VALUE, Hours.hours(Integer.MIN_VALUE)); assertEquals(-1, Hours.hours(-1).getHours()); assertEquals(9, Hours.hours(9).getHours()); } //----------------------------------------------------------------------- public void testFactory_hoursBetween_RInstant() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 9, 15, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 9, 18, 0, 0, 0, PARIS); assertEquals(3, Hours.hoursBetween(start, end1).getHours()); assertEquals(0, Hours.hoursBetween(start, start).getHours()); assertEquals(0, Hours.hoursBetween(end1, end1).getHours()); assertEquals(-3, Hours.hoursBetween(end1, start).getHours()); assertEquals(6, Hours.hoursBetween(start, end2).getHours()); } public void testFactory_hoursBetween_RPartial() { LocalTime start = new LocalTime(12, 0); LocalTime end1 = new LocalTime(15, 0); @SuppressWarnings("deprecation") TimeOfDay end2 = new TimeOfDay(18, 0); assertEquals(3, Hours.hoursBetween(start, end1).getHours()); assertEquals(0, Hours.hoursBetween(start, start).getHours()); assertEquals(0, Hours.hoursBetween(end1, end1).getHours()); assertEquals(-3, Hours.hoursBetween(end1, start).getHours()); assertEquals(6, Hours.hoursBetween(start, end2).getHours()); } public void testFactory_hoursIn_RInterval() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 9, 15, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 9, 18, 0, 0, 0, PARIS); assertEquals(0, Hours.hoursIn((ReadableInterval) null).getHours()); assertEquals(3, Hours.hoursIn(new Interval(start, end1)).getHours()); assertEquals(0, Hours.hoursIn(new Interval(start, start)).getHours()); assertEquals(0, Hours.hoursIn(new Interval(end1, end1)).getHours()); assertEquals(6, Hours.hoursIn(new Interval(start, end2)).getHours()); } public void testFactory_standardHoursIn_RPeriod() { assertEquals(0, Hours.standardHoursIn((ReadablePeriod) null).getHours()); assertEquals(0, Hours.standardHoursIn(Period.ZERO).getHours()); assertEquals(1, Hours.standardHoursIn(new Period(0, 0, 0, 0, 1, 0, 0, 0)).getHours()); assertEquals(123, Hours.standardHoursIn(Period.hours(123)).getHours()); assertEquals(-987, Hours.standardHoursIn(Period.hours(-987)).getHours()); assertEquals(1, Hours.standardHoursIn(Period.minutes(119)).getHours()); assertEquals(2, Hours.standardHoursIn(Period.minutes(120)).getHours()); assertEquals(2, Hours.standardHoursIn(Period.minutes(121)).getHours()); assertEquals(48, Hours.standardHoursIn(Period.days(2)).getHours()); try { Hours.standardHoursIn(Period.months(1)); fail(); } catch (IllegalArgumentException ex) { // expeceted } } public void testFactory_parseHours_String() { assertEquals(0, Hours.parseHours((String) null).getHours()); assertEquals(0, Hours.parseHours("PT0H").getHours()); assertEquals(1, Hours.parseHours("PT1H").getHours()); assertEquals(-3, Hours.parseHours("PT-3H").getHours()); assertEquals(2, Hours.parseHours("P0Y0M0DT2H").getHours()); assertEquals(2, Hours.parseHours("PT2H0M").getHours()); try { Hours.parseHours("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Hours.parseHours("P1DT1H"); fail(); } catch (IllegalArgumentException ex) { // expeceted } } //----------------------------------------------------------------------- public void testGetMethods() { Hours test = Hours.hours(20); assertEquals(20, test.getHours()); } public void testGetFieldType() { Hours test = Hours.hours(20); assertEquals(DurationFieldType.hours(), test.getFieldType()); } public void testGetPeriodType() { Hours test = Hours.hours(20); assertEquals(PeriodType.hours(), test.getPeriodType()); } //----------------------------------------------------------------------- public void testIsGreaterThan() { assertEquals(true, Hours.THREE.isGreaterThan(Hours.TWO)); assertEquals(false, Hours.THREE.isGreaterThan(Hours.THREE)); assertEquals(false, Hours.TWO.isGreaterThan(Hours.THREE)); assertEquals(true, Hours.ONE.isGreaterThan(null)); assertEquals(false, Hours.hours(-1).isGreaterThan(null)); } public void testIsLessThan() { assertEquals(false, Hours.THREE.isLessThan(Hours.TWO)); assertEquals(false, Hours.THREE.isLessThan(Hours.THREE)); assertEquals(true, Hours.TWO.isLessThan(Hours.THREE)); assertEquals(false, Hours.ONE.isLessThan(null)); assertEquals(true, Hours.hours(-1).isLessThan(null)); } //----------------------------------------------------------------------- public void testToString() { Hours test = Hours.hours(20); assertEquals("PT20H", test.toString()); test = Hours.hours(-20); assertEquals("PT-20H", test.toString()); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Hours test = Hours.SEVEN; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Hours result = (Hours) ois.readObject(); ois.close(); assertSame(test, result); } //----------------------------------------------------------------------- public void testToStandardWeeks() { Hours test = Hours.hours(24 * 7 * 2); Weeks expected = Weeks.weeks(2); assertEquals(expected, test.toStandardWeeks()); } public void testToStandardDays() { Hours test = Hours.hours(24 * 2); Days expected = Days.days(2); assertEquals(expected, test.toStandardDays()); } public void testToStandardMinutes() { Hours test = Hours.hours(3); Minutes expected = Minutes.minutes(3 * 60); assertEquals(expected, test.toStandardMinutes()); try { Hours.MAX_VALUE.toStandardMinutes(); fail(); } catch (ArithmeticException ex) { // expected } } public void testToStandardSeconds() { Hours test = Hours.hours(3); Seconds expected = Seconds.seconds(3 * 60 * 60); assertEquals(expected, test.toStandardSeconds()); try { Hours.MAX_VALUE.toStandardSeconds(); fail(); } catch (ArithmeticException ex) { // expected } } public void testToStandardDuration() { Hours test = Hours.hours(20); Duration expected = new Duration(20L * DateTimeConstants.MILLIS_PER_HOUR); assertEquals(expected, test.toStandardDuration()); expected = new Duration(((long) Integer.MAX_VALUE) * DateTimeConstants.MILLIS_PER_HOUR); assertEquals(expected, Hours.MAX_VALUE.toStandardDuration()); } //----------------------------------------------------------------------- public void testPlus_int() { Hours test2 = Hours.hours(2); Hours result = test2.plus(3); assertEquals(2, test2.getHours()); assertEquals(5, result.getHours()); assertEquals(1, Hours.ONE.plus(0).getHours()); try { Hours.MAX_VALUE.plus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testPlus_Hours() { Hours test2 = Hours.hours(2); Hours test3 = Hours.hours(3); Hours result = test2.plus(test3); assertEquals(2, test2.getHours()); assertEquals(3, test3.getHours()); assertEquals(5, result.getHours()); assertEquals(1, Hours.ONE.plus(Hours.ZERO).getHours()); assertEquals(1, Hours.ONE.plus((Hours) null).getHours()); try { Hours.MAX_VALUE.plus(Hours.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_int() { Hours test2 = Hours.hours(2); Hours result = test2.minus(3); assertEquals(2, test2.getHours()); assertEquals(-1, result.getHours()); assertEquals(1, Hours.ONE.minus(0).getHours()); try { Hours.MIN_VALUE.minus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_Hours() { Hours test2 = Hours.hours(2); Hours test3 = Hours.hours(3); Hours result = test2.minus(test3); assertEquals(2, test2.getHours()); assertEquals(3, test3.getHours()); assertEquals(-1, result.getHours()); assertEquals(1, Hours.ONE.minus(Hours.ZERO).getHours()); assertEquals(1, Hours.ONE.minus((Hours) null).getHours()); try { Hours.MIN_VALUE.minus(Hours.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMultipliedBy_int() { Hours test = Hours.hours(2); assertEquals(6, test.multipliedBy(3).getHours()); assertEquals(2, test.getHours()); assertEquals(-6, test.multipliedBy(-3).getHours()); assertSame(test, test.multipliedBy(1)); Hours halfMax = Hours.hours(Integer.MAX_VALUE / 2 + 1); try { halfMax.multipliedBy(2); fail(); } catch (ArithmeticException ex) { // expected } } public void testDividedBy_int() { Hours test = Hours.hours(12); assertEquals(6, test.dividedBy(2).getHours()); assertEquals(12, test.getHours()); assertEquals(4, test.dividedBy(3).getHours()); assertEquals(3, test.dividedBy(4).getHours()); assertEquals(2, test.dividedBy(5).getHours()); assertEquals(2, test.dividedBy(6).getHours()); assertSame(test, test.dividedBy(1)); try { Hours.ONE.dividedBy(0); fail(); } catch (ArithmeticException ex) { // expected } } public void testNegated() { Hours test = Hours.hours(12); assertEquals(-12, test.negated().getHours()); assertEquals(12, test.getHours()); try { Hours.MIN_VALUE.negated(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testAddToLocalDate() { Hours test = Hours.hours(26); LocalDateTime date = new LocalDateTime(2006, 6, 1, 0, 0, 0, 0); LocalDateTime expected = new LocalDateTime(2006, 6, 2, 2, 0, 0, 0); assertEquals(expected, date.plus(test)); } } joda-time-2.3/src/test/java/org/joda/time/TestDays.java0000644000175000017500000003765412200501234022317 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for Days. * * @author Stephen Colebourne */ public class TestDays extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDays.class); } public TestDays(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testConstants() { assertEquals(0, Days.ZERO.getDays()); assertEquals(1, Days.ONE.getDays()); assertEquals(2, Days.TWO.getDays()); assertEquals(3, Days.THREE.getDays()); assertEquals(4, Days.FOUR.getDays()); assertEquals(5, Days.FIVE.getDays()); assertEquals(6, Days.SIX.getDays()); assertEquals(7, Days.SEVEN.getDays()); assertEquals(Integer.MAX_VALUE, Days.MAX_VALUE.getDays()); assertEquals(Integer.MIN_VALUE, Days.MIN_VALUE.getDays()); } //----------------------------------------------------------------------- public void testFactory_days_int() { assertSame(Days.ZERO, Days.days(0)); assertSame(Days.ONE, Days.days(1)); assertSame(Days.TWO, Days.days(2)); assertSame(Days.THREE, Days.days(3)); assertSame(Days.FOUR, Days.days(4)); assertSame(Days.FIVE, Days.days(5)); assertSame(Days.SIX, Days.days(6)); assertSame(Days.SEVEN, Days.days(7)); assertSame(Days.MAX_VALUE, Days.days(Integer.MAX_VALUE)); assertSame(Days.MIN_VALUE, Days.days(Integer.MIN_VALUE)); assertEquals(-1, Days.days(-1).getDays()); assertEquals(8, Days.days(8).getDays()); } //----------------------------------------------------------------------- public void testFactory_daysBetween_RInstant() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 12, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 15, 18, 0, 0, 0, PARIS); assertEquals(3, Days.daysBetween(start, end1).getDays()); assertEquals(0, Days.daysBetween(start, start).getDays()); assertEquals(0, Days.daysBetween(end1, end1).getDays()); assertEquals(-3, Days.daysBetween(end1, start).getDays()); assertEquals(6, Days.daysBetween(start, end2).getDays()); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testFactory_daysBetween_RPartial_LocalDate() { LocalDate start = new LocalDate(2006, 6, 9); LocalDate end1 = new LocalDate(2006, 6, 12); YearMonthDay end2 = new YearMonthDay(2006, 6, 15); assertEquals(3, Days.daysBetween(start, end1).getDays()); assertEquals(0, Days.daysBetween(start, start).getDays()); assertEquals(0, Days.daysBetween(end1, end1).getDays()); assertEquals(-3, Days.daysBetween(end1, start).getDays()); assertEquals(6, Days.daysBetween(start, end2).getDays()); } public void testFactory_daysBetween_RPartial_YearMonth() { YearMonth start1 = new YearMonth(2011, 1); YearMonth start2 = new YearMonth(2012, 1); YearMonth end1 = new YearMonth(2011, 3); YearMonth end2 = new YearMonth(2012, 3); assertEquals(59, Days.daysBetween(start1, end1).getDays()); assertEquals(60, Days.daysBetween(start2, end2).getDays()); assertEquals(-59, Days.daysBetween(end1, start1).getDays()); assertEquals(-60, Days.daysBetween(end2, start2).getDays()); } public void testFactory_daysBetween_RPartial_MonthDay() { MonthDay start1 = new MonthDay(2, 1); MonthDay start2 = new MonthDay(2, 28); MonthDay end1 = new MonthDay(2, 28); MonthDay end2 = new MonthDay(2, 29); assertEquals(27, Days.daysBetween(start1, end1).getDays()); assertEquals(28, Days.daysBetween(start1, end2).getDays()); assertEquals(0, Days.daysBetween(start2, end1).getDays()); assertEquals(1, Days.daysBetween(start2, end2).getDays()); assertEquals(-27, Days.daysBetween(end1, start1).getDays()); assertEquals(-28, Days.daysBetween(end2, start1).getDays()); assertEquals(0, Days.daysBetween(end1, start2).getDays()); assertEquals(-1, Days.daysBetween(end2, start2).getDays()); } //----------------------------------------------------------------------- public void testFactory_daysIn_RInterval() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 12, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 15, 18, 0, 0, 0, PARIS); assertEquals(0, Days.daysIn((ReadableInterval) null).getDays()); assertEquals(3, Days.daysIn(new Interval(start, end1)).getDays()); assertEquals(0, Days.daysIn(new Interval(start, start)).getDays()); assertEquals(0, Days.daysIn(new Interval(end1, end1)).getDays()); assertEquals(6, Days.daysIn(new Interval(start, end2)).getDays()); } //----------------------------------------------------------------------- public void testFactory_standardDaysIn_RPeriod() { assertEquals(0, Days.standardDaysIn((ReadablePeriod) null).getDays()); assertEquals(0, Days.standardDaysIn(Period.ZERO).getDays()); assertEquals(1, Days.standardDaysIn(new Period(0, 0, 0, 1, 0, 0, 0, 0)).getDays()); assertEquals(123, Days.standardDaysIn(Period.days(123)).getDays()); assertEquals(-987, Days.standardDaysIn(Period.days(-987)).getDays()); assertEquals(1, Days.standardDaysIn(Period.hours(47)).getDays()); assertEquals(2, Days.standardDaysIn(Period.hours(48)).getDays()); assertEquals(2, Days.standardDaysIn(Period.hours(49)).getDays()); assertEquals(14, Days.standardDaysIn(Period.weeks(2)).getDays()); try { Days.standardDaysIn(Period.months(1)); fail(); } catch (IllegalArgumentException ex) { // expeceted } } public void testFactory_parseDays_String() { assertEquals(0, Days.parseDays((String) null).getDays()); assertEquals(0, Days.parseDays("P0D").getDays()); assertEquals(1, Days.parseDays("P1D").getDays()); assertEquals(-3, Days.parseDays("P-3D").getDays()); assertEquals(2, Days.parseDays("P0Y0M2D").getDays()); assertEquals(2, Days.parseDays("P2DT0H0M").getDays()); try { Days.parseDays("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Days.parseDays("P1DT1H"); fail(); } catch (IllegalArgumentException ex) { // expeceted } } //----------------------------------------------------------------------- public void testGetMethods() { Days test = Days.days(20); assertEquals(20, test.getDays()); } public void testGetFieldType() { Days test = Days.days(20); assertEquals(DurationFieldType.days(), test.getFieldType()); } public void testGetPeriodType() { Days test = Days.days(20); assertEquals(PeriodType.days(), test.getPeriodType()); } //----------------------------------------------------------------------- public void testIsGreaterThan() { assertEquals(true, Days.THREE.isGreaterThan(Days.TWO)); assertEquals(false, Days.THREE.isGreaterThan(Days.THREE)); assertEquals(false, Days.TWO.isGreaterThan(Days.THREE)); assertEquals(true, Days.ONE.isGreaterThan(null)); assertEquals(false, Days.days(-1).isGreaterThan(null)); } public void testIsLessThan() { assertEquals(false, Days.THREE.isLessThan(Days.TWO)); assertEquals(false, Days.THREE.isLessThan(Days.THREE)); assertEquals(true, Days.TWO.isLessThan(Days.THREE)); assertEquals(false, Days.ONE.isLessThan(null)); assertEquals(true, Days.days(-1).isLessThan(null)); } //----------------------------------------------------------------------- public void testToString() { Days test = Days.days(20); assertEquals("P20D", test.toString()); test = Days.days(-20); assertEquals("P-20D", test.toString()); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Days test = Days.SEVEN; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Days result = (Days) ois.readObject(); ois.close(); assertSame(test, result); } //----------------------------------------------------------------------- public void testToStandardWeeks() { Days test = Days.days(14); Weeks expected = Weeks.weeks(2); assertEquals(expected, test.toStandardWeeks()); } public void testToStandardHours() { Days test = Days.days(2); Hours expected = Hours.hours(2 * 24); assertEquals(expected, test.toStandardHours()); try { Days.MAX_VALUE.toStandardHours(); fail(); } catch (ArithmeticException ex) { // expected } } public void testToStandardMinutes() { Days test = Days.days(2); Minutes expected = Minutes.minutes(2 * 24 * 60); assertEquals(expected, test.toStandardMinutes()); try { Days.MAX_VALUE.toStandardMinutes(); fail(); } catch (ArithmeticException ex) { // expected } } public void testToStandardSeconds() { Days test = Days.days(2); Seconds expected = Seconds.seconds(2 * 24 * 60 * 60); assertEquals(expected, test.toStandardSeconds()); try { Days.MAX_VALUE.toStandardSeconds(); fail(); } catch (ArithmeticException ex) { // expected } } public void testToStandardDuration() { Days test = Days.days(20); Duration expected = new Duration(20L * DateTimeConstants.MILLIS_PER_DAY); assertEquals(expected, test.toStandardDuration()); expected = new Duration(((long) Integer.MAX_VALUE) * DateTimeConstants.MILLIS_PER_DAY); assertEquals(expected, Days.MAX_VALUE.toStandardDuration()); } //----------------------------------------------------------------------- public void testPlus_int() { Days test2 = Days.days(2); Days result = test2.plus(3); assertEquals(2, test2.getDays()); assertEquals(5, result.getDays()); assertEquals(1, Days.ONE.plus(0).getDays()); try { Days.MAX_VALUE.plus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testPlus_Days() { Days test2 = Days.days(2); Days test3 = Days.days(3); Days result = test2.plus(test3); assertEquals(2, test2.getDays()); assertEquals(3, test3.getDays()); assertEquals(5, result.getDays()); assertEquals(1, Days.ONE.plus(Days.ZERO).getDays()); assertEquals(1, Days.ONE.plus((Days) null).getDays()); try { Days.MAX_VALUE.plus(Days.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_int() { Days test2 = Days.days(2); Days result = test2.minus(3); assertEquals(2, test2.getDays()); assertEquals(-1, result.getDays()); assertEquals(1, Days.ONE.minus(0).getDays()); try { Days.MIN_VALUE.minus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_Days() { Days test2 = Days.days(2); Days test3 = Days.days(3); Days result = test2.minus(test3); assertEquals(2, test2.getDays()); assertEquals(3, test3.getDays()); assertEquals(-1, result.getDays()); assertEquals(1, Days.ONE.minus(Days.ZERO).getDays()); assertEquals(1, Days.ONE.minus((Days) null).getDays()); try { Days.MIN_VALUE.minus(Days.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMultipliedBy_int() { Days test = Days.days(2); assertEquals(6, test.multipliedBy(3).getDays()); assertEquals(2, test.getDays()); assertEquals(-6, test.multipliedBy(-3).getDays()); assertSame(test, test.multipliedBy(1)); Days halfMax = Days.days(Integer.MAX_VALUE / 2 + 1); try { halfMax.multipliedBy(2); fail(); } catch (ArithmeticException ex) { // expected } } public void testDividedBy_int() { Days test = Days.days(12); assertEquals(6, test.dividedBy(2).getDays()); assertEquals(12, test.getDays()); assertEquals(4, test.dividedBy(3).getDays()); assertEquals(3, test.dividedBy(4).getDays()); assertEquals(2, test.dividedBy(5).getDays()); assertEquals(2, test.dividedBy(6).getDays()); assertSame(test, test.dividedBy(1)); try { Days.ONE.dividedBy(0); fail(); } catch (ArithmeticException ex) { // expected } } public void testNegated() { Days test = Days.days(12); assertEquals(-12, test.negated().getDays()); assertEquals(12, test.getDays()); try { Days.MIN_VALUE.negated(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testAddToLocalDate() { Days test = Days.days(20); LocalDate date = new LocalDate(2006, 6, 1); LocalDate expected = new LocalDate(2006, 6, 21); assertEquals(expected, date.plus(test)); } } joda-time-2.3/src/test/java/org/joda/time/MockPartial.java0000644000175000017500000000371711567200522022771 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.time.chrono.ISOChronology; /** * A basic mock testing class for a PartialInstant that doesn't extend AbstractPartialInstant. * * @author Stephen Colebourne */ public class MockPartial implements ReadablePartial { public static final ReadablePartial EMPTY_INSTANCE = new MockPartial(); public Chronology getChronology() { return ISOChronology.getInstanceUTC(); } public int size() { return getFields().length; } public DateTimeFieldType getFieldType(int index) { return getFields()[index].getType(); } public DateTimeField getField(int index) { return getFields()[index]; } public int getValue(int index) { return getValues()[index]; } public int get(DateTimeFieldType field) { return 0; } public boolean isSupported(DateTimeFieldType field) { return false; } public DateTime toDateTime(DateTimeZone zone) { return null; } public DateTime toDateTime(ReadableInstant base) { return null; } public DateTimeField[] getFields() { return new DateTimeField[0]; } public int[] getValues() { return new int[0]; } public int compareTo(ReadablePartial partial) { return 0; } } joda-time-2.3/src/test/java/org/joda/time/TestDateTime_Basics.java0000644000175000017500000015233412200501234024370 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractInstant; import org.joda.time.chrono.BaseChronology; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.UnsupportedDateTimeField; import org.joda.time.field.UnsupportedDurationField; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for DateTime. * * @author Stephen Colebourne */ public class TestDateTime_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); // the default time zone is set to LONDON in setUp() // we have to hard code LONDON here (instead of ISOChronology.getInstance() etc.) // as TestAll sets up a different time zone for better all-round testing private static final ISOChronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final ISOChronology ISO_DEFAULT = ISOChronology.getInstance(LONDON); private static final ISOChronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static final GJChronology GJ_DEFAULT = GJChronology.getInstance(LONDON); private static final GregorianChronology GREGORIAN_DEFAULT = GregorianChronology.getInstance(LONDON); private static final GregorianChronology GREGORIAN_PARIS = GregorianChronology.getInstance(PARIS); private static final BuddhistChronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private static final BuddhistChronology BUDDHIST_DEFAULT = BuddhistChronology.getInstance(LONDON); private static final CopticChronology COPTIC_DEFAULT = CopticChronology.getInstance(LONDON); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTime_Basics.class); } public TestDateTime_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGet_DateTimeField() { DateTime test = new DateTime(); assertEquals(1, test.get(ISO_DEFAULT.era())); assertEquals(20, test.get(ISO_DEFAULT.centuryOfEra())); assertEquals(2, test.get(ISO_DEFAULT.yearOfCentury())); assertEquals(2002, test.get(ISO_DEFAULT.yearOfEra())); assertEquals(2002, test.get(ISO_DEFAULT.year())); assertEquals(6, test.get(ISO_DEFAULT.monthOfYear())); assertEquals(9, test.get(ISO_DEFAULT.dayOfMonth())); assertEquals(2002, test.get(ISO_DEFAULT.weekyear())); assertEquals(23, test.get(ISO_DEFAULT.weekOfWeekyear())); assertEquals(7, test.get(ISO_DEFAULT.dayOfWeek())); assertEquals(160, test.get(ISO_DEFAULT.dayOfYear())); assertEquals(0, test.get(ISO_DEFAULT.halfdayOfDay())); assertEquals(1, test.get(ISO_DEFAULT.hourOfHalfday())); assertEquals(1, test.get(ISO_DEFAULT.clockhourOfDay())); assertEquals(1, test.get(ISO_DEFAULT.clockhourOfHalfday())); assertEquals(1, test.get(ISO_DEFAULT.hourOfDay())); assertEquals(0, test.get(ISO_DEFAULT.minuteOfHour())); assertEquals(60, test.get(ISO_DEFAULT.minuteOfDay())); assertEquals(0, test.get(ISO_DEFAULT.secondOfMinute())); assertEquals(60 * 60, test.get(ISO_DEFAULT.secondOfDay())); assertEquals(0, test.get(ISO_DEFAULT.millisOfSecond())); assertEquals(60 * 60 * 1000, test.get(ISO_DEFAULT.millisOfDay())); try { test.get((DateTimeField) null); fail(); } catch (IllegalArgumentException ex) {} } public void testGet_DateTimeFieldType() { DateTime test = new DateTime(); assertEquals(1, test.get(DateTimeFieldType.era())); assertEquals(20, test.get(DateTimeFieldType.centuryOfEra())); assertEquals(2, test.get(DateTimeFieldType.yearOfCentury())); assertEquals(2002, test.get(DateTimeFieldType.yearOfEra())); assertEquals(2002, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); assertEquals(2002, test.get(DateTimeFieldType.weekyear())); assertEquals(23, test.get(DateTimeFieldType.weekOfWeekyear())); assertEquals(7, test.get(DateTimeFieldType.dayOfWeek())); assertEquals(160, test.get(DateTimeFieldType.dayOfYear())); assertEquals(0, test.get(DateTimeFieldType.halfdayOfDay())); assertEquals(1, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(1, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(1, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(1, test.get(DateTimeFieldType.hourOfDay())); assertEquals(0, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(60, test.get(DateTimeFieldType.minuteOfDay())); assertEquals(0, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(60 * 60, test.get(DateTimeFieldType.secondOfDay())); assertEquals(0, test.get(DateTimeFieldType.millisOfSecond())); assertEquals(60 * 60 * 1000, test.get(DateTimeFieldType.millisOfDay())); try { test.get((DateTimeFieldType) null); fail(); } catch (IllegalArgumentException ex) {} } public void testIsSupported_DateTimeFieldType() { DateTime test = new DateTime(); assertEquals(true, test.isSupported(DateTimeFieldType.era())); assertEquals(true, test.isSupported(DateTimeFieldType.centuryOfEra())); assertEquals(true, test.isSupported(DateTimeFieldType.yearOfCentury())); assertEquals(true, test.isSupported(DateTimeFieldType.yearOfEra())); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(true, test.isSupported(DateTimeFieldType.weekyear())); assertEquals(true, test.isSupported(DateTimeFieldType.weekOfWeekyear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfWeek())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.halfdayOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfHalfday())); assertEquals(true, test.isSupported(DateTimeFieldType.clockhourOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.clockhourOfHalfday())); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.secondOfMinute())); assertEquals(true, test.isSupported(DateTimeFieldType.secondOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.millisOfSecond())); assertEquals(true, test.isSupported(DateTimeFieldType.millisOfDay())); assertEquals(false, test.isSupported(null)); } //----------------------------------------------------------------------- public void testGetters() { DateTime test = new DateTime(); assertEquals(ISO_DEFAULT, test.getChronology()); assertEquals(LONDON, test.getZone()); assertEquals(TEST_TIME_NOW, test.getMillis()); assertEquals(1, test.getEra()); assertEquals(20, test.getCenturyOfEra()); assertEquals(2, test.getYearOfCentury()); assertEquals(2002, test.getYearOfEra()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(2002, test.getWeekyear()); assertEquals(23, test.getWeekOfWeekyear()); assertEquals(7, test.getDayOfWeek()); assertEquals(160, test.getDayOfYear()); assertEquals(1, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(60, test.getMinuteOfDay()); assertEquals(0, test.getSecondOfMinute()); assertEquals(60 * 60, test.getSecondOfDay()); assertEquals(0, test.getMillisOfSecond()); assertEquals(60 * 60 * 1000, test.getMillisOfDay()); } public void testWithers() { DateTime test = new DateTime(1970, 6, 9, 10, 20, 30, 40, GJ_DEFAULT); check(test.withYear(2000), 2000, 6, 9, 10, 20, 30, 40); check(test.withMonthOfYear(2), 1970, 2, 9, 10, 20, 30, 40); check(test.withDayOfMonth(2), 1970, 6, 2, 10, 20, 30, 40); check(test.withDayOfYear(6), 1970, 1, 6, 10, 20, 30, 40); check(test.withDayOfWeek(6), 1970, 6, 13, 10, 20, 30, 40); check(test.withWeekOfWeekyear(6), 1970, 2, 3, 10, 20, 30, 40); check(test.withWeekyear(1971), 1971, 6, 15, 10, 20, 30, 40); check(test.withYearOfCentury(60), 1960, 6, 9, 10, 20, 30, 40); check(test.withCenturyOfEra(21), 2070, 6, 9, 10, 20, 30, 40); check(test.withYearOfEra(1066), 1066, 6, 9, 10, 20, 30, 40); check(test.withEra(DateTimeConstants.BC), -1970, 6, 9, 10, 20, 30, 40); check(test.withHourOfDay(6), 1970, 6, 9, 6, 20, 30, 40); check(test.withMinuteOfHour(6), 1970, 6, 9, 10, 6, 30, 40); check(test.withSecondOfMinute(6), 1970, 6, 9, 10, 20, 6, 40); check(test.withMillisOfSecond(6), 1970, 6, 9, 10, 20, 30, 6); check(test.withMillisOfDay(61234), 1970, 6, 9, 0, 1, 1, 234); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testEqualsHashCode() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME1); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); DateTime test3 = new DateTime(TEST_TIME2); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInstant())); assertEquals(false, test1.equals(new DateTime(TEST_TIME1, GREGORIAN_DEFAULT))); assertEquals(true, new DateTime(TEST_TIME1, new MockEqualsChronology()).equals(new DateTime(TEST_TIME1, new MockEqualsChronology()))); assertEquals(false, new DateTime(TEST_TIME1, new MockEqualsChronology()).equals(new DateTime(TEST_TIME1, ISO_DEFAULT))); } class MockInstant extends AbstractInstant { public String toString() { return null; } public long getMillis() { return TEST_TIME1; } public Chronology getChronology() { return ISO_DEFAULT; } } class MockEqualsChronology extends BaseChronology { private static final long serialVersionUID = 1L; public boolean equals(Object obj) { return obj instanceof MockEqualsChronology; } public DateTimeZone getZone() { return null; } public Chronology withUTC() { return this; } public Chronology withZone(DateTimeZone zone) { return this; } public String toString() { return ""; } } public void testCompareTo() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test1a = new DateTime(TEST_TIME1); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); DateTime test3 = new DateTime(TEST_TIME2, GREGORIAN_PARIS); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); assertEquals(+1, test2.compareTo(new MockInstant())); assertEquals(0, test1.compareTo(new MockInstant())); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_long() { assertEquals(false, new DateTime(TEST_TIME1).isEqual(TEST_TIME2)); assertEquals(true, new DateTime(TEST_TIME1).isEqual(TEST_TIME1)); assertEquals(false, new DateTime(TEST_TIME2).isEqual(TEST_TIME1)); } public void testIsEqualNow() { assertEquals(false, new DateTime(TEST_TIME_NOW - 1).isEqualNow()); assertEquals(true, new DateTime(TEST_TIME_NOW).isEqualNow()); assertEquals(false, new DateTime(TEST_TIME_NOW + 1).isEqualNow()); } public void testIsEqual_RI() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test1a = new DateTime(TEST_TIME1); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); DateTime test3 = new DateTime(TEST_TIME2, GREGORIAN_PARIS); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); assertEquals(false, test2.isEqual(new MockInstant())); assertEquals(true, test1.isEqual(new MockInstant())); assertEquals(false, new DateTime(TEST_TIME_NOW + 1).isEqual(null)); assertEquals(true, new DateTime(TEST_TIME_NOW).isEqual(null)); assertEquals(false, new DateTime(TEST_TIME_NOW - 1).isEqual(null)); } //----------------------------------------------------------------------- public void testIsBefore_long() { assertEquals(true, new DateTime(TEST_TIME1).isBefore(TEST_TIME2)); assertEquals(false, new DateTime(TEST_TIME1).isBefore(TEST_TIME1)); assertEquals(false, new DateTime(TEST_TIME2).isBefore(TEST_TIME1)); } public void testIsBeforeNow() { assertEquals(true, new DateTime(TEST_TIME_NOW - 1).isBeforeNow()); assertEquals(false, new DateTime(TEST_TIME_NOW).isBeforeNow()); assertEquals(false, new DateTime(TEST_TIME_NOW + 1).isBeforeNow()); } public void testIsBefore_RI() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test1a = new DateTime(TEST_TIME1); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); DateTime test3 = new DateTime(TEST_TIME2, GREGORIAN_PARIS); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); assertEquals(false, test2.isBefore(new MockInstant())); assertEquals(false, test1.isBefore(new MockInstant())); assertEquals(false, new DateTime(TEST_TIME_NOW + 1).isBefore(null)); assertEquals(false, new DateTime(TEST_TIME_NOW).isBefore(null)); assertEquals(true, new DateTime(TEST_TIME_NOW - 1).isBefore(null)); } //----------------------------------------------------------------------- public void testIsAfter_long() { assertEquals(false, new DateTime(TEST_TIME1).isAfter(TEST_TIME2)); assertEquals(false, new DateTime(TEST_TIME1).isAfter(TEST_TIME1)); assertEquals(true, new DateTime(TEST_TIME2).isAfter(TEST_TIME1)); } public void testIsAfterNow() { assertEquals(false, new DateTime(TEST_TIME_NOW - 1).isAfterNow()); assertEquals(false, new DateTime(TEST_TIME_NOW).isAfterNow()); assertEquals(true, new DateTime(TEST_TIME_NOW + 1).isAfterNow()); } public void testIsAfter_RI() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test1a = new DateTime(TEST_TIME1); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); DateTime test3 = new DateTime(TEST_TIME2, GREGORIAN_PARIS); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); assertEquals(true, test2.isAfter(new MockInstant())); assertEquals(false, test1.isAfter(new MockInstant())); assertEquals(true, new DateTime(TEST_TIME_NOW + 1).isAfter(null)); assertEquals(false, new DateTime(TEST_TIME_NOW).isAfter(null)); assertEquals(false, new DateTime(TEST_TIME_NOW - 1).isAfter(null)); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { DateTime test = new DateTime(TEST_TIME_NOW); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTime result = (DateTime) ois.readObject(); ois.close(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToString() { DateTime test = new DateTime(TEST_TIME_NOW); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString()); test = new DateTime(TEST_TIME_NOW, PARIS); assertEquals("2002-06-09T02:00:00.000+02:00", test.toString()); } public void testToString_String() { DateTime test = new DateTime(TEST_TIME_NOW); assertEquals("2002 01", test.toString("yyyy HH")); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString((String) null)); } public void testToString_String_Locale() { DateTime test = new DateTime(TEST_TIME_NOW); assertEquals("Sun 9/6", test.toString("EEE d/M", Locale.ENGLISH)); assertEquals("dim. 9/6", test.toString("EEE d/M", Locale.FRENCH)); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString(null, Locale.ENGLISH)); assertEquals("Sun 9/6", test.toString("EEE d/M", null)); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString(null, null)); } @SuppressWarnings("deprecation") public void testToString_DTFormatter() { DateMidnight test = new DateMidnight(TEST_TIME_NOW); assertEquals("2002 00", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("2002-06-09T00:00:00.000+01:00", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- public void testToInstant() { DateTime test = new DateTime(TEST_TIME1); Instant result = test.toInstant(); assertEquals(TEST_TIME1, result.getMillis()); } public void testToDateTime() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.toDateTime(); assertSame(test, result); } public void testToDateTimeISO() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.toDateTimeISO(); assertSame(test, result); test = new DateTime(TEST_TIME1, ISO_PARIS); result = test.toDateTimeISO(); assertSame(DateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_PARIS, result.getChronology()); assertNotSame(test, result); test = new DateTime(TEST_TIME1, BUDDHIST_DEFAULT); result = test.toDateTimeISO(); assertSame(DateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); assertNotSame(test, result); test = new DateTime(TEST_TIME1, new MockNullZoneChronology()); result = test.toDateTimeISO(); assertSame(DateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); assertNotSame(test, result); } public void testToDateTime_DateTimeZone() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.toDateTime(LONDON); assertSame(test, result); test = new DateTime(TEST_TIME1); result = test.toDateTime(PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(PARIS, result.getZone()); test = new DateTime(TEST_TIME1, PARIS); result = test.toDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(LONDON, result.getZone()); test = new DateTime(TEST_TIME1); result = test.toDateTime((DateTimeZone) null); assertSame(test, result); } public void testToDateTime_Chronology() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.toDateTime(ISO_DEFAULT); assertSame(test, result); test = new DateTime(TEST_TIME1); result = test.toDateTime(GREGORIAN_PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GREGORIAN_PARIS, result.getChronology()); test = new DateTime(TEST_TIME1, GREGORIAN_PARIS); result = test.toDateTime((Chronology) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.toDateTime((Chronology) null); assertSame(test, result); } public void testToMutableDateTime() { DateTime test = new DateTime(TEST_TIME1, PARIS); MutableDateTime result = test.toMutableDateTime(); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_PARIS, result.getChronology()); } public void testToMutableDateTimeISO() { DateTime test = new DateTime(TEST_TIME1, PARIS); MutableDateTime result = test.toMutableDateTimeISO(); assertSame(MutableDateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_PARIS, result.getChronology()); } public void testToMutableDateTime_DateTimeZone() { DateTime test = new DateTime(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(LONDON); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.toMutableDateTime(PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_PARIS, result.getChronology()); test = new DateTime(TEST_TIME1, PARIS); result = test.toMutableDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.toMutableDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); } public void testToMutableDateTime_Chronology() { DateTime test = new DateTime(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(ISO_DEFAULT); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.toMutableDateTime(GREGORIAN_PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GREGORIAN_PARIS, result.getChronology()); test = new DateTime(TEST_TIME1, GREGORIAN_PARIS); result = test.toMutableDateTime((Chronology) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.toMutableDateTime((Chronology) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); } public void testToDate() { DateTime test = new DateTime(TEST_TIME1); Date result = test.toDate(); assertEquals(test.getMillis(), result.getTime()); } public void testToCalendar_Locale() { DateTime test = new DateTime(TEST_TIME1); Calendar result = test.toCalendar(null); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/London"), result.getTimeZone()); test = new DateTime(TEST_TIME1, PARIS); result = test.toCalendar(null); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/Paris"), result.getTimeZone()); test = new DateTime(TEST_TIME1, PARIS); result = test.toCalendar(Locale.UK); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/Paris"), result.getTimeZone()); } public void testToGregorianCalendar() { DateTime test = new DateTime(TEST_TIME1); GregorianCalendar result = test.toGregorianCalendar(); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/London"), result.getTimeZone()); test = new DateTime(TEST_TIME1, PARIS); result = test.toGregorianCalendar(); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/Paris"), result.getTimeZone()); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testToDateMidnight() { DateTime base = new DateTime(TEST_TIME1, COPTIC_DEFAULT); DateMidnight test = base.toDateMidnight(); assertEquals(new DateMidnight(base, COPTIC_DEFAULT), test); } @SuppressWarnings("deprecation") public void testToYearMonthDay() { DateTime base = new DateTime(TEST_TIME1, COPTIC_DEFAULT); YearMonthDay test = base.toYearMonthDay(); assertEquals(new YearMonthDay(TEST_TIME1, COPTIC_DEFAULT), test); } @SuppressWarnings("deprecation") public void testToTimeOfDay() { DateTime base = new DateTime(TEST_TIME1, COPTIC_DEFAULT); TimeOfDay test = base.toTimeOfDay(); assertEquals(new TimeOfDay(TEST_TIME1, COPTIC_DEFAULT), test); } public void testToLocalDateTime() { DateTime base = new DateTime(TEST_TIME1, COPTIC_DEFAULT); LocalDateTime test = base.toLocalDateTime(); assertEquals(new LocalDateTime(TEST_TIME1, COPTIC_DEFAULT), test); } public void testToLocalDate() { DateTime base = new DateTime(TEST_TIME1, COPTIC_DEFAULT); LocalDate test = base.toLocalDate(); assertEquals(new LocalDate(TEST_TIME1, COPTIC_DEFAULT), test); } public void testToLocalTime() { DateTime base = new DateTime(TEST_TIME1, COPTIC_DEFAULT); LocalTime test = base.toLocalTime(); assertEquals(new LocalTime(TEST_TIME1, COPTIC_DEFAULT), test); } //----------------------------------------------------------------------- public void testWithMillis_long() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.withMillis(TEST_TIME2); assertEquals(TEST_TIME2, result.getMillis()); assertEquals(test.getChronology(), result.getChronology()); test = new DateTime(TEST_TIME1, GREGORIAN_PARIS); result = test.withMillis(TEST_TIME2); assertEquals(TEST_TIME2, result.getMillis()); assertEquals(test.getChronology(), result.getChronology()); test = new DateTime(TEST_TIME1); result = test.withMillis(TEST_TIME1); assertSame(test, result); } public void testWithChronology_Chronology() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.withChronology(GREGORIAN_PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GREGORIAN_PARIS, result.getChronology()); test = new DateTime(TEST_TIME1, GREGORIAN_PARIS); result = test.withChronology(null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.withChronology(null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.withChronology(ISO_DEFAULT); assertSame(test, result); } public void testWithZone_DateTimeZone() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.withZone(PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISO_PARIS, result.getChronology()); test = new DateTime(TEST_TIME1, GREGORIAN_PARIS); result = test.withZone(null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GREGORIAN_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.withZone(null); assertSame(test, result); } public void testWithZoneRetainFields_DateTimeZone() { DateTime test = new DateTime(TEST_TIME1); DateTime result = test.withZoneRetainFields(PARIS); assertEquals(test.getMillis() - DateTimeConstants.MILLIS_PER_HOUR, result.getMillis()); assertEquals(ISO_PARIS, result.getChronology()); test = new DateTime(TEST_TIME1); result = test.withZoneRetainFields(LONDON); assertSame(test, result); test = new DateTime(TEST_TIME1); result = test.withZoneRetainFields(null); assertSame(test, result); test = new DateTime(TEST_TIME1, GREGORIAN_PARIS); result = test.withZoneRetainFields(null); assertEquals(test.getMillis() + DateTimeConstants.MILLIS_PER_HOUR, result.getMillis()); assertEquals(GREGORIAN_DEFAULT, result.getChronology()); test = new DateTime(TEST_TIME1, new MockNullZoneChronology()); result = test.withZoneRetainFields(LONDON); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithDate_int_int_int() { DateTime test = new DateTime(2002, 4, 5, 1, 2, 3, 4, ISO_UTC); DateTime result = test.withDate(2003, 5, 6); DateTime expected = new DateTime(2003, 5, 6, 1, 2, 3, 4, ISO_UTC); assertEquals(expected, result); test = new DateTime(TEST_TIME1); try { test.withDate(2003, 13, 1); fail(); } catch (IllegalArgumentException ex) {} } public void testWithTime_int_int_int() { DateTime test = new DateTime(TEST_TIME1 - 12345L, BUDDHIST_UTC); DateTime result = test.withTime(12, 24, 0, 0); assertEquals(TEST_TIME1, result.getMillis()); assertEquals(BUDDHIST_UTC, result.getChronology()); test = new DateTime(TEST_TIME1); try { test.withTime(25, 1, 1, 1); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testWithFields_RPartial() { DateTime test = new DateTime(2004, 5, 6, 7, 8, 9, 0); DateTime result = test.withFields(new YearMonthDay(2003, 4, 5)); DateTime expected = new DateTime(2003, 4, 5, 7, 8, 9, 0); assertEquals(expected, result); test = new DateTime(TEST_TIME1); result = test.withFields(null); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithField1() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime result = test.withField(DateTimeFieldType.year(), 2006); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0), test); assertEquals(new DateTime(2006, 6, 9, 0, 0, 0, 0), result); } public void testWithField2() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithFieldAdded1() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime result = test.withFieldAdded(DurationFieldType.years(), 6); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0), test); assertEquals(new DateTime(2010, 6, 9, 0, 0, 0, 0), result); } public void testWithFieldAdded2() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded3() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded4() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime result = test.withFieldAdded(DurationFieldType.years(), 0); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithDurationAdded_long_int() { DateTime test = new DateTime(TEST_TIME1, BUDDHIST_DEFAULT); DateTime result = test.withDurationAdded(123456789L, 1); DateTime expected = new DateTime(TEST_TIME1 + 123456789L, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.withDurationAdded(123456789L, 0); assertSame(test, result); result = test.withDurationAdded(123456789L, 2); expected = new DateTime(TEST_TIME1 + (2L * 123456789L), BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.withDurationAdded(123456789L, -3); expected = new DateTime(TEST_TIME1 - (3L * 123456789L), BUDDHIST_DEFAULT); assertEquals(expected, result); } //----------------------------------------------------------------------- public void testWithDurationAdded_RD_int() { DateTime test = new DateTime(TEST_TIME1, BUDDHIST_DEFAULT); DateTime result = test.withDurationAdded(new Duration(123456789L), 1); DateTime expected = new DateTime(TEST_TIME1 + 123456789L, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.withDurationAdded(null, 1); assertSame(test, result); result = test.withDurationAdded(new Duration(123456789L), 0); assertSame(test, result); result = test.withDurationAdded(new Duration(123456789L), 2); expected = new DateTime(TEST_TIME1 + (2L * 123456789L), BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.withDurationAdded(new Duration(123456789L), -3); expected = new DateTime(TEST_TIME1 - (3L * 123456789L), BUDDHIST_DEFAULT); assertEquals(expected, result); } //----------------------------------------------------------------------- public void testWithDurationAdded_RP_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.withPeriodAdded(new Period(1, 2, 3, 4, 5, 6, 7, 8), 1); DateTime expected = new DateTime(2003, 7, 28, 6, 8, 10, 12, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.withPeriodAdded(null, 1); assertSame(test, result); result = test.withPeriodAdded(new Period(1, 2, 3, 4, 5, 6, 7, 8), 0); assertSame(test, result); result = test.withPeriodAdded(new Period(1, 2, 0, 4, 5, 6, 7, 8), 3); expected = new DateTime(2005, 11, 15, 16, 20, 24, 28, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.withPeriodAdded(new Period(1, 2, 0, 1, 1, 2, 3, 4), -1); expected = new DateTime(2001, 3, 2, 0, 0, 0, 0, BUDDHIST_DEFAULT); assertEquals(expected, result); } //----------------------------------------------------------------------- public void testPlus_long() { DateTime test = new DateTime(TEST_TIME1, BUDDHIST_DEFAULT); DateTime result = test.plus(123456789L); DateTime expected = new DateTime(TEST_TIME1 + 123456789L, BUDDHIST_DEFAULT); assertEquals(expected, result); } public void testPlus_RD() { DateTime test = new DateTime(TEST_TIME1, BUDDHIST_DEFAULT); DateTime result = test.plus(new Duration(123456789L)); DateTime expected = new DateTime(TEST_TIME1 + 123456789L, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plus((ReadableDuration) null); assertSame(test, result); } public void testPlus_RP() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8)); DateTime expected = new DateTime(2003, 7, 28, 6, 8, 10, 12, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusYears_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusYears(1); DateTime expected = new DateTime(2003, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusYears(0); assertSame(test, result); } public void testPlusMonths_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusMonths(1); DateTime expected = new DateTime(2002, 6, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusMonths(0); assertSame(test, result); } public void testPlusWeeks_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusWeeks(1); DateTime expected = new DateTime(2002, 5, 10, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusWeeks(0); assertSame(test, result); } public void testPlusDays_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusDays(1); DateTime expected = new DateTime(2002, 5, 4, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusDays(0); assertSame(test, result); } public void testPlusHours_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusHours(1); DateTime expected = new DateTime(2002, 5, 3, 2, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusHours(0); assertSame(test, result); } public void testPlusMinutes_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusMinutes(1); DateTime expected = new DateTime(2002, 5, 3, 1, 3, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusMinutes(0); assertSame(test, result); } public void testPlusSeconds_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusSeconds(1); DateTime expected = new DateTime(2002, 5, 3, 1, 2, 4, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusSeconds(0); assertSame(test, result); } public void testPlusMillis_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.plusMillis(1); DateTime expected = new DateTime(2002, 5, 3, 1, 2, 3, 5, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.plusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_long() { DateTime test = new DateTime(TEST_TIME1, BUDDHIST_DEFAULT); DateTime result = test.minus(123456789L); DateTime expected = new DateTime(TEST_TIME1 - 123456789L, BUDDHIST_DEFAULT); assertEquals(expected, result); } public void testMinus_RD() { DateTime test = new DateTime(TEST_TIME1, BUDDHIST_DEFAULT); DateTime result = test.minus(new Duration(123456789L)); DateTime expected = new DateTime(TEST_TIME1 - 123456789L, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minus((ReadableDuration) null); assertSame(test, result); } public void testMinus_RP() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); DateTime expected = new DateTime(2001, 3, 26, 0, 1, 2, 3, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusYears_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusYears(1); DateTime expected = new DateTime(2001, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusYears(0); assertSame(test, result); } public void testMinusMonths_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusMonths(1); DateTime expected = new DateTime(2002, 4, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusMonths(0); assertSame(test, result); } public void testMinusWeeks_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusWeeks(1); DateTime expected = new DateTime(2002, 4, 26, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusWeeks(0); assertSame(test, result); } public void testMinusDays_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusDays(1); DateTime expected = new DateTime(2002, 5, 2, 1, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusDays(0); assertSame(test, result); } public void testMinusHours_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusHours(1); DateTime expected = new DateTime(2002, 5, 3, 0, 2, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusHours(0); assertSame(test, result); } public void testMinusMinutes_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusMinutes(1); DateTime expected = new DateTime(2002, 5, 3, 1, 1, 3, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusMinutes(0); assertSame(test, result); } public void testMinusSeconds_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusSeconds(1); DateTime expected = new DateTime(2002, 5, 3, 1, 2, 2, 4, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusSeconds(0); assertSame(test, result); } public void testMinusMillis_int() { DateTime test = new DateTime(2002, 5, 3, 1, 2, 3, 4, BUDDHIST_DEFAULT); DateTime result = test.minusMillis(1); DateTime expected = new DateTime(2002, 5, 3, 1, 2, 3, 3, BUDDHIST_DEFAULT); assertEquals(expected, result); result = test.minusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testProperty() { DateTime test = new DateTime(); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek())); assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute())); assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond())); DateTimeFieldType bad = new DateTimeFieldType("bad") { private static final long serialVersionUID = 1L; public DurationFieldType getDurationType() { return DurationFieldType.weeks(); } public DurationFieldType getRangeDurationType() { return null; } public DateTimeField getField(Chronology chronology) { return UnsupportedDateTimeField.getInstance(this, UnsupportedDurationField.getInstance(getDurationType())); } }; try { test.property(bad); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- private void check(DateTime test, int year, int month, int day, int hour, int min, int sec, int mil) { assertEquals(year, test.getYear()); assertEquals(month, test.getMonthOfYear()); assertEquals(day, test.getDayOfMonth()); assertEquals(hour, test.getHourOfDay()); assertEquals(min, test.getMinuteOfHour()); assertEquals(sec, test.getSecondOfMinute()); assertEquals(mil, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutablePeriod_Basics.java0000644000175000017500000005340211564251364025446 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.BasePeriod; /** * This class is a Junit unit test for MutableDuration. * * @author Stephen Colebourne */ public class TestMutablePeriod_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutablePeriod_Basics.class); } public TestMutablePeriod_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGetPeriodType() { MutablePeriod test = new MutablePeriod(); assertEquals(PeriodType.standard(), test.getPeriodType()); } public void testGetMethods() { MutablePeriod test = new MutablePeriod(); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getDays()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testEqualsHashCode() { MutablePeriod test1 = new MutablePeriod(123L); MutablePeriod test2 = new MutablePeriod(123L); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); MutablePeriod test3 = new MutablePeriod(321L); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockMutablePeriod(123L))); assertEquals(false, test1.equals(new Period(123L, PeriodType.dayTime()))); } class MockMutablePeriod extends BasePeriod { public MockMutablePeriod(long value) { super(value, null, null); } } //----------------------------------------------------------------------- public void testSerialization() throws Exception { MutablePeriod test = new MutablePeriod(123L); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); MutablePeriod result = (MutablePeriod) ois.readObject(); ois.close(); assertEquals(test, result); } // //----------------------------------------------------------------------- // public void testAddTo1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, 1); // assertEquals(expected, added); // } // // public void testAddTo2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, -2); // assertEquals(expected, added); // } // // public void testAddTo3() { // long expected = TEST_TIME_NOW; // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, 0); // assertEquals(expected, added); // } // // public void testAddTo4() { // long expected = TEST_TIME_NOW + 100L; // MutablePeriod test = new MutablePeriod(100L); // long added = test.addTo(TEST_TIME_NOW, 1); // assertEquals(expected, added); // } // // //----------------------------------------------------------------------- // public void testAddToWithChronology1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, 1, ISOChronology.getInstance()); // assertEquals(expected, added); // } // // public void testAddToWithChronology2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstanceUTC().years().add(expected, -2); // expected = ISOChronology.getInstanceUTC().months().add(expected, -4); // expected = ISOChronology.getInstanceUTC().weeks().add(expected, -6); // expected = ISOChronology.getInstanceUTC().days().add(expected, -8); // expected = ISOChronology.getInstanceUTC().hours().add(expected, -10); // expected = ISOChronology.getInstanceUTC().minutes().add(expected, -12); // expected = ISOChronology.getInstanceUTC().seconds().add(expected, -14); // expected = ISOChronology.getInstanceUTC().millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // long added = test.addTo(TEST_TIME_NOW, -2, ISOChronology.getInstanceUTC()); // chrono specified so use it // assertEquals(expected, added); // } // // public void testAddToWithChronology3() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // long added = test.addTo(TEST_TIME_NOW, -2, null); // no chrono so use default // assertEquals(expected, added); // } // // //----------------------------------------------------------------------- // public void testAddToRI1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); // DateTime added = test.addTo(new Instant(), 1); // Instant has no time zone, use default // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(), added.getChronology()); // } // // public void testAddToRI2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(new Instant(), -2); // Instant has no time zone, use default // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(), added.getChronology()); // } // // public void testAddToRI3() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstanceUTC().years().add(expected, -2); // expected = ISOChronology.getInstanceUTC().months().add(expected, -4); // expected = ISOChronology.getInstanceUTC().weeks().add(expected, -6); // expected = ISOChronology.getInstanceUTC().days().add(expected, -8); // expected = ISOChronology.getInstanceUTC().hours().add(expected, -10); // expected = ISOChronology.getInstanceUTC().minutes().add(expected, -12); // expected = ISOChronology.getInstanceUTC().seconds().add(expected, -14); // expected = ISOChronology.getInstanceUTC().millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(new DateTime(ISOChronology.getInstanceUTC()), -2); // DateTime has UTC time zone // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstanceUTC(), added.getChronology()); // } // // public void testAddToRI4() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance(PARIS).years().add(expected, -2); // expected = ISOChronology.getInstance(PARIS).months().add(expected, -4); // expected = ISOChronology.getInstance(PARIS).weeks().add(expected, -6); // expected = ISOChronology.getInstance(PARIS).days().add(expected, -8); // expected = ISOChronology.getInstance(PARIS).hours().add(expected, -10); // expected = ISOChronology.getInstance(PARIS).minutes().add(expected, -12); // expected = ISOChronology.getInstance(PARIS).seconds().add(expected, -14); // expected = ISOChronology.getInstance(PARIS).millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(new DateTime(PARIS), -2); // DateTime has PARIS time zone // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(PARIS), added.getChronology()); // } // // public void testAddToRI5() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(null, -2); // null has no time zone, use default // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(), added.getChronology()); // } // // //----------------------------------------------------------------------- // public void testAddIntoRWI1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); // MutableDateTime mdt = new MutableDateTime(); // test.addInto(mdt, 1); // assertEquals(expected, mdt.getMillis()); // } // // public void testAddIntoRWI2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // MutableDateTime mdt = new MutableDateTime(); // test.addInto(mdt, -2); // MutableDateTime has a chronology, use it // assertEquals(expected, mdt.getMillis()); // } // // public void testAddIntoRWI3() { // MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); // try { // test.addInto(null, 1); // fail(); // } catch (IllegalArgumentException ex) {} // } //----------------------------------------------------------------------- public void testToString() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); assertEquals("P1Y2M3W4DT5H6M7.008S", test.toString()); test = new MutablePeriod(0, 0, 0, 0, 0, 0, 0, 0); assertEquals("PT0S", test.toString()); test = new MutablePeriod(12345L); assertEquals("PT12.345S", test.toString()); } //----------------------------------------------------------------------- public void testToPeriod() { MutablePeriod test = new MutablePeriod(123L); Period result = test.toPeriod(); assertEquals(test, result); } public void testToMutablePeriod() { MutablePeriod test = new MutablePeriod(123L); MutablePeriod result = test.toMutablePeriod(); assertEquals(test, result); } //----------------------------------------------------------------------- // public void testToDurationMillisFrom() { // MutablePeriod test = new MutablePeriod(123L); // assertEquals(123L, test.toDurationMillisFrom(0L, null)); // } public void testToDurationFrom() { MutablePeriod test = new MutablePeriod(123L); assertEquals(new Duration(123L), test.toDurationFrom(new Instant(0L))); } //----------------------------------------------------------------------- public void testCopy() { MutablePeriod test = new MutablePeriod(123L); MutablePeriod copy = test.copy(); assertEquals(test.getPeriodType(), copy.getPeriodType()); assertEquals(test, copy); } //----------------------------------------------------------------------- public void testClone() { MutablePeriod test = new MutablePeriod(123L); MutablePeriod copy = (MutablePeriod) test.clone(); assertEquals(test.getPeriodType(), copy.getPeriodType()); assertEquals(test, copy); } } joda-time-2.3/src/test/java/org/joda/time/TestDateTime_Properties.java0000644000175000017500000021612712200501234025321 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.StrictChronology; /** * This class is a Junit unit test for DateTime. * * @author Stephen Colebourne * @author Mike Schrag */ public class TestDateTime_Properties extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); //private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 Fri private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 Tue private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTime_Properties.class); } public TestDateTime_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); Locale.setDefault(locale); zone = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testPropertyGetEra() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().era(), test.era().getField()); assertEquals("era", test.era().getName()); assertEquals("Property[era]", test.era().toString()); assertSame(test, test.era().getDateTime()); assertEquals(1, test.era().get()); assertEquals("1", test.era().getAsString()); assertEquals("AD", test.era().getAsText()); assertEquals("AD", test.era().getField().getAsText(1, Locale.ENGLISH)); assertEquals("ap. J.-C.", test.era().getAsText(Locale.FRENCH)); assertEquals("ap. J.-C.", test.era().getField().getAsText(1, Locale.FRENCH)); assertEquals("AD", test.era().getAsShortText()); assertEquals("AD", test.era().getField().getAsShortText(1, Locale.ENGLISH)); assertEquals("ap. J.-C.", test.era().getAsShortText(Locale.FRENCH)); assertEquals("ap. J.-C.", test.era().getField().getAsShortText(1, Locale.FRENCH)); assertEquals(test.getChronology().eras(), test.era().getDurationField()); assertEquals(null, test.era().getRangeDurationField()); assertEquals(2, test.era().getMaximumTextLength(null)); assertEquals(9, test.era().getMaximumTextLength(Locale.FRENCH)); assertEquals(2, test.era().getMaximumShortTextLength(null)); assertEquals(9, test.era().getMaximumShortTextLength(Locale.FRENCH)); } //----------------------------------------------------------------------- public void testPropertyGetYearOfEra() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().yearOfEra(), test.yearOfEra().getField()); assertEquals("yearOfEra", test.yearOfEra().getName()); assertEquals("Property[yearOfEra]", test.yearOfEra().toString()); assertSame(test, test.yearOfEra().getDateTime()); assertEquals(2004, test.yearOfEra().get()); assertEquals("2004", test.yearOfEra().getAsString()); assertEquals("2004", test.yearOfEra().getAsText()); assertEquals("2004", test.yearOfEra().getAsText(Locale.FRENCH)); assertEquals("2004", test.yearOfEra().getAsShortText()); assertEquals("2004", test.yearOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfEra().getDurationField()); assertEquals(null, test.yearOfEra().getRangeDurationField()); assertEquals(9, test.yearOfEra().getMaximumTextLength(null)); assertEquals(9, test.yearOfEra().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetCenturyOfEra() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().centuryOfEra(), test.centuryOfEra().getField()); assertEquals("centuryOfEra", test.centuryOfEra().getName()); assertEquals("Property[centuryOfEra]", test.centuryOfEra().toString()); assertSame(test, test.centuryOfEra().getDateTime()); assertEquals(20, test.centuryOfEra().get()); assertEquals("20", test.centuryOfEra().getAsString()); assertEquals("20", test.centuryOfEra().getAsText()); assertEquals("20", test.centuryOfEra().getAsText(Locale.FRENCH)); assertEquals("20", test.centuryOfEra().getAsShortText()); assertEquals("20", test.centuryOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().centuries(), test.centuryOfEra().getDurationField()); assertEquals(null, test.centuryOfEra().getRangeDurationField()); assertEquals(7, test.centuryOfEra().getMaximumTextLength(null)); assertEquals(7, test.centuryOfEra().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetYearOfCentury() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().yearOfCentury(), test.yearOfCentury().getField()); assertEquals("yearOfCentury", test.yearOfCentury().getName()); assertEquals("Property[yearOfCentury]", test.yearOfCentury().toString()); assertSame(test, test.yearOfCentury().getDateTime()); assertEquals(4, test.yearOfCentury().get()); assertEquals("4", test.yearOfCentury().getAsString()); assertEquals("4", test.yearOfCentury().getAsText()); assertEquals("4", test.yearOfCentury().getAsText(Locale.FRENCH)); assertEquals("4", test.yearOfCentury().getAsShortText()); assertEquals("4", test.yearOfCentury().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfCentury().getDurationField()); assertEquals(test.getChronology().centuries(), test.yearOfCentury().getRangeDurationField()); assertEquals(2, test.yearOfCentury().getMaximumTextLength(null)); assertEquals(2, test.yearOfCentury().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetWeekyear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().weekyear(), test.weekyear().getField()); assertEquals("weekyear", test.weekyear().getName()); assertEquals("Property[weekyear]", test.weekyear().toString()); assertSame(test, test.weekyear().getDateTime()); assertEquals(2004, test.weekyear().get()); assertEquals("2004", test.weekyear().getAsString()); assertEquals("2004", test.weekyear().getAsText()); assertEquals("2004", test.weekyear().getAsText(Locale.FRENCH)); assertEquals("2004", test.weekyear().getAsShortText()); assertEquals("2004", test.weekyear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().weekyears(), test.weekyear().getDurationField()); assertEquals(null, test.weekyear().getRangeDurationField()); assertEquals(9, test.weekyear().getMaximumTextLength(null)); assertEquals(9, test.weekyear().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertSame(test, test.year().getDateTime()); assertEquals(2004, test.year().get()); assertEquals("2004", test.year().getAsString()); assertEquals("2004", test.year().getAsText()); assertEquals("2004", test.year().getAsText(Locale.FRENCH)); assertEquals("2004", test.year().getAsShortText()); assertEquals("2004", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292278993, test.year().getMaximumValue()); assertEquals(292278993, test.year().getMaximumValueOverall()); } public void testPropertyLeapYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertEquals(true, test.year().isLeap()); assertEquals(1, test.year().getLeapAmount()); assertEquals(test.getChronology().days(), test.year().getLeapDurationField()); test = new DateTime(2003, 6, 9, 0, 0, 0, 0); assertEquals(false, test.year().isLeap()); assertEquals(0, test.year().getLeapAmount()); assertEquals(test.getChronology().days(), test.year().getLeapDurationField()); } public void testPropertyAddYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().addToCopy(9); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2013-06-09T00:00:00.000+01:00", copy.toString()); copy = test.year().addToCopy(0); assertEquals("2004-06-09T00:00:00.000+01:00", copy.toString()); copy = test.year().addToCopy(292277023 - 2004); assertEquals(292277023, copy.getYear()); try { test.year().addToCopy(292278993 - 2004 + 1); fail(); } catch (IllegalArgumentException ex) {} copy = test.year().addToCopy(-2004); assertEquals(0, copy.getYear()); copy = test.year().addToCopy(-2005); assertEquals(-1, copy.getYear()); try { test.year().addToCopy(-292275054 - 2004 - 1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyAddWrapFieldYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().addWrapFieldToCopy(9); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2013-06-09T00:00:00.000+01:00", copy.toString()); copy = test.year().addWrapFieldToCopy(0); assertEquals(2004, copy.getYear()); copy = test.year().addWrapFieldToCopy(292278993 - 2004 + 1); assertEquals(-292275054, copy.getYear()); copy = test.year().addWrapFieldToCopy(-292275054 - 2004 - 1); assertEquals(292278993, copy.getYear()); } public void testPropertySetYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().setCopy(1960); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1960-06-09T00:00:00.000+01:00", copy.toString()); } public void testPropertySetTextYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.year().setCopy("1960"); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("1960-06-09T00:00:00.000+01:00", copy.toString()); } public void testPropertyCompareToYear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.year().compareTo(test2) < 0); assertEquals(true, test2.year().compareTo(test1) > 0); assertEquals(true, test1.year().compareTo(test1) == 0); try { test1.year().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testPropertyCompareToYear2() { DateTime test1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); YearMonthDay ymd1 = new YearMonthDay(2003, 6, 9); YearMonthDay ymd2 = new YearMonthDay(2004, 6, 9); YearMonthDay ymd3 = new YearMonthDay(2005, 6, 9); assertEquals(true, test1.year().compareTo(ymd1) > 0); assertEquals(true, test1.year().compareTo(ymd2) == 0); assertEquals(true, test1.year().compareTo(ymd3) < 0); try { test1.year().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyEqualsHashCodeYear() { DateTime test1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertEquals(true, test1.year().equals(test1.year())); assertEquals(true, test1.year().equals(new DateTime(2004, 6, 9, 0, 0, 0, 0).year())); assertEquals(false, test1.year().equals(new DateTime(2004, 6, 9, 0, 0, 0, 0).monthOfYear())); assertEquals(false, test1.year().equals(new DateTime(2004, 6, 9, 0, 0, 0, 0, CopticChronology.getInstance()).year())); assertEquals(true, test1.year().hashCode() == test1.year().hashCode()); assertEquals(true, test1.year().hashCode() == new DateTime(2004, 6, 9, 0, 0, 0, 0).year().hashCode()); assertEquals(false, test1.year().hashCode() == new DateTime(2004, 6, 9, 0, 0, 0, 0).monthOfYear().hashCode()); assertEquals(false, test1.year().hashCode() == new DateTime(2004, 6, 9, 0, 0, 0, 0, CopticChronology.getInstance()).year().hashCode()); } //----------------------------------------------------------------------- public void testPropertyGetMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getDateTime()); assertEquals(6, test.monthOfYear().get()); assertEquals("6", test.monthOfYear().getAsString()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("June", test.monthOfYear().getField().getAsText(6, Locale.ENGLISH)); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juin", test.monthOfYear().getField().getAsText(6, Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("Jun", test.monthOfYear().getField().getAsShortText(6, Locale.ENGLISH)); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals("juin", test.monthOfYear().getField().getAsShortText(6, Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new DateTime(2004, 7, 9, 0, 0, 0, 0); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juillet", test.monthOfYear().getField().getAsText(7, Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getField().getAsShortText(7, Locale.FRENCH)); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyLeapMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertEquals(false, test.monthOfYear().isLeap()); assertEquals(0, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); test = new DateTime(2004, 2, 9, 0, 0, 0, 0); assertEquals(true, test.monthOfYear().isLeap()); assertEquals(1, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); test = new DateTime(2003, 6, 9, 0, 0, 0, 0); assertEquals(false, test.monthOfYear().isLeap()); assertEquals(0, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); test = new DateTime(2003, 2, 9, 0, 0, 0, 0); assertEquals(false, test.monthOfYear().isLeap()); assertEquals(0, test.monthOfYear().getLeapAmount()); assertEquals(test.getChronology().days(), test.monthOfYear().getLeapDurationField()); } public void testPropertyAddMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().addToCopy(6); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-12-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(7); assertEquals("2005-01-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(-5); assertEquals("2004-01-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(-6); assertEquals("2003-12-09T00:00:00.000Z", copy.toString()); test = new DateTime(2004, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addToCopy(1); assertEquals("2004-01-31T00:00:00.000Z", test.toString()); assertEquals("2004-02-29T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addToCopy(2); assertEquals("2004-03-31T00:00:00.000+01:00", copy.toString()); copy = test.monthOfYear().addToCopy(3); assertEquals("2004-04-30T00:00:00.000+01:00", copy.toString()); test = new DateTime(2003, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addToCopy(1); assertEquals("2003-02-28T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().addWrapFieldToCopy(4); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-10-09T00:00:00.000+01:00", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(8); assertEquals("2004-02-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(-8); assertEquals("2004-10-09T00:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addWrapFieldToCopy(1); assertEquals("2004-01-31T00:00:00.000Z", test.toString()); assertEquals("2004-02-29T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(2); assertEquals("2004-03-31T00:00:00.000+01:00", copy.toString()); copy = test.monthOfYear().addWrapFieldToCopy(3); assertEquals("2004-04-30T00:00:00.000+01:00", copy.toString()); test = new DateTime(2005, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().addWrapFieldToCopy(1); assertEquals("2005-01-31T00:00:00.000Z", test.toString()); assertEquals("2005-02-28T00:00:00.000Z", copy.toString()); } public void testPropertySetMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().setCopy(12); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-12-09T00:00:00.000Z", copy.toString()); test = new DateTime(2004, 1, 31, 0, 0, 0, 0); copy = test.monthOfYear().setCopy(2); assertEquals("2004-02-29T00:00:00.000Z", copy.toString()); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.monthOfYear().setCopy("12"); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-12-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().setCopy("December"); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-12-09T00:00:00.000Z", copy.toString()); copy = test.monthOfYear().setCopy("Dec"); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-12-09T00:00:00.000Z", copy.toString()); } public void testPropertyCompareToMonthOfYear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertSame(test, test.dayOfMonth().getDateTime()); assertEquals(9, test.dayOfMonth().get()); assertEquals("9", test.dayOfMonth().getAsString()); assertEquals("9", test.dayOfMonth().getAsText()); assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("9", test.dayOfMonth().getAsShortText()); assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); assertEquals(false, test.dayOfMonth().isLeap()); assertEquals(0, test.dayOfMonth().getLeapAmount()); assertEquals(null, test.dayOfMonth().getLeapDurationField()); } public void testPropertyGetMaxMinValuesDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); test = new DateTime(2004, 7, 9, 0, 0, 0, 0); assertEquals(31, test.dayOfMonth().getMaximumValue()); test = new DateTime(2004, 2, 9, 0, 0, 0, 0); assertEquals(29, test.dayOfMonth().getMaximumValue()); test = new DateTime(2003, 2, 9, 0, 0, 0, 0); assertEquals(28, test.dayOfMonth().getMaximumValue()); } public void testPropertyAddDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().addToCopy(9); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-18T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(21); assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(22); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(22 + 30); assertEquals("2004-07-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(22 + 31); assertEquals("2004-08-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("2004-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfMonth().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("2005-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfMonth().addToCopy(-8); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(-9); assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); assertEquals("2004-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfMonth().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); assertEquals("2003-12-31T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().addWrapFieldToCopy(21); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(22); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(-12); assertEquals("2004-06-27T00:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 7, 9, 0, 0, 0, 0); copy = test.dayOfMonth().addWrapFieldToCopy(21); assertEquals("2004-07-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(22); assertEquals("2004-07-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(23); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfMonth().addWrapFieldToCopy(-12); assertEquals("2004-07-28T00:00:00.000+01:00", copy.toString()); } public void testPropertySetDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().setCopy(12); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-12T00:00:00.000+01:00", copy.toString()); try { test.dayOfMonth().setCopy(31); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfMonth().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().setCopy("12"); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-12T00:00:00.000+01:00", copy.toString()); } public void testPropertyWithMaximumValueDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().withMaximumValue(); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString()); } public void testPropertyWithMaximumValueMillisOfDayDSTGap() { DateTimeZone paris = DateTimeZone.forID("Europe/Paris"); DateTime dt = new DateTime(1926, 4, 17, 18, 0, 0, 0, paris); // DST gap 23:00 to 00:00 DateTime test = dt.millisOfDay().withMaximumValue(); assertEquals("1926-04-17T22:59:59.999Z", test.toString()); } public void testPropertyWithMinimumValueDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfMonth().withMinimumValue(); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); } public void testPropertyWithMinimumValueMillisOfDayDSTGap() { DateTimeZone gaza = DateTimeZone.forID("Asia/Gaza"); DateTime dt = new DateTime(2001, 4, 20, 18, 0, 0, 0, gaza); // DST gap 00:00 to 01:00 DateTime test = dt.millisOfDay().withMinimumValue(); assertEquals("2001-04-20T01:00:00.000+03:00", test.toString()); } public void testPropertyCompareToDayOfMonth() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetDayOfYear() { // 31+29+31+30+31+9 = 161 DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfYear(), test.dayOfYear().getField()); assertEquals("dayOfYear", test.dayOfYear().getName()); assertEquals("Property[dayOfYear]", test.dayOfYear().toString()); assertSame(test, test.dayOfYear().getDateTime()); assertEquals(161, test.dayOfYear().get()); assertEquals("161", test.dayOfYear().getAsString()); assertEquals("161", test.dayOfYear().getAsText()); assertEquals("161", test.dayOfYear().getAsText(Locale.FRENCH)); assertEquals("161", test.dayOfYear().getAsShortText()); assertEquals("161", test.dayOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.dayOfYear().getRangeDurationField()); assertEquals(3, test.dayOfYear().getMaximumTextLength(null)); assertEquals(3, test.dayOfYear().getMaximumShortTextLength(null)); assertEquals(false, test.dayOfYear().isLeap()); assertEquals(0, test.dayOfYear().getLeapAmount()); assertEquals(null, test.dayOfYear().getLeapDurationField()); } public void testPropertyGetMaxMinValuesDayOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertEquals(1, test.dayOfYear().getMinimumValue()); assertEquals(1, test.dayOfYear().getMinimumValueOverall()); assertEquals(366, test.dayOfYear().getMaximumValue()); assertEquals(366, test.dayOfYear().getMaximumValueOverall()); test = new DateTime(2002, 6, 9, 0, 0, 0, 0); assertEquals(365, test.dayOfYear().getMaximumValue()); assertEquals(366, test.dayOfYear().getMaximumValueOverall()); } public void testPropertyAddDayOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().addToCopy(9); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-18T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(21); assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(22); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("2004-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("2005-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addToCopy(-8); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(-9); assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); assertEquals("2004-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); assertEquals("2003-12-31T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldDayOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().addWrapFieldToCopy(21); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(22); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(-12); assertEquals("2004-05-28T00:00:00.000+01:00", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(205); assertEquals("2004-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(206); assertEquals("2004-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(-160); assertEquals("2004-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfYear().addWrapFieldToCopy(-161); assertEquals("2004-12-31T00:00:00.000Z", copy.toString()); } public void testPropertySetDayOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().setCopy(12); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-01-12T00:00:00.000Z", copy.toString()); try { test.dayOfYear().setCopy(367); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDayOfYear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfYear().setCopy("12"); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-01-12T00:00:00.000Z", copy.toString()); } public void testPropertyCompareToDayOfYear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfYear().compareTo(test2) < 0); assertEquals(true, test2.dayOfYear().compareTo(test1) > 0); assertEquals(true, test1.dayOfYear().compareTo(test1) == 0); try { test1.dayOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfYear().compareTo(dt2) < 0); assertEquals(true, test2.dayOfYear().compareTo(dt1) > 0); assertEquals(true, test1.dayOfYear().compareTo(dt1) == 0); try { test1.dayOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetWeekOfWeekyear() { // 2002-01-01 = Thu // 2002-12-31 = Thu (+364 days) // 2003-12-30 = Thu (+364 days) // 2004-01-03 = Mon W1 // 2004-01-31 = Mon (+28 days) W5 // 2004-02-28 = Mon (+28 days) W9 // 2004-03-27 = Mon (+28 days) W13 // 2004-04-24 = Mon (+28 days) W17 // 2004-05-23 = Mon (+28 days) W21 // 2004-06-05 = Mon (+14 days) W23 // 2004-06-09 = Fri // 2004-12-25 = Mon W52 // 2005-01-01 = Mon W1 DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().weekOfWeekyear(), test.weekOfWeekyear().getField()); assertEquals("weekOfWeekyear", test.weekOfWeekyear().getName()); assertEquals("Property[weekOfWeekyear]", test.weekOfWeekyear().toString()); assertSame(test, test.weekOfWeekyear().getDateTime()); assertEquals(24, test.weekOfWeekyear().get()); assertEquals("24", test.weekOfWeekyear().getAsString()); assertEquals("24", test.weekOfWeekyear().getAsText()); assertEquals("24", test.weekOfWeekyear().getAsText(Locale.FRENCH)); assertEquals("24", test.weekOfWeekyear().getAsShortText()); assertEquals("24", test.weekOfWeekyear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().weeks(), test.weekOfWeekyear().getDurationField()); assertEquals(test.getChronology().weekyears(), test.weekOfWeekyear().getRangeDurationField()); assertEquals(2, test.weekOfWeekyear().getMaximumTextLength(null)); assertEquals(2, test.weekOfWeekyear().getMaximumShortTextLength(null)); assertEquals(false, test.weekOfWeekyear().isLeap()); assertEquals(0, test.weekOfWeekyear().getLeapAmount()); assertEquals(null, test.weekOfWeekyear().getLeapDurationField()); } public void testPropertyGetMaxMinValuesWeekOfWeekyear() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertEquals(1, test.weekOfWeekyear().getMinimumValue()); assertEquals(1, test.weekOfWeekyear().getMinimumValueOverall()); assertEquals(53, test.weekOfWeekyear().getMaximumValue()); assertEquals(53, test.weekOfWeekyear().getMaximumValueOverall()); test = new DateTime(2005, 6, 9, 0, 0, 0, 0); assertEquals(52, test.weekOfWeekyear().getMaximumValue()); assertEquals(53, test.weekOfWeekyear().getMaximumValueOverall()); } public void testPropertyAddWeekOfWeekyear() { DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().addToCopy(1); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-14T00:00:00.000+01:00", copy.toString()); copy = test.weekOfWeekyear().addToCopy(29); assertEquals("2004-12-27T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addToCopy(30); assertEquals("2005-01-03T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addToCopy(-22); assertEquals("2004-01-05T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addToCopy(-23); assertEquals("2003-12-29T00:00:00.000Z", copy.toString()); } public void testPropertyAddWrapFieldWeekOfWeekyear() { DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().addWrapFieldToCopy(1); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-14T00:00:00.000+01:00", copy.toString()); copy = test.weekOfWeekyear().addWrapFieldToCopy(29); assertEquals("2004-12-27T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addWrapFieldToCopy(30); assertEquals("2003-12-29T00:00:00.000Z", copy.toString()); copy = test.weekOfWeekyear().addWrapFieldToCopy(-23); assertEquals("2003-12-29T00:00:00.000Z", copy.toString()); } public void testPropertySetWeekOfWeekyear() { DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().setCopy(4); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); assertEquals("2004-01-19T00:00:00.000Z", copy.toString()); try { test.weekOfWeekyear().setCopy(54); fail(); } catch (IllegalArgumentException ex) {} try { test.weekOfWeekyear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextWeekOfWeekyear() { DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0); DateTime copy = test.weekOfWeekyear().setCopy("4"); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); assertEquals("2004-01-19T00:00:00.000Z", copy.toString()); } public void testPropertyCompareToWeekOfWeekyear() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test1.weekOfWeekyear().compareTo(test2) < 0); assertEquals(true, test2.weekOfWeekyear().compareTo(test1) > 0); assertEquals(true, test1.weekOfWeekyear().compareTo(test1) == 0); try { test1.weekOfWeekyear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.weekOfWeekyear().compareTo(dt2) < 0); assertEquals(true, test2.weekOfWeekyear().compareTo(dt1) > 0); assertEquals(true, test1.weekOfWeekyear().compareTo(dt1) == 0); try { test1.weekOfWeekyear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetDayOfWeek() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfWeek(), test.dayOfWeek().getField()); assertEquals("dayOfWeek", test.dayOfWeek().getName()); assertEquals("Property[dayOfWeek]", test.dayOfWeek().toString()); assertSame(test, test.dayOfWeek().getDateTime()); assertEquals(3, test.dayOfWeek().get()); assertEquals("3", test.dayOfWeek().getAsString()); assertEquals("Wednesday", test.dayOfWeek().getAsText()); assertEquals("Wednesday", test.dayOfWeek().getField().getAsText(3, Locale.ENGLISH)); assertEquals("mercredi", test.dayOfWeek().getAsText(Locale.FRENCH)); assertEquals("mercredi", test.dayOfWeek().getField().getAsText(3, Locale.FRENCH)); assertEquals("Wed", test.dayOfWeek().getAsShortText()); assertEquals("Wed", test.dayOfWeek().getField().getAsShortText(3, Locale.ENGLISH)); assertEquals("mer.", test.dayOfWeek().getAsShortText(Locale.FRENCH)); assertEquals("mer.", test.dayOfWeek().getField().getAsShortText(3, Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfWeek().getDurationField()); assertEquals(test.getChronology().weeks(), test.dayOfWeek().getRangeDurationField()); assertEquals(9, test.dayOfWeek().getMaximumTextLength(null)); assertEquals(8, test.dayOfWeek().getMaximumTextLength(Locale.FRENCH)); assertEquals(3, test.dayOfWeek().getMaximumShortTextLength(null)); assertEquals(4, test.dayOfWeek().getMaximumShortTextLength(Locale.FRENCH)); assertEquals(1, test.dayOfWeek().getMinimumValue()); assertEquals(1, test.dayOfWeek().getMinimumValueOverall()); assertEquals(7, test.dayOfWeek().getMaximumValue()); assertEquals(7, test.dayOfWeek().getMaximumValueOverall()); assertEquals(false, test.dayOfWeek().isLeap()); assertEquals(0, test.dayOfWeek().getLeapAmount()); assertEquals(null, test.dayOfWeek().getLeapDurationField()); } public void testPropertyAddDayOfWeek() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().addToCopy(1); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(21); assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(22); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("2004-12-31T00:00:00.000Z", copy.toString()); copy = test.dayOfWeek().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); assertEquals("2005-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfWeek().addToCopy(-8); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(-9); assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); assertEquals("2004-01-01T00:00:00.000Z", copy.toString()); copy = test.dayOfWeek().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); assertEquals("2003-12-31T00:00:00.000Z", copy.toString()); } public void testPropertyAddLongDayOfWeek() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().addToCopy(1L); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString()); } public void testPropertyAddWrapFieldDayOfWeek() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); // Wed DateTime copy = test.dayOfWeek().addWrapFieldToCopy(1); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addWrapFieldToCopy(5); assertEquals("2004-06-07T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().addWrapFieldToCopy(-10); assertEquals("2004-06-13T00:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 2, 0, 0, 0, 0); copy = test.dayOfWeek().addWrapFieldToCopy(5); assertEquals("2004-06-02T00:00:00.000+01:00", test.toString()); assertEquals("2004-05-31T00:00:00.000+01:00", copy.toString()); } public void testPropertySetDayOfWeek() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().setCopy(4); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString()); try { test.dayOfWeek().setCopy(8); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfWeek().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDayOfWeek() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime copy = test.dayOfWeek().setCopy("4"); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-10T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().setCopy("Mon"); assertEquals("2004-06-07T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().setCopy("Tuesday"); assertEquals("2004-06-08T00:00:00.000+01:00", copy.toString()); copy = test.dayOfWeek().setCopy("lundi", Locale.FRENCH); assertEquals("2004-06-07T00:00:00.000+01:00", copy.toString()); } public void testPropertyCompareToDayOfWeek() { DateTime test1 = new DateTime(TEST_TIME1); DateTime test2 = new DateTime(TEST_TIME2); assertEquals(true, test2.dayOfWeek().compareTo(test1) < 0); assertEquals(true, test1.dayOfWeek().compareTo(test2) > 0); assertEquals(true, test1.dayOfWeek().compareTo(test1) == 0); try { test1.dayOfWeek().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test2.dayOfWeek().compareTo(dt1) < 0); assertEquals(true, test1.dayOfWeek().compareTo(dt2) > 0); assertEquals(true, test1.dayOfWeek().compareTo(dt1) == 0); try { test1.dayOfWeek().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().hourOfDay(), test.hourOfDay().getField()); assertEquals("hourOfDay", test.hourOfDay().getName()); assertEquals("Property[hourOfDay]", test.hourOfDay().toString()); assertSame(test, test.hourOfDay().getDateTime()); assertEquals(13, test.hourOfDay().get()); assertEquals("13", test.hourOfDay().getAsString()); assertEquals("13", test.hourOfDay().getAsText()); assertEquals("13", test.hourOfDay().getAsText(Locale.FRENCH)); assertEquals("13", test.hourOfDay().getAsShortText()); assertEquals("13", test.hourOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().hours(), test.hourOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.hourOfDay().getRangeDurationField()); assertEquals(2, test.hourOfDay().getMaximumTextLength(null)); assertEquals(2, test.hourOfDay().getMaximumShortTextLength(null)); } public void testPropertyGetDifferenceHourOfDay() { DateTime test1 = new DateTime(2004, 6, 9, 13, 30, 0, 0); DateTime test2 = new DateTime(2004, 6, 9, 15, 30, 0, 0); assertEquals(-2, test1.hourOfDay().getDifference(test2)); assertEquals(2, test2.hourOfDay().getDifference(test1)); assertEquals(-2L, test1.hourOfDay().getDifferenceAsLong(test2)); assertEquals(2L, test2.hourOfDay().getDifferenceAsLong(test1)); DateTime test = new DateTime(TEST_TIME_NOW + (13L * DateTimeConstants.MILLIS_PER_HOUR)); assertEquals(13, test.hourOfDay().getDifference(null)); assertEquals(13L, test.hourOfDay().getDifferenceAsLong(null)); } public void testPropertyRoundFloorHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0); DateTime copy = test.hourOfDay().roundFloorCopy(); assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString()); } public void testPropertyRoundCeilingHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0); DateTime copy = test.hourOfDay().roundCeilingCopy(); assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString()); } public void testPropertyRoundHalfFloorHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0); DateTime copy = test.hourOfDay().roundHalfFloorCopy(); assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 9, 13, 30, 0, 1); copy = test.hourOfDay().roundHalfFloorCopy(); assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 9, 13, 29, 59, 999); copy = test.hourOfDay().roundHalfFloorCopy(); assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString()); } public void testPropertyRoundHalfCeilingHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0); DateTime copy = test.hourOfDay().roundHalfCeilingCopy(); assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 9, 13, 30, 0, 1); copy = test.hourOfDay().roundHalfCeilingCopy(); assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 9, 13, 29, 59, 999); copy = test.hourOfDay().roundHalfCeilingCopy(); assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString()); } public void testPropertyRoundHalfEvenHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0); DateTime copy = test.hourOfDay().roundHalfEvenCopy(); assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 9, 14, 30, 0, 0); copy = test.hourOfDay().roundHalfEvenCopy(); assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 9, 13, 30, 0, 1); copy = test.hourOfDay().roundHalfEvenCopy(); assertEquals("2004-06-09T14:00:00.000+01:00", copy.toString()); test = new DateTime(2004, 6, 9, 13, 29, 59, 999); copy = test.hourOfDay().roundHalfEvenCopy(); assertEquals("2004-06-09T13:00:00.000+01:00", copy.toString()); } public void testPropertyRemainderHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 30, 0, 0); assertEquals(30L * DateTimeConstants.MILLIS_PER_MINUTE, test.hourOfDay().remainder()); } //----------------------------------------------------------------------- public void testPropertyGetMinuteOfHour() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().minuteOfHour(), test.minuteOfHour().getField()); assertEquals("minuteOfHour", test.minuteOfHour().getName()); assertEquals("Property[minuteOfHour]", test.minuteOfHour().toString()); assertSame(test, test.minuteOfHour().getDateTime()); assertEquals(23, test.minuteOfHour().get()); assertEquals("23", test.minuteOfHour().getAsString()); assertEquals("23", test.minuteOfHour().getAsText()); assertEquals("23", test.minuteOfHour().getAsText(Locale.FRENCH)); assertEquals("23", test.minuteOfHour().getAsShortText()); assertEquals("23", test.minuteOfHour().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.minuteOfHour().getDurationField()); assertEquals(test.getChronology().hours(), test.minuteOfHour().getRangeDurationField()); assertEquals(2, test.minuteOfHour().getMaximumTextLength(null)); assertEquals(2, test.minuteOfHour().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetMinuteOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().minuteOfDay(), test.minuteOfDay().getField()); assertEquals("minuteOfDay", test.minuteOfDay().getName()); assertEquals("Property[minuteOfDay]", test.minuteOfDay().toString()); assertSame(test, test.minuteOfDay().getDateTime()); assertEquals(803, test.minuteOfDay().get()); assertEquals("803", test.minuteOfDay().getAsString()); assertEquals("803", test.minuteOfDay().getAsText()); assertEquals("803", test.minuteOfDay().getAsText(Locale.FRENCH)); assertEquals("803", test.minuteOfDay().getAsShortText()); assertEquals("803", test.minuteOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.minuteOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.minuteOfDay().getRangeDurationField()); assertEquals(4, test.minuteOfDay().getMaximumTextLength(null)); assertEquals(4, test.minuteOfDay().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetSecondOfMinute() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().secondOfMinute(), test.secondOfMinute().getField()); assertEquals("secondOfMinute", test.secondOfMinute().getName()); assertEquals("Property[secondOfMinute]", test.secondOfMinute().toString()); assertSame(test, test.secondOfMinute().getDateTime()); assertEquals(43, test.secondOfMinute().get()); assertEquals("43", test.secondOfMinute().getAsString()); assertEquals("43", test.secondOfMinute().getAsText()); assertEquals("43", test.secondOfMinute().getAsText(Locale.FRENCH)); assertEquals("43", test.secondOfMinute().getAsShortText()); assertEquals("43", test.secondOfMinute().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().seconds(), test.secondOfMinute().getDurationField()); assertEquals(test.getChronology().minutes(), test.secondOfMinute().getRangeDurationField()); assertEquals(2, test.secondOfMinute().getMaximumTextLength(null)); assertEquals(2, test.secondOfMinute().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetSecondOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().secondOfDay(), test.secondOfDay().getField()); assertEquals("secondOfDay", test.secondOfDay().getName()); assertEquals("Property[secondOfDay]", test.secondOfDay().toString()); assertSame(test, test.secondOfDay().getDateTime()); assertEquals(48223, test.secondOfDay().get()); assertEquals("48223", test.secondOfDay().getAsString()); assertEquals("48223", test.secondOfDay().getAsText()); assertEquals("48223", test.secondOfDay().getAsText(Locale.FRENCH)); assertEquals("48223", test.secondOfDay().getAsShortText()); assertEquals("48223", test.secondOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().seconds(), test.secondOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.secondOfDay().getRangeDurationField()); assertEquals(5, test.secondOfDay().getMaximumTextLength(null)); assertEquals(5, test.secondOfDay().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetMillisOfSecond() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().millisOfSecond(), test.millisOfSecond().getField()); assertEquals("millisOfSecond", test.millisOfSecond().getName()); assertEquals("Property[millisOfSecond]", test.millisOfSecond().toString()); assertSame(test, test.millisOfSecond().getDateTime()); assertEquals(53, test.millisOfSecond().get()); assertEquals("53", test.millisOfSecond().getAsString()); assertEquals("53", test.millisOfSecond().getAsText()); assertEquals("53", test.millisOfSecond().getAsText(Locale.FRENCH)); assertEquals("53", test.millisOfSecond().getAsShortText()); assertEquals("53", test.millisOfSecond().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().millis(), test.millisOfSecond().getDurationField()); assertEquals(test.getChronology().seconds(), test.millisOfSecond().getRangeDurationField()); assertEquals(3, test.millisOfSecond().getMaximumTextLength(null)); assertEquals(3, test.millisOfSecond().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetMillisOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().millisOfDay(), test.millisOfDay().getField()); assertEquals("millisOfDay", test.millisOfDay().getName()); assertEquals("Property[millisOfDay]", test.millisOfDay().toString()); assertSame(test, test.millisOfDay().getDateTime()); assertEquals(48223053, test.millisOfDay().get()); assertEquals("48223053", test.millisOfDay().getAsString()); assertEquals("48223053", test.millisOfDay().getAsText()); assertEquals("48223053", test.millisOfDay().getAsText(Locale.FRENCH)); assertEquals("48223053", test.millisOfDay().getAsShortText()); assertEquals("48223053", test.millisOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().millis(), test.millisOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.millisOfDay().getRangeDurationField()); assertEquals(8, test.millisOfDay().getMaximumTextLength(null)); assertEquals(8, test.millisOfDay().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyToIntervalYearOfEra() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.yearOfEra().toInterval(); assertEquals(new DateTime(2004, 1, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new DateTime(2005, 1, 1, 0, 0, 0, 0), testInterval.getEnd()); } public void testPropertyToIntervalYearOfCentury() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.yearOfCentury().toInterval(); assertEquals(new DateTime(2004, 1, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new DateTime(2005, 1, 1, 0, 0, 0, 0), testInterval.getEnd()); } public void testPropertyToIntervalYear() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.year().toInterval(); assertEquals(new DateTime(2004, 1, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new DateTime(2005, 1, 1, 0, 0, 0, 0), testInterval.getEnd()); } public void testPropertyToIntervalMonthOfYear() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.monthOfYear().toInterval(); assertEquals(new DateTime(2004, 6, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new DateTime(2004, 7, 1, 0, 0, 0, 0), testInterval.getEnd()); } public void testPropertyToIntervalDayOfMonth() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.dayOfMonth().toInterval(); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new DateTime(2004, 6, 10, 0, 0, 0, 0), testInterval.getEnd()); DateTime febTest = new DateTime(2004, 2, 29, 13, 23, 43, 53); Interval febTestInterval = febTest.dayOfMonth().toInterval(); assertEquals(new DateTime(2004, 2, 29, 0, 0, 0, 0), febTestInterval.getStart()); assertEquals(new DateTime(2004, 3, 1, 0, 0, 0, 0), febTestInterval.getEnd()); } public void testPropertyToIntervalHourOfDay() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.hourOfDay().toInterval(); assertEquals(new DateTime(2004, 6, 9, 13, 0, 0, 0), testInterval.getStart()); assertEquals(new DateTime(2004, 6, 9, 14, 0, 0, 0), testInterval.getEnd()); DateTime midnightTest = new DateTime(2004, 6, 9, 23, 23, 43, 53); Interval midnightTestInterval = midnightTest.hourOfDay().toInterval(); assertEquals(new DateTime(2004, 6, 9, 23, 0, 0, 0), midnightTestInterval.getStart()); assertEquals(new DateTime(2004, 6, 10, 0, 0, 0, 0), midnightTestInterval.getEnd()); } public void testPropertyToIntervalMinuteOfHour() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.minuteOfHour().toInterval(); assertEquals(new DateTime(2004, 6, 9, 13, 23, 0, 0), testInterval.getStart()); assertEquals(new DateTime(2004, 6, 9, 13, 24, 0, 0), testInterval.getEnd()); } public void testPropertyToIntervalSecondOfMinute() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.secondOfMinute().toInterval(); assertEquals(new DateTime(2004, 6, 9, 13, 23, 43, 0), testInterval.getStart()); assertEquals(new DateTime(2004, 6, 9, 13, 23, 44, 0), testInterval.getEnd()); } public void testPropertyToIntervalMillisOfSecond() { DateTime test = new DateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.millisOfSecond().toInterval(); assertEquals(new DateTime(2004, 6, 9, 13, 23, 43, 53), testInterval.getStart()); assertEquals(new DateTime(2004, 6, 9, 13, 23, 43, 54), testInterval.getEnd()); } public void testPropertyEqualsHashCodeLenient() { DateTime test1 = new DateTime(1970, 6, 9, 0, 0, 0, 0, LenientChronology.getInstance(COPTIC_PARIS)); DateTime test2 = new DateTime(1970, 6, 9, 0, 0, 0, 0, LenientChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } public void testPropertyEqualsHashCodeStrict() { DateTime test1 = new DateTime(1970, 6, 9, 0, 0, 0, 0, StrictChronology.getInstance(COPTIC_PARIS)); DateTime test2 = new DateTime(1970, 6, 9, 0, 0, 0, 0, StrictChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } } joda-time-2.3/src/test/java/org/joda/time/TestYearMonthDay_Constructors.java0000644000175000017500000004211212200501234026534 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for YearMonthDay. * * @author Stephen Colebourne */ @SuppressWarnings("deprecation") public class TestYearMonthDay_Constructors extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology GREGORIAN_UTC = GregorianChronology.getInstanceUTC(); private static final Chronology GREGORIAN_PARIS = GregorianChronology.getInstance(PARIS); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestYearMonthDay_Constructors.class); } public TestYearMonthDay_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testFactory_FromCalendarFields() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); YearMonthDay expected = new YearMonthDay(1970, 2, 3); assertEquals(expected, YearMonthDay.fromCalendarFields(cal)); try { YearMonthDay.fromCalendarFields(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFactory_FromDateFields() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); YearMonthDay expected = new YearMonthDay(1970, 2, 3); assertEquals(expected, YearMonthDay.fromDateFields(cal.getTime())); try { YearMonthDay.fromDateFields(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstructor() throws Throwable { YearMonthDay test = new YearMonthDay(); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } /** * Test constructor (DateTimeZone) */ public void testConstructor_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 0, 0, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris YearMonthDay test = new YearMonthDay(LONDON); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(8, test.getDayOfMonth()); test = new YearMonthDay(PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } /** * Test constructor (DateTimeZone=null) */ public void testConstructor_nullDateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 0, 0, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris YearMonthDay test = new YearMonthDay((DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(8, test.getDayOfMonth()); } /** * Test constructor (Chronology) */ public void testConstructor_Chronology() throws Throwable { YearMonthDay test = new YearMonthDay(GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } /** * Test constructor (Chronology=null) */ public void testConstructor_nullChronology() throws Throwable { YearMonthDay test = new YearMonthDay((Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } //----------------------------------------------------------------------- /** * Test constructor (long) */ public void testConstructor_long1() throws Throwable { YearMonthDay test = new YearMonthDay(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } /** * Test constructor (long) */ public void testConstructor_long2() throws Throwable { YearMonthDay test = new YearMonthDay(TEST_TIME2); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long1_Chronology() throws Throwable { YearMonthDay test = new YearMonthDay(TEST_TIME1, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long2_Chronology() throws Throwable { YearMonthDay test = new YearMonthDay(TEST_TIME2, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); assertEquals(7, test.getDayOfMonth()); } /** * Test constructor (long, Chronology=null) */ public void testConstructor_long_nullChronology() throws Throwable { YearMonthDay test = new YearMonthDay(TEST_TIME1, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } //----------------------------------------------------------------------- public void testConstructor_Object() throws Throwable { Date date = new Date(TEST_TIME1); YearMonthDay test = new YearMonthDay(date); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } public void testConstructor_nullObject() throws Throwable { YearMonthDay test = new YearMonthDay((Object) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } public void testConstructor_ObjectString1() throws Throwable { YearMonthDay test = new YearMonthDay("1972-12-03"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); } public void testConstructor_ObjectString2() throws Throwable { YearMonthDay test = new YearMonthDay("1972-12-03T+14:00"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(2, test.getDayOfMonth()); // timezone } public void testConstructor_ObjectString3() throws Throwable { YearMonthDay test = new YearMonthDay("1972-12-03T10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); } public void testConstructor_ObjectString4() throws Throwable { YearMonthDay test = new YearMonthDay("1972-12-03T10:20:30.040+14:00"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(2, test.getDayOfMonth()); // timezone } public void testConstructor_ObjectString5() throws Throwable { YearMonthDay test = new YearMonthDay("10"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getYear()); assertEquals(1, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); } public void testConstructor_ObjectStringEx1() throws Throwable { try { new YearMonthDay("T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testConstructor_ObjectStringEx2() throws Throwable { try { new YearMonthDay("T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testConstructor_ObjectStringEx3() throws Throwable { try { new YearMonthDay("10:20:30.040"); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testConstructor_ObjectStringEx4() throws Throwable { try { new YearMonthDay("10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- /** * Test constructor (Object, Chronology) */ public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); YearMonthDay test = new YearMonthDay(date, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } /** * Test constructor (Object=null, Chronology) */ public void testConstructor_nullObject_Chronology() throws Throwable { YearMonthDay test = new YearMonthDay((Object) null, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } /** * Test constructor (Object, Chronology=null) */ public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); YearMonthDay test = new YearMonthDay(date, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); assertEquals(6, test.getDayOfMonth()); } /** * Test constructor (Object=null, Chronology=null) */ public void testConstructor_nullObject_nullChronology() throws Throwable { YearMonthDay test = new YearMonthDay((Object) null, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } //----------------------------------------------------------------------- /** * Test constructor (int, int, int) */ public void testConstructor_int_int_int() throws Throwable { YearMonthDay test = new YearMonthDay(1970, 6, 9); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); try { new YearMonthDay(Integer.MIN_VALUE, 6, 9); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(Integer.MAX_VALUE, 6, 9); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 0, 9); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 13, 9); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 6, 0); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 6, 31); fail(); } catch (IllegalArgumentException ex) {} new YearMonthDay(1970, 7, 31); try { new YearMonthDay(1970, 7, 32); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology) */ public void testConstructor_int_int_int_Chronology() throws Throwable { YearMonthDay test = new YearMonthDay(1970, 6, 9, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); try { new YearMonthDay(Integer.MIN_VALUE, 6, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(Integer.MAX_VALUE, 6, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 0, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 13, 9, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 6, 0, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonthDay(1970, 6, 31, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} new YearMonthDay(1970, 7, 31, GREGORIAN_PARIS); try { new YearMonthDay(1970, 7, 32, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology=null) */ public void testConstructor_int_int_int_nullChronology() throws Throwable { YearMonthDay test = new YearMonthDay(1970, 6, 9, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutableDateTime_Constructors.java0000644000175000017500000005611411616003375027222 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Date; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.MockZeroNullIntegerConverter; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for MutableDateTime. * * @author Stephen Colebourne */ public class TestMutableDateTime_Constructors extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutableDateTime_Constructors.class); } public TestMutableDateTime_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); java.util.TimeZone.setDefault(LONDON.toTimeZone()); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); java.util.TimeZone.setDefault(zone.toTimeZone()); Locale.setDefault(locale); zone = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- /** * Test now () */ public void test_now() throws Throwable { MutableDateTime test = MutableDateTime.now(); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test now (DateTimeZone) */ public void test_now_DateTimeZone() throws Throwable { MutableDateTime test = MutableDateTime.now(PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test now (DateTimeZone=null) */ public void test_now_nullDateTimeZone() throws Throwable { try { MutableDateTime.now((DateTimeZone) null); fail(); } catch (NullPointerException ex) {} } /** * Test now (Chronology) */ public void test_now_Chronology() throws Throwable { MutableDateTime test = MutableDateTime.now(GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test now (Chronology=null) */ public void test_now_nullChronology() throws Throwable { try { MutableDateTime.now((Chronology) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new MutableDateTime(2010, 6, 30, 1, 20, 0, 0, ISOChronology.getInstance(DateTimeZone.forOffsetHours(2))), MutableDateTime.parse("2010-06-30T01:20+02:00")); assertEquals(new MutableDateTime(2010, 1, 2, 14, 50, 0, 0, ISOChronology.getInstance(LONDON)), MutableDateTime.parse("2010-002T14:50")); } public void testParse_formatter() throws Throwable { DateTimeFormatter f = DateTimeFormat.forPattern("yyyy--dd MM HH").withChronology(ISOChronology.getInstance(PARIS)); assertEquals(new MutableDateTime(2010, 6, 30, 13, 0, 0, 0, ISOChronology.getInstance(PARIS)), MutableDateTime.parse("2010--30 06 13", f)); } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstructor() throws Throwable { MutableDateTime test = new MutableDateTime(); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (DateTimeZone) */ public void testConstructor_DateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime(PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (DateTimeZone=null) */ public void testConstructor_nullDateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime((DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Chronology) */ public void testConstructor_Chronology() throws Throwable { MutableDateTime test = new MutableDateTime(GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Chronology=null) */ public void testConstructor_nullChronology() throws Throwable { MutableDateTime test = new MutableDateTime((Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (long) */ public void testConstructor_long1() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME1); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long) */ public void testConstructor_long2() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME2); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME2, test.getMillis()); } /** * Test constructor (long, DateTimeZone) */ public void testConstructor_long1_DateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME1, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long, DateTimeZone) */ public void testConstructor_long2_DateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME2, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME2, test.getMillis()); } /** * Test constructor (long, DateTimeZone=null) */ public void testConstructor_long_nullDateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME1, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long1_Chronology() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME1, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long2_Chronology() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME2, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME2, test.getMillis()); } /** * Test constructor (long, Chronology=null) */ public void testConstructor_long_nullChronology() throws Throwable { MutableDateTime test = new MutableDateTime(TEST_TIME1, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (Object) */ public void testConstructor_Object() throws Throwable { Date date = new Date(TEST_TIME1); MutableDateTime test = new MutableDateTime(date); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object) */ public void testConstructor_invalidObject() throws Throwable { try { new MutableDateTime(new Object()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null) */ public void testConstructor_nullObject() throws Throwable { MutableDateTime test = new MutableDateTime((Object) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object=null) */ public void testConstructor_badconverterObject() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); MutableDateTime test = new MutableDateTime(new Integer(0)); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_Object_DateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); MutableDateTime test = new MutableDateTime(date, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_invalidObject_DateTimeZone() throws Throwable { try { new MutableDateTime(new Object(), PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null, DateTimeZone) */ public void testConstructor_nullObject_DateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime((Object) null, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, DateTimeZone=null) */ public void testConstructor_Object_nullDateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); MutableDateTime test = new MutableDateTime(date, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object=null, DateTimeZone=null) */ public void testConstructor_nullObject_nullDateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime((Object) null, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_badconverterObject_DateTimeZone() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); MutableDateTime test = new MutableDateTime(new Integer(0), GregorianChronology.getInstance()); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } /** * Test constructor (Object, Chronology) */ public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); MutableDateTime test = new MutableDateTime(date, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object, Chronology) */ public void testConstructor_invalidObject_Chronology() throws Throwable { try { new MutableDateTime(new Object(), GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null, Chronology) */ public void testConstructor_nullObject_Chronology() throws Throwable { MutableDateTime test = new MutableDateTime((Object) null, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, Chronology=null) */ public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); MutableDateTime test = new MutableDateTime(date, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1, test.getMillis()); } /** * Test constructor (Object=null, Chronology=null) */ public void testConstructor_nullObject_nullChronology() throws Throwable { MutableDateTime test = new MutableDateTime((Object) null, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (Object, Chronology) */ public void testConstructor_badconverterObject_Chronology() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); MutableDateTime test = new MutableDateTime(new Integer(0), GregorianChronology.getInstance()); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } //----------------------------------------------------------------------- /** * Test constructor (int, int, int) */ public void testConstructor_int_int_int_int_int_int_int() throws Throwable { MutableDateTime test = new MutableDateTime(2002, 6, 9, 1, 0, 0, 0); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(LONDON, test.getZone()); assertEquals(TEST_TIME_NOW, test.getMillis()); try { new MutableDateTime(Integer.MIN_VALUE, 6, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(Integer.MAX_VALUE, 6, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 0, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 13, 9, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 6, 0, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 6, 31, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} new MutableDateTime(2002, 7, 31, 0, 0, 0, 0); try { new MutableDateTime(2002, 7, 32, 0, 0, 0, 0); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, DateTimeZone) */ public void testConstructor_int_int_int_int_int_int_int_DateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime(2002, 6, 9, 2, 0, 0, 0, PARIS); // +02:00 assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); try { new MutableDateTime(Integer.MIN_VALUE, 6, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(Integer.MAX_VALUE, 6, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 0, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 13, 9, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 6, 0, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 6, 31, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} new MutableDateTime(2002, 7, 31, 0, 0, 0, 0, PARIS); try { new MutableDateTime(2002, 7, 32, 0, 0, 0, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, DateTimeZone=null) */ public void testConstructor_int_int_int_int_int_int_int_nullDateTimeZone() throws Throwable { MutableDateTime test = new MutableDateTime(2002, 6, 9, 1, 0, 0, 0, (DateTimeZone) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } /** * Test constructor (int, int, int, Chronology) */ public void testConstructor_int_int_int_int_int_int_int_Chronology() throws Throwable { MutableDateTime test = new MutableDateTime(2002, 6, 9, 1, 0, 0, 0, GregorianChronology.getInstance()); // +01:00 assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); try { new MutableDateTime(Integer.MIN_VALUE, 6, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(Integer.MAX_VALUE, 6, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 0, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 13, 9, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 6, 0, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new MutableDateTime(2002, 6, 31, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} new MutableDateTime(2002, 7, 31, 0, 0, 0, 0, GregorianChronology.getInstance()); try { new MutableDateTime(2002, 7, 32, 0, 0, 0, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology=null) */ public void testConstructor_int_int_int_int_int_int_int_nullChronology() throws Throwable { MutableDateTime test = new MutableDateTime(2002, 6, 9, 1, 0, 0, 0, (Chronology) null); // +01:00 assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW, test.getMillis()); } } joda-time-2.3/src/test/java/org/joda/time/TestStringConvert.java0000644000175000017500000002013512200501234024210 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.convert.StringConvert; import org.joda.time.chrono.ISOChronology; /** * Test string conversion. * * @author Stephen Colebourne */ public class TestStringConvert extends TestCase { private static final DateTimeZone ZONE = DateTimeZone.forID("+02:00"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestStringConvert.class); } public TestStringConvert(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testDateMidnight() { DateMidnight test = new DateMidnight(2010, 6, 30, ISOChronology.getInstance(ZONE)); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("2010-06-30T00:00:00.000+02:00", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(DateMidnight.class, str)); } public void testDateTime() { DateTime test = new DateTime(2010, 6, 30, 2, 30, 50, 678, ISOChronology.getInstance(ZONE)); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("2010-06-30T02:30:50.678+02:00", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(DateTime.class, str)); } public void testMutableDateTime() { MutableDateTime test = new MutableDateTime(2010, 6, 30, 2, 30, 50, 678, ISOChronology.getInstance(ZONE)); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("2010-06-30T02:30:50.678+02:00", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(MutableDateTime.class, str)); } public void testLocalDateTime() { LocalDateTime test = new LocalDateTime(2010, 6, 30, 2, 30); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("2010-06-30T02:30:00.000", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(LocalDateTime.class, str)); } public void testLocalDate() { LocalDate test = new LocalDate(2010, 6, 30); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("2010-06-30", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(LocalDate.class, str)); } public void testLocalTime() { LocalTime test = new LocalTime(2, 30, 50, 678); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("02:30:50.678", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(LocalTime.class, str)); } public void testYearMonth() { YearMonth test = new YearMonth(2010, 6); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("2010-06", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(YearMonth.class, str)); } public void testMonthDay() { MonthDay test = new MonthDay(6, 30); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("--06-30", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(MonthDay.class, str)); } public void testMonthDay_leapDay() { MonthDay test = new MonthDay(2, 29); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("--02-29", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(MonthDay.class, str)); } //----------------------------------------------------------------------- public void testTimeZone() { DateTimeZone test = DateTimeZone.forID("Europe/Paris"); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("Europe/Paris", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(DateTimeZone.class, str)); } // public void testInterval() { // DateTime a = new DateTime(2010, 6, 30, 2, 30, 50, 678, ISOChronology.getInstance(ZONE)); // DateTime b = new DateTime(2011, 9, 10, 4, 20, 40, 234, ISOChronology.getInstance(ZONE)); // Interval test = new Interval(a, b); // String str = StringConvert.INSTANCE.convertToString(test); // assertEquals("2010-06-30T02:30:50.678+02:00/2011-09-10T04:20:40.234+02:00", str); // assertEquals(test, StringConvert.INSTANCE.convertFromString(Interval.class, str)); // } public void testDuration() { Duration test = new Duration(12345678L); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("PT12345.678S", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Duration.class, str)); } public void testPeriod() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("P1Y2M3W4DT5H6M7.008S", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Period.class, str)); } public void testMutablePeriod() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("P1Y2M3W4DT5H6M7.008S", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(MutablePeriod.class, str)); } public void testYears() { Years test = Years.years(5); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("P5Y", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Years.class, str)); } public void testMonths() { Months test = Months.months(5); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("P5M", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Months.class, str)); } public void testWeeks() { Weeks test = Weeks.weeks(5); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("P5W", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Weeks.class, str)); } public void testDays() { Days test = Days.days(5); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("P5D", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Days.class, str)); } public void testHours() { Hours test = Hours.hours(5); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("PT5H", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Hours.class, str)); } public void testMinutes() { Minutes test = Minutes.minutes(5); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("PT5M", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Minutes.class, str)); } public void testSeconds() { Seconds test = Seconds.seconds(5); String str = StringConvert.INSTANCE.convertToString(test); assertEquals("PT5S", str); assertEquals(test, StringConvert.INSTANCE.convertFromString(Seconds.class, str)); } } joda-time-2.3/src/test/java/org/joda/time/TestDateTimeComparator.java0000644000175000017500000011327211564251363025153 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for the * org.joda.time.DateTimeComparator class. * * @author Guy Allard */ public class TestDateTimeComparator extends TestCase { private static final Chronology ISO = ISOChronology.getInstance(); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeComparator.class); } public TestDateTimeComparator(String name) { super(name); } /** * A reference to a DateTime object. */ DateTime aDateTime = null; /** * A reference to a DateTime object. */ DateTime bDateTime = null; /** * A reference to a DateTimeComparator object * (a Comparator) for millis of seconds. */ Comparator cMillis = null; /** * A reference to a DateTimeComparator object * (a Comparator) for seconds. */ Comparator cSecond = null; /** * A reference to a DateTimeComparator object * (a Comparator) for minutes. */ Comparator cMinute = null; /** * A reference to a DateTimeComparator object * (a Comparator) for hours. */ Comparator cHour = null; /** * A reference to a DateTimeComparator object * (a Comparator) for day of the week. */ Comparator cDayOfWeek = null; /** * A reference to a DateTimeComparator object * (a Comparator) for day of the month. */ Comparator cDayOfMonth = null; /** * A reference to a DateTimeComparator object * (a Comparator) for day of the year. */ Comparator cDayOfYear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for week of the weekyear. */ Comparator cWeekOfWeekyear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for year given a week of the year. */ Comparator cWeekyear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for months. */ Comparator cMonth = null; /** * A reference to a DateTimeComparator object * (a Comparator) for year. */ Comparator cYear = null; /** * A reference to a DateTimeComparator object * (a Comparator) for the date portion of an * object. */ Comparator cDate = null; /** * A reference to a DateTimeComparator object * (a Comparator) for the time portion of an * object. */ Comparator cTime = null; /** * Junit setUp() method. */ public void setUp() /* throws Exception */ { Chronology chrono = ISOChronology.getInstanceUTC(); // super.setUp(); // Obtain comparator's cMillis = DateTimeComparator.getInstance(null, DateTimeFieldType.secondOfMinute()); cSecond = DateTimeComparator.getInstance(DateTimeFieldType.secondOfMinute(), DateTimeFieldType.minuteOfHour()); cMinute = DateTimeComparator.getInstance(DateTimeFieldType.minuteOfHour(), DateTimeFieldType.hourOfDay()); cHour = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.dayOfYear()); cDayOfWeek = DateTimeComparator.getInstance(DateTimeFieldType.dayOfWeek(), DateTimeFieldType.weekOfWeekyear()); cDayOfMonth = DateTimeComparator.getInstance(DateTimeFieldType.dayOfMonth(), DateTimeFieldType.monthOfYear()); cDayOfYear = DateTimeComparator.getInstance(DateTimeFieldType.dayOfYear(), DateTimeFieldType.year()); cWeekOfWeekyear = DateTimeComparator.getInstance(DateTimeFieldType.weekOfWeekyear(), DateTimeFieldType.weekyear()); cWeekyear = DateTimeComparator.getInstance(DateTimeFieldType.weekyear()); cMonth = DateTimeComparator.getInstance(DateTimeFieldType.monthOfYear(), DateTimeFieldType.year()); cYear = DateTimeComparator.getInstance(DateTimeFieldType.year()); cDate = DateTimeComparator.getDateOnlyInstance(); cTime = DateTimeComparator.getTimeOnlyInstance(); } /** * Junit tearDown() method. */ protected void tearDown() /* throws Exception */ { // super.tearDown(); aDateTime = null; bDateTime = null; // cMillis = null; cSecond = null; cMinute = null; cHour = null; cDayOfWeek = null; cDayOfMonth = null; cDayOfYear = null; cWeekOfWeekyear = null; cWeekyear = null; cMonth = null; cYear = null; cDate = null; cTime = null; } //----------------------------------------------------------------------- public void testClass() { assertEquals(true, Modifier.isPublic(DateTimeComparator.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateTimeComparator.class.getModifiers())); assertEquals(1, DateTimeComparator.class.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(DateTimeComparator.class.getDeclaredConstructors()[0].getModifiers())); } //----------------------------------------------------------------------- public void testStaticGetInstance() { DateTimeComparator c = DateTimeComparator.getInstance(); assertEquals(null, c.getLowerLimit()); assertEquals(null, c.getUpperLimit()); assertEquals("DateTimeComparator[]", c.toString()); } public void testStaticGetDateOnlyInstance() { DateTimeComparator c = DateTimeComparator.getDateOnlyInstance(); assertEquals(DateTimeFieldType.dayOfYear(), c.getLowerLimit()); assertEquals(null, c.getUpperLimit()); assertEquals("DateTimeComparator[dayOfYear-]", c.toString()); assertSame(DateTimeComparator.getDateOnlyInstance(), DateTimeComparator.getDateOnlyInstance()); } public void testStaticGetTimeOnlyInstance() { DateTimeComparator c = DateTimeComparator.getTimeOnlyInstance(); assertEquals(null, c.getLowerLimit()); assertEquals(DateTimeFieldType.dayOfYear(), c.getUpperLimit()); assertEquals("DateTimeComparator[-dayOfYear]", c.toString()); assertSame(DateTimeComparator.getTimeOnlyInstance(), DateTimeComparator.getTimeOnlyInstance()); } public void testStaticGetInstanceLower() { DateTimeComparator c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay()); assertEquals(DateTimeFieldType.hourOfDay(), c.getLowerLimit()); assertEquals(null, c.getUpperLimit()); assertEquals("DateTimeComparator[hourOfDay-]", c.toString()); c = DateTimeComparator.getInstance(null); assertSame(DateTimeComparator.getInstance(), c); } public void testStaticGetInstanceLowerUpper() { DateTimeComparator c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.dayOfYear()); assertEquals(DateTimeFieldType.hourOfDay(), c.getLowerLimit()); assertEquals(DateTimeFieldType.dayOfYear(), c.getUpperLimit()); assertEquals("DateTimeComparator[hourOfDay-dayOfYear]", c.toString()); c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.hourOfDay()); assertEquals(DateTimeFieldType.hourOfDay(), c.getLowerLimit()); assertEquals(DateTimeFieldType.hourOfDay(), c.getUpperLimit()); assertEquals("DateTimeComparator[hourOfDay]", c.toString()); c = DateTimeComparator.getInstance(null, null); assertSame(DateTimeComparator.getInstance(), c); c = DateTimeComparator.getInstance(DateTimeFieldType.dayOfYear(), null); assertSame(DateTimeComparator.getDateOnlyInstance(), c); c = DateTimeComparator.getInstance(null, DateTimeFieldType.dayOfYear()); assertSame(DateTimeComparator.getTimeOnlyInstance(), c); } //----------------------------------------------------------------------- public void testEqualsHashCode() { DateTimeComparator c1 = DateTimeComparator.getInstance(); assertEquals(true, c1.equals(c1)); assertEquals(false, c1.equals(null)); assertEquals(true, c1.hashCode() == c1.hashCode()); DateTimeComparator c2 = DateTimeComparator.getTimeOnlyInstance(); assertEquals(true, c2.equals(c2)); assertEquals(false, c2.equals(c1)); assertEquals(false, c1.equals(c2)); assertEquals(false, c2.equals(null)); assertEquals(false, c1.hashCode() == c2.hashCode()); DateTimeComparator c3 = DateTimeComparator.getTimeOnlyInstance(); assertEquals(true, c3.equals(c3)); assertEquals(false, c3.equals(c1)); assertEquals(true, c3.equals(c2)); assertEquals(false, c1.equals(c3)); assertEquals(true, c2.equals(c3)); assertEquals(false, c1.hashCode() == c3.hashCode()); assertEquals(true, c2.hashCode() == c3.hashCode()); DateTimeComparator c4 = DateTimeComparator.getDateOnlyInstance(); assertEquals(false, c4.hashCode() == c3.hashCode()); } //----------------------------------------------------------------------- public void testSerialization1() throws Exception { DateTimeField f = ISO.dayOfYear(); f.toString(); DateTimeComparator c = DateTimeComparator.getInstance(DateTimeFieldType.hourOfDay(), DateTimeFieldType.dayOfYear()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(c); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeComparator result = (DateTimeComparator) ois.readObject(); ois.close(); assertEquals(c, result); } //----------------------------------------------------------------------- public void testSerialization2() throws Exception { DateTimeComparator c = DateTimeComparator.getInstance(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(c); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeComparator result = (DateTimeComparator) ois.readObject(); ois.close(); assertSame(c, result); } //----------------------------------------------------------------------- /** * Test all basic comparator operation with DateTime objects. */ public void testBasicComps1() { aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); bDateTime = new DateTime( aDateTime.getMillis(), DateTimeZone.UTC ); assertEquals( "getMillis", aDateTime.getMillis(), bDateTime.getMillis() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with ReadableInstant objects. */ public void testBasicComps2() { ReadableInstant aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); ReadableInstant bDateTime = new DateTime( aDateTime.getMillis(), DateTimeZone.UTC ); assertEquals( "getMillis", aDateTime.getMillis(), bDateTime.getMillis() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with java Date objects. */ public void testBasicComps3() { Date aDateTime = new Date( System.currentTimeMillis() ); Date bDateTime = new Date( aDateTime.getTime() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with Long objects. */ public void testBasicComps4() { Long aDateTime = new Long( System.currentTimeMillis() ); Long bDateTime = new Long( aDateTime.longValue() ); assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test all basic comparator operation with Calendar objects. */ public void testBasicComps5() { Calendar aDateTime = Calendar.getInstance(); // right now Calendar bDateTime = aDateTime; assertEquals( "MILLIS", 0, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "SECOND", 0, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "MINUTE", 0, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "HOUR", 0, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "DOW", 0, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOM", 0, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOY", 0, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "WOW", 0, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WY", 0, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "MONTH", 0, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "YEAR", 0, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "DATE", 0, cDate.compare( aDateTime, bDateTime ) ); assertEquals( "TIME", 0, cTime.compare( aDateTime, bDateTime ) ); } // end of testBasicComps /** * Test unequal comparisons with millis of second comparators. */ public void testMillis() { aDateTime = new DateTime( System.currentTimeMillis(), DateTimeZone.UTC ); bDateTime = new DateTime( aDateTime.getMillis() + 1, DateTimeZone.UTC ); assertEquals( "MillisM1", -1, cMillis.compare( aDateTime, bDateTime ) ); assertEquals( "MillisP1", 1, cMillis.compare( bDateTime, aDateTime ) ); } // end of testMillis /** * Test unequal comparisons with second comparators. */ public void testSecond() { aDateTime = getADate( "1969-12-31T23:59:58" ); bDateTime = getADate( "1969-12-31T23:50:59" ); assertEquals( "SecondM1a", -1, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "SecondP1a", 1, cSecond.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1970-01-01T00:00:00" ); bDateTime = getADate( "1970-01-01T00:00:01" ); assertEquals( "SecondM1b", -1, cSecond.compare( aDateTime, bDateTime ) ); assertEquals( "SecondP1b", 1, cSecond.compare( bDateTime, aDateTime ) ); } // end of testSecond /** * Test unequal comparisons with minute comparators. */ public void testMinute() { aDateTime = getADate( "1969-12-31T23:58:00" ); bDateTime = getADate( "1969-12-31T23:59:00" ); assertEquals( "MinuteM1a", -1, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "MinuteP1a", 1, cMinute.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1970-01-01T00:00:00" ); bDateTime = getADate( "1970-01-01T00:01:00" ); assertEquals( "MinuteM1b", -1, cMinute.compare( aDateTime, bDateTime ) ); assertEquals( "MinuteP1b", 1, cMinute.compare( bDateTime, aDateTime ) ); } // end of testMinute /** * Test unequal comparisons with hour comparators. */ public void testHour() { aDateTime = getADate( "1969-12-31T22:00:00" ); bDateTime = getADate( "1969-12-31T23:00:00" ); assertEquals( "HourM1a", -1, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "HourP1a", 1, cHour.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1970-01-01T00:00:00" ); bDateTime = getADate( "1970-01-01T01:00:00" ); assertEquals( "HourM1b", -1, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "HourP1b", 1, cHour.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1969-12-31T23:59:59" ); bDateTime = getADate( "1970-01-01T00:00:00" ); assertEquals( "HourP1c", 1, cHour.compare( aDateTime, bDateTime ) ); assertEquals( "HourM1c", -1, cHour.compare( bDateTime, aDateTime ) ); } // end of testHour /** * Test unequal comparisons with day of week comparators. */ public void testDOW() { /* * Dates chosen when I wrote the code, so I know what day of * the week it is. */ aDateTime = getADate( "2002-04-12T00:00:00" ); bDateTime = getADate( "2002-04-13T00:00:00" ); assertEquals( "DOWM1a", -1, cDayOfWeek.compare( aDateTime, bDateTime ) ); assertEquals( "DOWP1a", 1, cDayOfWeek.compare( bDateTime, aDateTime ) ); } // end of testDOW /** * Test unequal comparisons with day of month comparators. */ public void testDOM() { aDateTime = getADate( "2002-04-12T00:00:00" ); bDateTime = getADate( "2002-04-13T00:00:00" ); assertEquals( "DOMM1a", -1, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOMP1a", 1, cDayOfMonth.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "2000-12-01T00:00:00" ); bDateTime = getADate( "1814-04-30T00:00:00" ); assertEquals( "DOMM1b", -1, cDayOfMonth.compare( aDateTime, bDateTime ) ); assertEquals( "DOMP1b", 1, cDayOfMonth.compare( bDateTime, aDateTime ) ); } // end of testDOM /** * Test unequal comparisons with day of year comparators. */ public void testDOY() { aDateTime = getADate( "2002-04-12T00:00:00" ); bDateTime = getADate( "2002-04-13T00:00:00" ); assertEquals( "DOYM1a", -1, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "DOYP1a", 1, cDayOfYear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "2000-02-29T00:00:00" ); bDateTime = getADate( "1814-11-30T00:00:00" ); assertEquals( "DOYM1b", -1, cDayOfYear.compare( aDateTime, bDateTime ) ); assertEquals( "DOYP1b", 1, cDayOfYear.compare( bDateTime, aDateTime ) ); } // end of testDOY /** * Test unequal comparisons with week of weekyear comparators. */ public void testWOW() { // 1st week of year contains Jan 04. aDateTime = getADate( "2000-01-04T00:00:00" ); bDateTime = getADate( "2000-01-11T00:00:00" ); assertEquals( "WOWM1a", -1, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WOWP1a", 1, cWeekOfWeekyear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "2000-01-04T00:00:00" ); bDateTime = getADate( "1999-12-31T00:00:00" ); assertEquals( "WOWM1b", -1, cWeekOfWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "WOWP1b", 1, cWeekOfWeekyear.compare( bDateTime, aDateTime ) ); } // end of testMillis /** * Test unequal comparisons with year given the week comparators. */ public void testWOYY() { // How do I test the end conditions of this? // Don't understand ...... aDateTime = getADate( "1998-12-31T23:59:59" ); bDateTime = getADate( "1999-01-01T00:00:00" ); assertEquals( "YOYYZ", 0, cWeekyear.compare( aDateTime, bDateTime ) ); bDateTime = getADate( "1999-01-04T00:00:00" ); assertEquals( "YOYYM1", -1, cWeekyear.compare( aDateTime, bDateTime ) ); assertEquals( "YOYYP1", 1, cWeekyear.compare( bDateTime, aDateTime ) ); } // end of testWOYY /** * Test unequal comparisons with month comparators. */ public void testMonth() { aDateTime = getADate( "2002-04-30T00:00:00" ); bDateTime = getADate( "2002-05-01T00:00:00" ); assertEquals( "MONTHM1a", -1, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "MONTHP1a", 1, cMonth.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1900-01-01T00:00:00" ); bDateTime = getADate( "1899-12-31T00:00:00" ); assertEquals( "MONTHM1b", -1, cMonth.compare( aDateTime, bDateTime ) ); assertEquals( "MONTHP1b", 1, cMonth.compare( bDateTime, aDateTime ) ); } // end of testMonth /** * Test unequal comparisons with year comparators. */ public void testYear() { aDateTime = getADate( "2000-01-01T00:00:00" ); bDateTime = getADate( "2001-01-01T00:00:00" ); assertEquals( "YEARM1a", -1, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "YEARP1a", 1, cYear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1968-12-31T23:59:59" ); bDateTime = getADate( "1970-01-01T00:00:00" ); assertEquals( "YEARM1b", -1, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "YEARP1b", 1, cYear.compare( bDateTime, aDateTime ) ); aDateTime = getADate( "1969-12-31T23:59:59" ); bDateTime = getADate( "1970-01-01T00:00:00" ); assertEquals( "YEARM1c", -1, cYear.compare( aDateTime, bDateTime ) ); assertEquals( "YEARP1c", 1, cYear.compare( bDateTime, aDateTime ) ); } // end of testYear /* * 'List' processing tests follow. */ /** * Test sorting with full default comparator. */ public void testListBasic() { String[] dtStrs = { "1999-02-01T00:00:00", "1998-01-20T00:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListBasic", !isSorted1, isSorted2); } // end of testListBasic /** * Test sorting with millis of second comparator. */ public void testListMillis() { // List sl = new ArrayList(); long base = 12345L * 1000L; sl.add( new DateTime( base + 999L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 222L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 456L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 888L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 123L, DateTimeZone.UTC ) ); sl.add( new DateTime( base + 000L, DateTimeZone.UTC ) ); // boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cMillis ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListLillis", !isSorted1, isSorted2); } // end of testListSecond /** * Test sorting with second comparator. */ public void testListSecond() { String[] dtStrs = { "1999-02-01T00:00:10", "1999-02-01T00:00:30", "1999-02-01T00:00:25", "1999-02-01T00:00:18", "1999-02-01T00:00:01", "1999-02-01T00:00:59", "1999-02-01T00:00:22" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cSecond ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListSecond", !isSorted1, isSorted2); } // end of testListSecond /** * Test sorting with minute comparator. */ public void testListMinute() { String[] dtStrs = { "1999-02-01T00:10:00", "1999-02-01T00:30:00", "1999-02-01T00:25:00", "1999-02-01T00:18:00", "1999-02-01T00:01:00", "1999-02-01T00:59:00", "1999-02-01T00:22:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cMinute ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListMinute", !isSorted1, isSorted2); } // end of testListMinute /** * Test sorting with hour comparator. */ public void testListHour() { String[] dtStrs = { "1999-02-01T10:00:00", "1999-02-01T23:00:00", "1999-02-01T01:00:00", "1999-02-01T15:00:00", "1999-02-01T05:00:00", "1999-02-01T20:00:00", "1999-02-01T17:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cHour ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListHour", !isSorted1, isSorted2); } // end of testListHour /** * Test sorting with day of week comparator. */ public void testListDOW() { String[] dtStrs = { /* 2002-04-15 = Monday */ "2002-04-21T10:00:00", "2002-04-16T10:00:00", "2002-04-15T10:00:00", "2002-04-17T10:00:00", "2002-04-19T10:00:00", "2002-04-18T10:00:00", "2002-04-20T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDayOfWeek ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDOW", !isSorted1, isSorted2); } // end of testListDOW /** * Test sorting with day of month comparator. */ public void testListDOM() { String[] dtStrs = { /* 2002-04-14 = Sunday */ "2002-04-20T10:00:00", "2002-04-16T10:00:00", "2002-04-15T10:00:00", "2002-04-17T10:00:00", "2002-04-19T10:00:00", "2002-04-18T10:00:00", "2002-04-14T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDayOfMonth ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDOM", !isSorted1, isSorted2); } // end of testListDOM /** * Test sorting with day of year comparator. */ public void testListDOY() { String[] dtStrs = { "2002-04-20T10:00:00", "2002-01-16T10:00:00", "2002-12-31T10:00:00", "2002-09-14T10:00:00", "2002-09-19T10:00:00", "2002-02-14T10:00:00", "2002-10-30T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDayOfYear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDOY", !isSorted1, isSorted2); } // end of testListDOY /** * Test sorting with week of weekyear comparator. */ public void testListWOW() { String[] dtStrs = { "2002-04-01T10:00:00", "2002-01-01T10:00:00", "2002-12-01T10:00:00", "2002-09-01T10:00:00", "2002-09-01T10:00:00", "2002-02-01T10:00:00", "2002-10-01T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cWeekOfWeekyear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListWOW", !isSorted1, isSorted2); } // end of testListWOW /** * Test sorting with year (given week) comparator. */ public void testListYOYY() { // ?? How to catch end conditions ?? String[] dtStrs = { "2010-04-01T10:00:00", "2002-01-01T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cWeekyear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListYOYY", !isSorted1, isSorted2); } // end of testListYOYY /** * Test sorting with month comparator. */ public void testListMonth() { String[] dtStrs = { "2002-04-01T10:00:00", "2002-01-01T10:00:00", "2002-12-01T10:00:00", "2002-09-01T10:00:00", "2002-09-01T10:00:00", "2002-02-01T10:00:00", "2002-10-01T10:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cMonth ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListMonth", !isSorted1, isSorted2); } // end of testListMonth /** * Test sorting with year comparator. */ public void testListYear() { String[] dtStrs = { "1999-02-01T00:00:00", "1998-02-01T00:00:00", "2525-02-01T00:00:00", "1776-02-01T00:00:00", "1863-02-01T00:00:00", "1066-02-01T00:00:00", "2100-02-01T00:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cYear ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListYear", !isSorted1, isSorted2); } // end of testListYear /** * Test sorting with date only comparator. */ public void testListDate() { String[] dtStrs = { "1999-02-01T00:00:00", "1998-10-03T00:00:00", "2525-05-20T00:00:00", "1776-12-25T00:00:00", "1863-01-31T00:00:00", "1066-09-22T00:00:00", "2100-07-04T00:00:00" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cDate ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListDate", !isSorted1, isSorted2); } // end of testListDate /** * Test sorting with time only comparator. */ public void testListTime() { String[] dtStrs = { "1999-02-01T01:02:05", "1999-02-01T22:22:22", "1999-02-01T05:30:45", "1999-02-01T09:17:59", "1999-02-01T09:17:58", "1999-02-01T15:30:00", "1999-02-01T17:00:44" }; // List sl = loadAList( dtStrs ); boolean isSorted1 = isListSorted( sl ); Collections.sort( sl, cTime ); boolean isSorted2 = isListSorted( sl ); assertEquals("ListTime", !isSorted1, isSorted2); } // end of testListTime /** * Test comparator operation with null object(s). */ public void testNullDT() { // null means now aDateTime = getADate("2000-01-01T00:00:00"); assertTrue(cYear.compare(null, aDateTime) > 0); assertTrue(cYear.compare(aDateTime, null) < 0); } /** * Test comparator operation with an invalid object type. */ public void testInvalidObj() { aDateTime = getADate("2000-01-01T00:00:00"); try { cYear.compare("FreeBird", aDateTime); fail("Invalid object failed"); } catch (IllegalArgumentException cce) {} } // private convenience methods //----------------------------------------------------------------------- /** * Creates a date to test with. */ private DateTime getADate(String s) { DateTime retDT = null; try { retDT = new DateTime(s, DateTimeZone.UTC); } catch (IllegalArgumentException pe) { pe.printStackTrace(); } return retDT; } /** * Load a string array. */ private List loadAList(String[] someStrs) { List newList = new ArrayList(); try { for (int i = 0; i < someStrs.length; ++i) { newList.add(new DateTime(someStrs[i], DateTimeZone.UTC)); } // end of the for } catch (IllegalArgumentException pe) { pe.printStackTrace(); } return newList; } /** * Check if the list is sorted. */ private boolean isListSorted(List tl) { // tl must be populated with DateTime objects. DateTime lhDT = (DateTime)tl.get(0); DateTime rhDT = null; Long lhVal = new Long( lhDT.getMillis() ); Long rhVal = null; for (int i = 1; i < tl.size(); ++i) { rhDT = (DateTime)tl.get(i); rhVal = new Long( rhDT.getMillis() ); if ( lhVal.compareTo( rhVal) > 0 ) return false; // lhVal = rhVal; // swap for next iteration lhDT = rhDT; // swap for next iteration } return true; } } joda-time-2.3/src/test/java/org/joda/time/TestPeriod_Constructors.java0000644000175000017500000020531612200501234025421 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a JUnit test for Duration. * * @author Stephen Colebourne */ public class TestPeriod_Constructors extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPeriod_Constructors.class); } public TestPeriod_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testConstants() throws Throwable { Period test = Period.ZERO; assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 890), Period.parse("P1Y2M3W4DT5H6M7.890S")); } //----------------------------------------------------------------------- public void testConstructor1() throws Throwable { Period test = new Period(); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long2() throws Throwable { long length = 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long3() throws Throwable { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Period test = new Period(length); assertEquals(PeriodType.standard(), test.getPeriodType()); // only time fields are precise in AllType assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_fixedZone() throws Throwable { DateTimeZone zone = DateTimeZone.getDefault(); try { DateTimeZone.setDefault(DateTimeZone.forOffsetHours(2)); long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Period test = new Period(length); assertEquals(PeriodType.standard(), test.getPeriodType()); // only time fields are precise in AllType assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } finally { DateTimeZone.setDefault(zone); } } //----------------------------------------------------------------------- public void testConstructor_long_PeriodType1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, (PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType2() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, PeriodType.millis()); assertEquals(PeriodType.millis(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(length, test.getMillis()); } public void testConstructor_long_PeriodType3() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, PeriodType.dayTime()); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType4() throws Throwable { long length = 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, PeriodType.standard().withMillisRemoved()); assertEquals(PeriodType.standard().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_Chronology1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, ISOChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_Chronology2() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, ISOChronology.getInstanceUTC()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_Chronology3() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_PeriodType_Chronology1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, PeriodType.time().withMillisRemoved(), ISOChronology.getInstance()); assertEquals(PeriodType.time().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_long_PeriodType_Chronology2() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, PeriodType.standard(), ISOChronology.getInstanceUTC()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType_Chronology3() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, PeriodType.standard(), (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType_Chronology4() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, (PeriodType) null, (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (4ints) */ public void testConstructor_4int1() throws Throwable { Period test = new Period(5, 6, 7, 8); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (8ints) */ public void testConstructor_8int1() throws Throwable { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (8ints) */ public void testConstructor_8int__PeriodType1() throws Throwable { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_8int__PeriodType2() throws Throwable { Period test = new Period(0, 0, 0, 0, 5, 6, 7, 8, PeriodType.dayTime()); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_8int__PeriodType3() throws Throwable { try { new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.dayTime()); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_long_long1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1.getMillis(), dt2.getMillis()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); Period test = new Period(dt1.getMillis(), dt2.getMillis()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_long_PeriodType1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1.getMillis(), dt2.getMillis(), (PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_PeriodType2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1.getMillis(), dt2.getMillis(), PeriodType.dayTime()); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(31, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_PeriodType3() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 6, 9, 1, 1, 1, 1); Period test = new Period(dt1.getMillis(), dt2.getMillis(), PeriodType.standard().withMillisRemoved()); assertEquals(PeriodType.standard().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testToPeriod_PeriodType3() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10); DateTime dt2 = new DateTime(2005, 6, 9, 12, 14, 16, 18); Period test = new Period(dt1.getMillis(), dt2.getMillis(), PeriodType.yearWeekDayTime()); assertEquals(PeriodType.yearWeekDayTime(), test.getPeriodType()); assertEquals(1, test.getYears()); // tests using years and not weekyears assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_long_Chronology1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0, CopticChronology.getInstance()); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1, CopticChronology.getInstance()); Period test = new Period(dt1.getMillis(), dt2.getMillis(), CopticChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_Chronology2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1.getMillis(), dt2.getMillis(), (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_long_PeriodType_Chronology1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0, CopticChronology.getInstance()); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1, CopticChronology.getInstance()); Period test = new Period(dt1.getMillis(), dt2.getMillis(), (PeriodType) null, CopticChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_PeriodType_Chronology2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1.getMillis(), dt2.getMillis(), (PeriodType) null, null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RI_RI1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI3() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(3, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI4() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 17, 1, 1, 1, 1); DateTime dt2 = null; // 2002-06-09T01:00+01:00 Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(-3, test.getYears()); assertEquals(-1, test.getMonths()); assertEquals(-1, test.getWeeks()); assertEquals(-1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(-1, test.getMinutes()); assertEquals(-1, test.getSeconds()); assertEquals(-1, test.getMillis()); } public void testConstructor_RI_RI5() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = null; // 2002-06-09T01:00+01:00 Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RI_RI_PeriodType1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1, dt2, null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI_PeriodType2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 7, 10, 1, 1, 1, 1); Period test = new Period(dt1, dt2, PeriodType.dayTime()); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(31, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI_PeriodType3() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 6, 9, 1, 1, 1, 1); Period test = new Period(dt1, dt2, PeriodType.standard().withMillisRemoved()); assertEquals(PeriodType.standard().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_RI_RI_PeriodType4() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); Period test = new Period(dt1, dt2, PeriodType.standard()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(3, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI_PeriodType5() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = null; // 2002-06-09T01:00+01:00 Period test = new Period(dt1, dt2, PeriodType.standard()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testConstructor_RP_RP1() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2004, 6, 9); YearMonthDay dt2 = new YearMonthDay(2005, 7, 10); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } @SuppressWarnings("deprecation") public void testConstructor_RP_RP2() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2004, 6, 9); YearMonthDay dt2 = new YearMonthDay(2005, 5, 17); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(11, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_RP_RP2Local() throws Throwable { LocalDate dt1 = new LocalDate(2004, 6, 9); LocalDate dt2 = new LocalDate(2005, 5, 17); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(11, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } @SuppressWarnings("deprecation") public void testConstructor_RP_RP3() throws Throwable { YearMonthDay dt1 = null; YearMonthDay dt2 = new YearMonthDay(2005, 7, 17); try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testConstructor_RP_RP4() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2005, 7, 17); YearMonthDay dt2 = null; try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testConstructor_RP_RP5() throws Throwable { YearMonthDay dt1 = null; YearMonthDay dt2 = null; try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testConstructor_RP_RP6() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2005, 7, 17); TimeOfDay dt2 = new TimeOfDay(10, 20, 30, 40); try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_RP_RP7() throws Throwable { Partial dt1 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.monthOfYear(), 12); Partial dt2 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.hourOfDay(), 14); try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_RP_RP8() throws Throwable { Partial dt1 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.hourOfDay(), 12); Partial dt2 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.hourOfDay(), 14); try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testConstructor_RP_RP_PeriodType1() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2004, 6, 9); YearMonthDay dt2 = new YearMonthDay(2005, 7, 10); Period test = new Period(dt1, dt2, PeriodType.standard()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } @SuppressWarnings("deprecation") public void testConstructor_RP_RP_PeriodType2() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2004, 6, 9); YearMonthDay dt2 = new YearMonthDay(2005, 5, 17); Period test = new Period(dt1, dt2, PeriodType.yearMonthDay()); assertEquals(PeriodType.yearMonthDay(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(11, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(8, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_RP_RP_PeriodType2Local() throws Throwable { LocalDate dt1 = new LocalDate(2004, 6, 9); LocalDate dt2 = new LocalDate(2005, 5, 17); Period test = new Period(dt1, dt2, PeriodType.yearMonthDay()); assertEquals(PeriodType.yearMonthDay(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(11, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(8, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } @SuppressWarnings("deprecation") public void testConstructor_RP_RP_PeriodType3() throws Throwable { YearMonthDay dt1 = null; YearMonthDay dt2 = new YearMonthDay(2005, 7, 17); try { new Period(dt1, dt2, PeriodType.standard()); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testConstructor_RP_RP_PeriodType4() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2005, 7, 17); YearMonthDay dt2 = null; try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testConstructor_RP_RP_PeriodType5() throws Throwable { YearMonthDay dt1 = null; YearMonthDay dt2 = null; try { new Period(dt1, dt2, PeriodType.standard()); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testConstructor_RP_RP_PeriodType6() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2005, 7, 17); TimeOfDay dt2 = new TimeOfDay(10, 20, 30, 40); try { new Period(dt1, dt2, PeriodType.standard()); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_RP_RP_PeriodType7() throws Throwable { Partial dt1 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.monthOfYear(), 12); Partial dt2 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.hourOfDay(), 14); try { new Period(dt1, dt2, PeriodType.standard()); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_RP_RP_PeriodType8() throws Throwable { Partial dt1 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.hourOfDay(), 12); Partial dt2 = new Partial().with(DateTimeFieldType.year(), 2005).with(DateTimeFieldType.hourOfDay(), 14); try { new Period(dt1, dt2, PeriodType.standard()); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_RI_RD1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Duration dur = new Interval(dt1, dt2).toDuration(); Period test = new Period(dt1, dur); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RD2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Duration dur = null; Period test = new Period(dt1, dur); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RI_RD_PeriodType1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Duration dur = new Interval(dt1, dt2).toDuration(); Period test = new Period(dt1, dur, PeriodType.yearDayTime()); assertEquals(PeriodType.yearDayTime(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(31, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RD_PeriodType2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Duration dur = null; Period test = new Period(dt1, dur, (PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RD_RI1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Duration dur = new Interval(dt1, dt2).toDuration(); Period test = new Period(dur, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RD_RI2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Duration dur = null; Period test = new Period(dur, dt1); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RD_RI_PeriodType1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Duration dur = new Interval(dt1, dt2).toDuration(); Period test = new Period(dur, dt2, PeriodType.yearDayTime()); assertEquals(PeriodType.yearDayTime(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(31, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RD_RI_PeriodType2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Duration dur = null; Period test = new Period(dur, dt1, (PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (Object) */ public void testConstructor_Object1() throws Throwable { Period test = new Period("P1Y2M3D"); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(3, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object2() throws Throwable { Period test = new Period((Object) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object3() throws Throwable { Period test = new Period(new Period(0, 0, 0, 0, 1, 2, 3, 4, PeriodType.dayTime())); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(2, test.getMinutes()); assertEquals(3, test.getSeconds()); assertEquals(4, test.getMillis()); } public void testConstructor_Object4() throws Throwable { Period base = new Period(1, 1, 0, 1, 1, 1, 1, 1, PeriodType.standard()); Period test = new Period(base); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (Object) */ public void testConstructor_Object_PeriodType1() throws Throwable { Period test = new Period("P1Y2M3D", PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(3, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object_PeriodType2() throws Throwable { Period test = new Period((Object) null, PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object_PeriodType3() throws Throwable { Period test = new Period(new Period(0, 0, 0, 0, 1, 2, 3, 4, PeriodType.dayTime()), PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(2, test.getMinutes()); assertEquals(3, test.getSeconds()); assertEquals(4, test.getMillis()); } public void testConstructor_Object_PeriodType4() throws Throwable { Period test = new Period(new Period(0, 0, 0, 0, 1, 2, 3, 4, PeriodType.dayTime()), (PeriodType) null); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(2, test.getMinutes()); assertEquals(3, test.getSeconds()); assertEquals(4, test.getMillis()); } //----------------------------------------------------------------------- public void testFactoryYears() throws Throwable { Period test = Period.years(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(6, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testFactoryMonths() throws Throwable { Period test = Period.months(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(6, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testFactoryWeeks() throws Throwable { Period test = Period.weeks(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(6, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testFactoryDays() throws Throwable { Period test = Period.days(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(6, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testFactoryHours() throws Throwable { Period test = Period.hours(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(6, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testFactoryMinutes() throws Throwable { Period test = Period.minutes(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testFactorySeconds() throws Throwable { Period test = Period.seconds(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(6, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testFactoryMillis() throws Throwable { Period test = Period.millis(6); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(6, test.getMillis()); } //------------------------------------------------------------------------- public void testConstructor_trickyDifferences_RI_RI_toFeb_standardYear() throws Throwable { DateTime dt1 = new DateTime(2011, 1, 1, 0, 0); DateTime dt2 = new DateTime(2011, 2, 28, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 1, 3, 6, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_RI_RI_toFeb_leapYear() throws Throwable { DateTime dt1 = new DateTime(2012, 1, 1, 0, 0); DateTime dt2 = new DateTime(2012, 2, 29, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 1, 4, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_RI_RI_toFeb_exactMonths() throws Throwable { DateTime dt1 = new DateTime(2004, 12, 28, 0, 0); DateTime dt2 = new DateTime(2005, 2, 28, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_RI_RI_toFeb_endOfMonth1() throws Throwable { DateTime dt1 = new DateTime(2004, 12, 29, 0, 0); DateTime dt2 = new DateTime(2005, 2, 28, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_RI_RI_toFeb_endOfMonth2() throws Throwable { DateTime dt1 = new DateTime(2004, 12, 30, 0, 0); DateTime dt2 = new DateTime(2005, 2, 28, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_RI_RI_toFeb_endOfMonth3() throws Throwable { DateTime dt1 = new DateTime(2004, 12, 31, 0, 0); DateTime dt2 = new DateTime(2005, 2, 28, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_RI_RI_toMar_endOfMonth1() throws Throwable { DateTime dt1 = new DateTime(2013, 1, 31, 0, 0); DateTime dt2 = new DateTime(2013, 3, 30, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 1, 4, 2, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_RI_RI_toMar_endOfMonth2() throws Throwable { DateTime dt1 = new DateTime(2013, 1, 31, 0, 0); DateTime dt2 = new DateTime(2013, 3, 31, 0, 0); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } //------------------------------------------------------------------------- public void testConstructor_trickyDifferences_LD_LD_toFeb_standardYear() throws Throwable { LocalDate dt1 = new LocalDate(2011, 1, 1); LocalDate dt2 = new LocalDate(2011, 2, 28); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 1, 3, 6, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_LD_LD_toFeb_leapYear() throws Throwable { LocalDate dt1 = new LocalDate(2012, 1, 1); LocalDate dt2 = new LocalDate(2012, 2, 29); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 1, 4, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_LD_LD_toFeb_exactMonths() throws Throwable { LocalDate dt1 = new LocalDate(2004, 12, 28); LocalDate dt2 = new LocalDate(2005, 2, 28); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_LD_LD_toFeb_endOfMonth1() throws Throwable { LocalDate dt1 = new LocalDate(2004, 12, 29); LocalDate dt2 = new LocalDate(2005, 2, 28); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_LD_LD_toFeb_endOfMonth2() throws Throwable { LocalDate dt1 = new LocalDate(2004, 12, 30); LocalDate dt2 = new LocalDate(2005, 2, 28); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_LD_LD_toFeb_endOfMonth3() throws Throwable { LocalDate dt1 = new LocalDate(2004, 12, 31); LocalDate dt2 = new LocalDate(2005, 2, 28); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_LD_LD_toMar_endOfMonth1() throws Throwable { LocalDate dt1 = new LocalDate(2013, 1, 31); LocalDate dt2 = new LocalDate(2013, 3, 30); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 1, 4, 2, 0, 0, 0, 0), test); } public void testConstructor_trickyDifferences_LD_LD_toMar_endOfMonth2() throws Throwable { LocalDate dt1 = new LocalDate(2013, 1, 31); LocalDate dt2 = new LocalDate(2013, 3, 31); Period test = new Period(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0), test); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testFactoryFieldDifference1() throws Throwable { YearMonthDay start = new YearMonthDay(2005, 4, 9); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth(), }; Partial end = new Partial(types, new int[] {2004, 6, 7}); Period test = Period.fieldDifference(start, end); assertEquals(PeriodType.yearMonthDay(), test.getPeriodType()); assertEquals(-1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(-2, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } @SuppressWarnings("deprecation") public void testFactoryFieldDifference2() throws Throwable { YearMonthDay ymd = new YearMonthDay(2005, 4, 9); try { Period.fieldDifference(ymd, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} try { Period.fieldDifference((ReadablePartial) null, ymd); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testFactoryFieldDifference3() throws Throwable { YearMonthDay start = new YearMonthDay(2005, 4, 9); TimeOfDay endTime = new TimeOfDay(12, 30, 40, 0); try { Period.fieldDifference(start, endTime); fail(); } catch (IllegalArgumentException ex) {} } @SuppressWarnings("deprecation") public void testFactoryFieldDifference4() throws Throwable { DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfWeek(), }; YearMonthDay start = new YearMonthDay(2005, 4, 9); Partial end = new Partial(types, new int[] {1, 2, 3}); try { Period.fieldDifference(start, end); fail(); } catch (IllegalArgumentException ex) {} } public void testFactoryFieldDifference5() throws Throwable { DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.dayOfMonth(), DateTimeFieldType.dayOfWeek(), }; Partial start = new Partial(types, new int[] {1, 2, 3}); Partial end = new Partial(types, new int[] {1, 2, 3}); try { Period.fieldDifference(start, end); fail(); } catch (IllegalArgumentException ex) {} } } joda-time-2.3/src/test/java/org/joda/time/TestIllegalFieldValueException.java0000644000175000017500000003606612200501234026604 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; import org.joda.time.field.FieldUtils; import org.joda.time.field.SkipDateTimeField; /** * Tests IllegalFieldValueException by triggering it from other methods. * * @author Brian S O'Neill */ public class TestIllegalFieldValueException extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestIllegalFieldValueException.class); } public TestIllegalFieldValueException(String name) { super(name); } public void testVerifyValueBounds() { try { FieldUtils.verifyValueBounds(ISOChronology.getInstance().monthOfYear(), -5, 1, 31); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.monthOfYear(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("monthOfYear", e.getFieldName()); assertEquals(new Integer(-5), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("-5", e.getIllegalValueAsString()); assertEquals(new Integer(1), e.getLowerBound()); assertEquals(new Integer(31), e.getUpperBound()); } try { FieldUtils.verifyValueBounds(DateTimeFieldType.hourOfDay(), 27, 0, 23); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.hourOfDay(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("hourOfDay", e.getFieldName()); assertEquals(new Integer(27), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("27", e.getIllegalValueAsString()); assertEquals(new Integer(0), e.getLowerBound()); assertEquals(new Integer(23), e.getUpperBound()); } try { FieldUtils.verifyValueBounds("foo", 1, 2, 3); fail(); } catch (IllegalFieldValueException e) { assertEquals(null, e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("foo", e.getFieldName()); assertEquals(new Integer(1), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("1", e.getIllegalValueAsString()); assertEquals(new Integer(2), e.getLowerBound()); assertEquals(new Integer(3), e.getUpperBound()); } } public void testSkipDateTimeField() { DateTimeField field = new SkipDateTimeField (ISOChronology.getInstanceUTC(), ISOChronology.getInstanceUTC().year(), 1970); try { field.set(0, 1970); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.year(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("year", e.getFieldName()); assertEquals(new Integer(1970), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("1970", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } } public void testSetText() { try { ISOChronology.getInstanceUTC().year().set(0, null, java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.year(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("year", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("null", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().year().set(0, "nineteen seventy", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.year(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("year", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("nineteen seventy", e.getIllegalStringValue()); assertEquals("nineteen seventy", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().era().set(0, "long ago", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.era(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("era", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("long ago", e.getIllegalStringValue()); assertEquals("long ago", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().monthOfYear().set(0, "spring", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.monthOfYear(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("monthOfYear", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("spring", e.getIllegalStringValue()); assertEquals("spring", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().dayOfWeek().set(0, "yesterday", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.dayOfWeek(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("dayOfWeek", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("yesterday", e.getIllegalStringValue()); assertEquals("yesterday", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().halfdayOfDay().set(0, "morning", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.halfdayOfDay(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("halfdayOfDay", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("morning", e.getIllegalStringValue()); assertEquals("morning", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } } public void testZoneTransition() { DateTime dt = new DateTime (2005, 4, 3, 1, 0, 0, 0, DateTimeZone.forID("America/Los_Angeles")); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.hourOfDay(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("hourOfDay", e.getFieldName()); assertEquals(new Integer(2), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("2", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } } public void testJulianYearZero() { DateTime dt = new DateTime(JulianChronology.getInstanceUTC()); try { dt.year().setCopy(0); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.year(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("year", e.getFieldName()); assertEquals(new Integer(0), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("0", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } } public void testGJCutover() { DateTime dt = new DateTime("1582-10-04", GJChronology.getInstanceUTC()); try { dt.dayOfMonth().setCopy(5); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.dayOfMonth(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("dayOfMonth", e.getFieldName()); assertEquals(new Integer(5), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("5", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } dt = new DateTime("1582-10-15", GJChronology.getInstanceUTC()); try { dt.dayOfMonth().setCopy(14); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.dayOfMonth(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("dayOfMonth", e.getFieldName()); assertEquals(new Integer(14), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("14", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } } @SuppressWarnings("deprecation") public void testReadablePartialValidate() { try { new YearMonthDay(1970, -5, 1); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.monthOfYear(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("monthOfYear", e.getFieldName()); assertEquals(new Integer(-5), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("-5", e.getIllegalValueAsString()); assertEquals(new Integer(1), e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { new YearMonthDay(1970, 500, 1); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.monthOfYear(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("monthOfYear", e.getFieldName()); assertEquals(new Integer(500), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("500", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(new Integer(12), e.getUpperBound()); } try { new YearMonthDay(1970, 2, 30); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.dayOfMonth(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("dayOfMonth", e.getFieldName()); assertEquals(new Integer(30), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("30", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(new Integer(28), e.getUpperBound()); } } // Test extra constructors not currently called by anything public void testOtherConstructors() { IllegalFieldValueException e = new IllegalFieldValueException (DurationFieldType.days(), new Integer(1), new Integer(2), new Integer(3)); assertEquals(null, e.getDateTimeFieldType()); assertEquals(DurationFieldType.days(), e.getDurationFieldType()); assertEquals("days", e.getFieldName()); assertEquals(new Integer(1), e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("1", e.getIllegalValueAsString()); assertEquals(new Integer(2), e.getLowerBound()); assertEquals(new Integer(3), e.getUpperBound()); e = new IllegalFieldValueException(DurationFieldType.months(), "five"); assertEquals(null, e.getDateTimeFieldType()); assertEquals(DurationFieldType.months(), e.getDurationFieldType()); assertEquals("months", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("five", e.getIllegalStringValue()); assertEquals("five", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); e = new IllegalFieldValueException("months", "five"); assertEquals(null, e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("months", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("five", e.getIllegalStringValue()); assertEquals("five", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } } joda-time-2.3/src/test/java/org/joda/time/TestSeconds.java0000644000175000017500000003410412200501234023000 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for Seconds. * * @author Stephen Colebourne */ public class TestSeconds extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestSeconds.class); } public TestSeconds(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testConstants() { assertEquals(0, Seconds.ZERO.getSeconds()); assertEquals(1, Seconds.ONE.getSeconds()); assertEquals(2, Seconds.TWO.getSeconds()); assertEquals(3, Seconds.THREE.getSeconds()); assertEquals(Integer.MAX_VALUE, Seconds.MAX_VALUE.getSeconds()); assertEquals(Integer.MIN_VALUE, Seconds.MIN_VALUE.getSeconds()); } //----------------------------------------------------------------------- public void testFactory_seconds_int() { assertSame(Seconds.ZERO, Seconds.seconds(0)); assertSame(Seconds.ONE, Seconds.seconds(1)); assertSame(Seconds.TWO, Seconds.seconds(2)); assertSame(Seconds.THREE, Seconds.seconds(3)); assertSame(Seconds.MAX_VALUE, Seconds.seconds(Integer.MAX_VALUE)); assertSame(Seconds.MIN_VALUE, Seconds.seconds(Integer.MIN_VALUE)); assertEquals(-1, Seconds.seconds(-1).getSeconds()); assertEquals(4, Seconds.seconds(4).getSeconds()); } //----------------------------------------------------------------------- public void testFactory_secondsBetween_RInstant() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 3, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 9, 12, 0, 6, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 9, 12, 0, 9, 0, PARIS); assertEquals(3, Seconds.secondsBetween(start, end1).getSeconds()); assertEquals(0, Seconds.secondsBetween(start, start).getSeconds()); assertEquals(0, Seconds.secondsBetween(end1, end1).getSeconds()); assertEquals(-3, Seconds.secondsBetween(end1, start).getSeconds()); assertEquals(6, Seconds.secondsBetween(start, end2).getSeconds()); } public void testFactory_secondsBetween_RPartial() { LocalTime start = new LocalTime(12, 0, 3); LocalTime end1 = new LocalTime(12, 0, 6); @SuppressWarnings("deprecation") TimeOfDay end2 = new TimeOfDay(12, 0, 9); assertEquals(3, Seconds.secondsBetween(start, end1).getSeconds()); assertEquals(0, Seconds.secondsBetween(start, start).getSeconds()); assertEquals(0, Seconds.secondsBetween(end1, end1).getSeconds()); assertEquals(-3, Seconds.secondsBetween(end1, start).getSeconds()); assertEquals(6, Seconds.secondsBetween(start, end2).getSeconds()); } public void testFactory_secondsIn_RInterval() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 3, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 9, 12, 0, 6, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 9, 12, 0, 9, 0, PARIS); assertEquals(0, Seconds.secondsIn((ReadableInterval) null).getSeconds()); assertEquals(3, Seconds.secondsIn(new Interval(start, end1)).getSeconds()); assertEquals(0, Seconds.secondsIn(new Interval(start, start)).getSeconds()); assertEquals(0, Seconds.secondsIn(new Interval(end1, end1)).getSeconds()); assertEquals(6, Seconds.secondsIn(new Interval(start, end2)).getSeconds()); } public void testFactory_standardSecondsIn_RPeriod() { assertEquals(0, Seconds.standardSecondsIn((ReadablePeriod) null).getSeconds()); assertEquals(0, Seconds.standardSecondsIn(Period.ZERO).getSeconds()); assertEquals(1, Seconds.standardSecondsIn(new Period(0, 0, 0, 0, 0, 0, 1, 0)).getSeconds()); assertEquals(123, Seconds.standardSecondsIn(Period.seconds(123)).getSeconds()); assertEquals(-987, Seconds.standardSecondsIn(Period.seconds(-987)).getSeconds()); assertEquals(2 * 24 * 60 * 60, Seconds.standardSecondsIn(Period.days(2)).getSeconds()); try { Seconds.standardSecondsIn(Period.months(1)); fail(); } catch (IllegalArgumentException ex) { // expeceted } } public void testFactory_parseSeconds_String() { assertEquals(0, Seconds.parseSeconds((String) null).getSeconds()); assertEquals(0, Seconds.parseSeconds("PT0S").getSeconds()); assertEquals(1, Seconds.parseSeconds("PT1S").getSeconds()); assertEquals(-3, Seconds.parseSeconds("PT-3S").getSeconds()); assertEquals(2, Seconds.parseSeconds("P0Y0M0DT2S").getSeconds()); assertEquals(2, Seconds.parseSeconds("PT0H2S").getSeconds()); try { Seconds.parseSeconds("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Seconds.parseSeconds("P1DT1S"); fail(); } catch (IllegalArgumentException ex) { // expeceted } } //----------------------------------------------------------------------- public void testGetMethods() { Seconds test = Seconds.seconds(20); assertEquals(20, test.getSeconds()); } public void testGetFieldType() { Seconds test = Seconds.seconds(20); assertEquals(DurationFieldType.seconds(), test.getFieldType()); } public void testGetPeriodType() { Seconds test = Seconds.seconds(20); assertEquals(PeriodType.seconds(), test.getPeriodType()); } //----------------------------------------------------------------------- public void testIsGreaterThan() { assertEquals(true, Seconds.THREE.isGreaterThan(Seconds.TWO)); assertEquals(false, Seconds.THREE.isGreaterThan(Seconds.THREE)); assertEquals(false, Seconds.TWO.isGreaterThan(Seconds.THREE)); assertEquals(true, Seconds.ONE.isGreaterThan(null)); assertEquals(false, Seconds.seconds(-1).isGreaterThan(null)); } public void testIsLessThan() { assertEquals(false, Seconds.THREE.isLessThan(Seconds.TWO)); assertEquals(false, Seconds.THREE.isLessThan(Seconds.THREE)); assertEquals(true, Seconds.TWO.isLessThan(Seconds.THREE)); assertEquals(false, Seconds.ONE.isLessThan(null)); assertEquals(true, Seconds.seconds(-1).isLessThan(null)); } //----------------------------------------------------------------------- public void testToString() { Seconds test = Seconds.seconds(20); assertEquals("PT20S", test.toString()); test = Seconds.seconds(-20); assertEquals("PT-20S", test.toString()); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Seconds test = Seconds.THREE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Seconds result = (Seconds) ois.readObject(); ois.close(); assertSame(test, result); } //----------------------------------------------------------------------- public void testToStandardWeeks() { Seconds test = Seconds.seconds(60 * 60 * 24 * 7 * 2); Weeks expected = Weeks.weeks(2); assertEquals(expected, test.toStandardWeeks()); } public void testToStandardDays() { Seconds test = Seconds.seconds(60 * 60 * 24 * 2); Days expected = Days.days(2); assertEquals(expected, test.toStandardDays()); } public void testToStandardHours() { Seconds test = Seconds.seconds(60 * 60 * 2); Hours expected = Hours.hours(2); assertEquals(expected, test.toStandardHours()); } public void testToStandardMinutes() { Seconds test = Seconds.seconds(60 * 2); Minutes expected = Minutes.minutes(2); assertEquals(expected, test.toStandardMinutes()); } public void testToStandardDuration() { Seconds test = Seconds.seconds(20); Duration expected = new Duration(20L * DateTimeConstants.MILLIS_PER_SECOND); assertEquals(expected, test.toStandardDuration()); expected = new Duration(((long) Integer.MAX_VALUE) * DateTimeConstants.MILLIS_PER_SECOND); assertEquals(expected, Seconds.MAX_VALUE.toStandardDuration()); } //----------------------------------------------------------------------- public void testPlus_int() { Seconds test2 = Seconds.seconds(2); Seconds result = test2.plus(3); assertEquals(2, test2.getSeconds()); assertEquals(5, result.getSeconds()); assertEquals(1, Seconds.ONE.plus(0).getSeconds()); try { Seconds.MAX_VALUE.plus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testPlus_Seconds() { Seconds test2 = Seconds.seconds(2); Seconds test3 = Seconds.seconds(3); Seconds result = test2.plus(test3); assertEquals(2, test2.getSeconds()); assertEquals(3, test3.getSeconds()); assertEquals(5, result.getSeconds()); assertEquals(1, Seconds.ONE.plus(Seconds.ZERO).getSeconds()); assertEquals(1, Seconds.ONE.plus((Seconds) null).getSeconds()); try { Seconds.MAX_VALUE.plus(Seconds.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_int() { Seconds test2 = Seconds.seconds(2); Seconds result = test2.minus(3); assertEquals(2, test2.getSeconds()); assertEquals(-1, result.getSeconds()); assertEquals(1, Seconds.ONE.minus(0).getSeconds()); try { Seconds.MIN_VALUE.minus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_Seconds() { Seconds test2 = Seconds.seconds(2); Seconds test3 = Seconds.seconds(3); Seconds result = test2.minus(test3); assertEquals(2, test2.getSeconds()); assertEquals(3, test3.getSeconds()); assertEquals(-1, result.getSeconds()); assertEquals(1, Seconds.ONE.minus(Seconds.ZERO).getSeconds()); assertEquals(1, Seconds.ONE.minus((Seconds) null).getSeconds()); try { Seconds.MIN_VALUE.minus(Seconds.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMultipliedBy_int() { Seconds test = Seconds.seconds(2); assertEquals(6, test.multipliedBy(3).getSeconds()); assertEquals(2, test.getSeconds()); assertEquals(-6, test.multipliedBy(-3).getSeconds()); assertSame(test, test.multipliedBy(1)); Seconds halfMax = Seconds.seconds(Integer.MAX_VALUE / 2 + 1); try { halfMax.multipliedBy(2); fail(); } catch (ArithmeticException ex) { // expected } } public void testDividedBy_int() { Seconds test = Seconds.seconds(12); assertEquals(6, test.dividedBy(2).getSeconds()); assertEquals(12, test.getSeconds()); assertEquals(4, test.dividedBy(3).getSeconds()); assertEquals(3, test.dividedBy(4).getSeconds()); assertEquals(2, test.dividedBy(5).getSeconds()); assertEquals(2, test.dividedBy(6).getSeconds()); assertSame(test, test.dividedBy(1)); try { Seconds.ONE.dividedBy(0); fail(); } catch (ArithmeticException ex) { // expected } } public void testNegated() { Seconds test = Seconds.seconds(12); assertEquals(-12, test.negated().getSeconds()); assertEquals(12, test.getSeconds()); try { Seconds.MIN_VALUE.negated(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testAddToLocalDate() { Seconds test = Seconds.seconds(26); LocalDateTime date = new LocalDateTime(2006, 6, 1, 0, 0, 0, 0); LocalDateTime expected = new LocalDateTime(2006, 6, 1, 0, 0, 26, 0); assertEquals(expected, date.plus(test)); } } joda-time-2.3/src/test/java/org/joda/time/TestMutableInterval_Constructors.java0000644000175000017500000007327411564251364027325 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.IntervalConverter; /** * This class is a JUnit test for Interval. * * @author Stephen Colebourne */ public class TestMutableInterval_Constructors extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutableInterval_Constructors.class); } public TestMutableInterval_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(PARIS); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { DateTime start = new DateTime(2010, 6, 30, 12, 30, ISOChronology.getInstance(PARIS)); DateTime end = new DateTime(2010, 7, 1, 14, 30, ISOChronology.getInstance(PARIS)); assertEquals(new MutableInterval(start, end), MutableInterval.parse("2010-06-30T12:30/2010-07-01T14:30")); assertEquals(new MutableInterval(start, end), MutableInterval.parse("2010-06-30T12:30/P1DT2H")); assertEquals(new MutableInterval(start, end), MutableInterval.parse("P1DT2H/2010-07-01T14:30")); } //----------------------------------------------------------------------- public void testConstructor() throws Throwable { MutableInterval test = new MutableInterval(); assertEquals(0L, test.getStartMillis()); assertEquals(0L, test.getEndMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_long1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1.getMillis(), dt2.getMillis()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } public void testConstructor_long_long2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); MutableInterval test = new MutableInterval(dt1.getMillis(), dt1.getMillis()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt1.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } public void testConstructor_long_long3() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 10, 1, 1, 1, 1); DateTime dt2 = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { new MutableInterval(dt1.getMillis(), dt2.getMillis()); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_long_long_Chronology1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1.getMillis(), dt2.getMillis(), GJChronology.getInstance()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(GJChronology.getInstance(), test.getChronology()); } public void testConstructor_long_long_Chronology2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1.getMillis(), dt2.getMillis(), null); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testConstructor_RI_RI1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI2() throws Throwable { Instant dt1 = new Instant(new DateTime(2004, 6, 9, 0, 0, 0, 0)); Instant dt2 = new Instant(new DateTime(2005, 7, 10, 1, 1, 1, 1)); MutableInterval test = new MutableInterval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI3() throws Throwable { MutableInterval test = new MutableInterval((ReadableInstant) null, (ReadableInstant) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RI4() throws Throwable { DateTime dt1 = new DateTime(2000, 6, 9, 0, 0, 0, 0); MutableInterval test = new MutableInterval(dt1, (ReadableInstant) null); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RI5() throws Throwable { DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval((ReadableInstant) null, dt2); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI6() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); MutableInterval test = new MutableInterval(dt1, dt1); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt1.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI7() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 10, 1, 1, 1, 1); DateTime dt2 = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { new MutableInterval(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_RI_RI8() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0, GJChronology.getInstance()); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(GJChronology.getInstance(), test.getChronology()); } public void testConstructor_RI_RI9() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1, GJChronology.getInstance()); MutableInterval test = new MutableInterval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testConstructor_RI_RP1() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, 6); result = ISOChronology.getInstance().hours().add(result, 1); MutableInterval test = new MutableInterval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP2() throws Throwable { Instant dt = new Instant(new DateTime(TEST_TIME_NOW)); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstanceUTC().months().add(result, 6); result = ISOChronology.getInstanceUTC().days().add(result, 3); result = ISOChronology.getInstanceUTC().hours().add(result, 1); MutableInterval test = new MutableInterval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW, ISOChronology.getInstanceUTC()); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0, PeriodType.standard()); long result = TEST_TIME_NOW; result = ISOChronology.getInstanceUTC().months().add(result, 6); result = ISOChronology.getInstanceUTC().days().add(result, 3); result = ISOChronology.getInstanceUTC().hours().add(result, 1); MutableInterval test = new MutableInterval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP4() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(1 * DateTimeConstants.MILLIS_PER_HOUR + 23L); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().hours().add(result, 1); result = ISOChronology.getInstance().millis().add(result, 23); MutableInterval test = new MutableInterval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP5() throws Throwable { MutableInterval test = new MutableInterval((ReadableInstant) null, (ReadablePeriod) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RP6() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); MutableInterval test = new MutableInterval(dt, (ReadablePeriod) null); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RP7() throws Throwable { Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, 6); result = ISOChronology.getInstance().hourOfDay().add(result, 1); MutableInterval test = new MutableInterval((ReadableInstant) null, dur); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP8() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 0, 0, 0, 0, 0, 0, -1); try { new MutableInterval(dt, dur); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_RP_RI1() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, -6); result = ISOChronology.getInstance().hours().add(result, -1); MutableInterval test = new MutableInterval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI2() throws Throwable { Instant dt = new Instant(new DateTime(TEST_TIME_NOW)); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstanceUTC().months().add(result, -6); result = ISOChronology.getInstanceUTC().days().add(result, -3); result = ISOChronology.getInstanceUTC().hours().add(result, -1); MutableInterval test = new MutableInterval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW, ISOChronology.getInstanceUTC()); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0, PeriodType.standard()); long result = TEST_TIME_NOW; result = ISOChronology.getInstanceUTC().months().add(result, -6); result = ISOChronology.getInstanceUTC().days().add(result, -3); result = ISOChronology.getInstanceUTC().hours().add(result, -1); MutableInterval test = new MutableInterval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI4() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(1 * DateTimeConstants.MILLIS_PER_HOUR + 23L); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().hours().add(result, -1); result = ISOChronology.getInstance().millis().add(result, -23); MutableInterval test = new MutableInterval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI5() throws Throwable { MutableInterval test = new MutableInterval((ReadablePeriod) null, (ReadableInstant) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RP_RI6() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); MutableInterval test = new MutableInterval((ReadablePeriod) null, dt); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI7() throws Throwable { Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, -6); result = ISOChronology.getInstance().hourOfDay().add(result, -1); MutableInterval test = new MutableInterval(dur, (ReadableInstant) null); assertEquals(result, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RP_RI8() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 0, 0, 0, 0, 0, 0, -1); try { new MutableInterval(dur, dt); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_RI_RD1() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, 6); result = ISOChronology.getInstance().hours().add(result, 1); DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(result - TEST_TIME_NOW); MutableInterval test = new MutableInterval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RD2() throws Throwable { MutableInterval test = new MutableInterval((ReadableInstant) null, (ReadableDuration) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RD3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); MutableInterval test = new MutableInterval(dt, (ReadableDuration) null); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RD4() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, 6); result = ISOChronology.getInstance().hourOfDay().add(result, 1); Duration dur = new Duration(result - TEST_TIME_NOW); MutableInterval test = new MutableInterval((ReadableInstant) null, dur); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RD5() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(-1); try { new MutableInterval(dt, dur); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_RD_RI1() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, -6); result = ISOChronology.getInstance().hours().add(result, -1); DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(TEST_TIME_NOW - result); MutableInterval test = new MutableInterval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RD_RI2() throws Throwable { MutableInterval test = new MutableInterval((ReadableDuration) null, (ReadableInstant) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RD_RI3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); MutableInterval test = new MutableInterval((ReadableDuration) null, dt); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RD_RI4() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, -6); result = ISOChronology.getInstance().hourOfDay().add(result, -1); Duration dur = new Duration(TEST_TIME_NOW - result); MutableInterval test = new MutableInterval(dur, (ReadableInstant) null); assertEquals(result, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RD_RI5() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(-1); try { new MutableInterval(dur, dt); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_Object1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1.toString() + '/' + dt2.toString()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_Object2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval base = new MutableInterval(dt1, dt2); MutableInterval test = new MutableInterval(base); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_Object3() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval base = new Interval(dt1, dt2); MutableInterval test = new MutableInterval(base); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_Object4() throws Throwable { MockInterval base = new MockInterval(); MutableInterval test = new MutableInterval(base); assertEquals(base.getStartMillis(), test.getStartMillis()); assertEquals(base.getEndMillis(), test.getEndMillis()); } public void testConstructor_Object5() throws Throwable { IntervalConverter oldConv = ConverterManager.getInstance().getIntervalConverter(""); IntervalConverter conv = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) { return false; } public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) { interval.setChronology(chrono); interval.setInterval(1234L, 5678L); } public Class getSupportedType() { return String.class; } }; try { ConverterManager.getInstance().addIntervalConverter(conv); DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1.toString() + '/' + dt2.toString()); assertEquals(1234L, test.getStartMillis()); assertEquals(5678L, test.getEndMillis()); } finally { ConverterManager.getInstance().addIntervalConverter(oldConv); } } public void testConstructor_Object6() throws Throwable { IntervalConverter oldConv = ConverterManager.getInstance().getIntervalConverter(new MutableInterval(0L, 0L)); IntervalConverter conv = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) { return false; } public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) { interval.setChronology(chrono); interval.setInterval(1234L, 5678L); } public Class getSupportedType() { return ReadableInterval.class; } }; try { ConverterManager.getInstance().addIntervalConverter(conv); Interval base = new Interval(-1000L, 1000L); MutableInterval test = new MutableInterval(base); assertEquals(1234L, test.getStartMillis()); assertEquals(5678L, test.getEndMillis()); } finally { ConverterManager.getInstance().addIntervalConverter(oldConv); } } class MockInterval implements ReadableInterval { public Chronology getChronology() { return ISOChronology.getInstance(); } public long getStartMillis() { return 1234L; } public DateTime getStart() { return new DateTime(1234L); } public long getEndMillis() { return 5678L; } public DateTime getEnd() { return new DateTime(5678L); } public long toDurationMillis() { return (5678L - 1234L); } public Duration toDuration() { return new Duration(5678L - 1234L); } public boolean contains(long millisInstant) { return false; } public boolean containsNow() { return false; } public boolean contains(ReadableInstant instant) { return false; } public boolean contains(ReadableInterval interval) { return false; } public boolean overlaps(ReadableInterval interval) { return false; } public boolean isBefore(ReadableInstant instant) { return false; } public boolean isBefore(ReadableInterval interval) { return false; } public boolean isAfter(ReadableInstant instant) { return false; } public boolean isAfter(ReadableInterval interval) { return false; } public Interval toInterval() { return null; } public MutableInterval toMutableInterval() { return null; } public Period toPeriod() { return null; } public Period toPeriod(PeriodType type) { return null; } } //----------------------------------------------------------------------- public void testConstructor_Object_Chronology1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval base = new Interval(dt1, dt2); MutableInterval test = new MutableInterval(base, BuddhistChronology.getInstance()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(BuddhistChronology.getInstance(), test.getChronology()); } public void testConstructor_Object_Chronology2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval base = new Interval(dt1, dt2); MutableInterval test = new MutableInterval(base, null); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } } joda-time-2.3/src/test/java/org/joda/time/TestYears.java0000644000175000017500000002676512200501234022503 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for Years. * * @author Stephen Colebourne */ public class TestYears extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestYears.class); } public TestYears(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testConstants() { assertEquals(0, Years.ZERO.getYears()); assertEquals(1, Years.ONE.getYears()); assertEquals(2, Years.TWO.getYears()); assertEquals(3, Years.THREE.getYears()); assertEquals(Integer.MAX_VALUE, Years.MAX_VALUE.getYears()); assertEquals(Integer.MIN_VALUE, Years.MIN_VALUE.getYears()); } //----------------------------------------------------------------------- public void testFactory_years_int() { assertSame(Years.ZERO, Years.years(0)); assertSame(Years.ONE, Years.years(1)); assertSame(Years.TWO, Years.years(2)); assertSame(Years.THREE, Years.years(3)); assertSame(Years.MAX_VALUE, Years.years(Integer.MAX_VALUE)); assertSame(Years.MIN_VALUE, Years.years(Integer.MIN_VALUE)); assertEquals(-1, Years.years(-1).getYears()); assertEquals(4, Years.years(4).getYears()); } //----------------------------------------------------------------------- public void testFactory_yearsBetween_RInstant() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2009, 6, 9, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2012, 6, 9, 12, 0, 0, 0, PARIS); assertEquals(3, Years.yearsBetween(start, end1).getYears()); assertEquals(0, Years.yearsBetween(start, start).getYears()); assertEquals(0, Years.yearsBetween(end1, end1).getYears()); assertEquals(-3, Years.yearsBetween(end1, start).getYears()); assertEquals(6, Years.yearsBetween(start, end2).getYears()); } @SuppressWarnings("deprecation") public void testFactory_yearsBetween_RPartial() { LocalDate start = new LocalDate(2006, 6, 9); LocalDate end1 = new LocalDate(2009, 6, 9); YearMonthDay end2 = new YearMonthDay(2012, 6, 9); assertEquals(3, Years.yearsBetween(start, end1).getYears()); assertEquals(0, Years.yearsBetween(start, start).getYears()); assertEquals(0, Years.yearsBetween(end1, end1).getYears()); assertEquals(-3, Years.yearsBetween(end1, start).getYears()); assertEquals(6, Years.yearsBetween(start, end2).getYears()); } public void testFactory_yearsIn_RInterval() { DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2009, 6, 9, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2012, 6, 9, 12, 0, 0, 0, PARIS); assertEquals(0, Years.yearsIn((ReadableInterval) null).getYears()); assertEquals(3, Years.yearsIn(new Interval(start, end1)).getYears()); assertEquals(0, Years.yearsIn(new Interval(start, start)).getYears()); assertEquals(0, Years.yearsIn(new Interval(end1, end1)).getYears()); assertEquals(6, Years.yearsIn(new Interval(start, end2)).getYears()); } public void testFactory_parseYears_String() { assertEquals(0, Years.parseYears((String) null).getYears()); assertEquals(0, Years.parseYears("P0Y").getYears()); assertEquals(1, Years.parseYears("P1Y").getYears()); assertEquals(-3, Years.parseYears("P-3Y").getYears()); assertEquals(2, Years.parseYears("P2Y0M").getYears()); assertEquals(2, Years.parseYears("P2YT0H0M").getYears()); try { Years.parseYears("P1M1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Years.parseYears("P1YT1H"); fail(); } catch (IllegalArgumentException ex) { // expeceted } } //----------------------------------------------------------------------- public void testGetMethods() { Years test = Years.years(20); assertEquals(20, test.getYears()); } public void testGetFieldType() { Years test = Years.years(20); assertEquals(DurationFieldType.years(), test.getFieldType()); } public void testGetPeriodType() { Years test = Years.years(20); assertEquals(PeriodType.years(), test.getPeriodType()); } //----------------------------------------------------------------------- public void testIsGreaterThan() { assertEquals(true, Years.THREE.isGreaterThan(Years.TWO)); assertEquals(false, Years.THREE.isGreaterThan(Years.THREE)); assertEquals(false, Years.TWO.isGreaterThan(Years.THREE)); assertEquals(true, Years.ONE.isGreaterThan(null)); assertEquals(false, Years.years(-1).isGreaterThan(null)); } public void testIsLessThan() { assertEquals(false, Years.THREE.isLessThan(Years.TWO)); assertEquals(false, Years.THREE.isLessThan(Years.THREE)); assertEquals(true, Years.TWO.isLessThan(Years.THREE)); assertEquals(false, Years.ONE.isLessThan(null)); assertEquals(true, Years.years(-1).isLessThan(null)); } //----------------------------------------------------------------------- public void testToString() { Years test = Years.years(20); assertEquals("P20Y", test.toString()); test = Years.years(-20); assertEquals("P-20Y", test.toString()); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Years test = Years.THREE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Years result = (Years) ois.readObject(); ois.close(); assertSame(test, result); } //----------------------------------------------------------------------- public void testPlus_int() { Years test2 = Years.years(2); Years result = test2.plus(3); assertEquals(2, test2.getYears()); assertEquals(5, result.getYears()); assertEquals(1, Years.ONE.plus(0).getYears()); try { Years.MAX_VALUE.plus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testPlus_Years() { Years test2 = Years.years(2); Years test3 = Years.years(3); Years result = test2.plus(test3); assertEquals(2, test2.getYears()); assertEquals(3, test3.getYears()); assertEquals(5, result.getYears()); assertEquals(1, Years.ONE.plus(Years.ZERO).getYears()); assertEquals(1, Years.ONE.plus((Years) null).getYears()); try { Years.MAX_VALUE.plus(Years.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_int() { Years test2 = Years.years(2); Years result = test2.minus(3); assertEquals(2, test2.getYears()); assertEquals(-1, result.getYears()); assertEquals(1, Years.ONE.minus(0).getYears()); try { Years.MIN_VALUE.minus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_Years() { Years test2 = Years.years(2); Years test3 = Years.years(3); Years result = test2.minus(test3); assertEquals(2, test2.getYears()); assertEquals(3, test3.getYears()); assertEquals(-1, result.getYears()); assertEquals(1, Years.ONE.minus(Years.ZERO).getYears()); assertEquals(1, Years.ONE.minus((Years) null).getYears()); try { Years.MIN_VALUE.minus(Years.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMultipliedBy_int() { Years test = Years.years(2); assertEquals(6, test.multipliedBy(3).getYears()); assertEquals(2, test.getYears()); assertEquals(-6, test.multipliedBy(-3).getYears()); assertSame(test, test.multipliedBy(1)); Years halfMax = Years.years(Integer.MAX_VALUE / 2 + 1); try { halfMax.multipliedBy(2); fail(); } catch (ArithmeticException ex) { // expected } } public void testDividedBy_int() { Years test = Years.years(12); assertEquals(6, test.dividedBy(2).getYears()); assertEquals(12, test.getYears()); assertEquals(4, test.dividedBy(3).getYears()); assertEquals(3, test.dividedBy(4).getYears()); assertEquals(2, test.dividedBy(5).getYears()); assertEquals(2, test.dividedBy(6).getYears()); assertSame(test, test.dividedBy(1)); try { Years.ONE.dividedBy(0); fail(); } catch (ArithmeticException ex) { // expected } } public void testNegated() { Years test = Years.years(12); assertEquals(-12, test.negated().getYears()); assertEquals(12, test.getYears()); try { Years.MIN_VALUE.negated(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testAddToLocalDate() { Years test = Years.years(3); LocalDate date = new LocalDate(2006, 6, 1); LocalDate expected = new LocalDate(2009, 6, 1); assertEquals(expected, date.plus(test)); } } joda-time-2.3/src/test/java/org/joda/time/TestTimeOfDay_Constructors.java0000644000175000017500000007207612200501234026025 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for TimeOfDay. * * @author Stephen Colebourne */ @SuppressWarnings("deprecation") public class TestTimeOfDay_Constructors extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final ISOChronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final int OFFSET = 1; private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME1 = 1L * DateTimeConstants.MILLIS_PER_HOUR + 2L * DateTimeConstants.MILLIS_PER_MINUTE + 3L * DateTimeConstants.MILLIS_PER_SECOND + 4L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestTimeOfDay_Constructors.class); } public TestTimeOfDay_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); java.util.TimeZone.setDefault(LONDON.toTimeZone()); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); java.util.TimeZone.setDefault(zone.toTimeZone()); zone = null; } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstantMidnight() throws Throwable { TimeOfDay test = TimeOfDay.MIDNIGHT; assertEquals(ISO_UTC, test.getChronology()); assertEquals(0, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testFactory_FromCalendarFields() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); TimeOfDay expected = new TimeOfDay(4, 5, 6, 7); assertEquals(expected, TimeOfDay.fromCalendarFields(cal)); try { TimeOfDay.fromCalendarFields(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFactory_FromDateFields_after1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); TimeOfDay expected = new TimeOfDay(4, 5, 6, 7); assertEquals(expected, TimeOfDay.fromDateFields(cal.getTime())); } public void testFactory_FromDateFields_before1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1969, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); TimeOfDay expected = new TimeOfDay(4, 5, 6, 7); assertEquals(expected, TimeOfDay.fromDateFields(cal.getTime())); } public void testFactory_FromDateFields_null() throws Exception { try { TimeOfDay.fromDateFields(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Test factory (long) */ public void testFactoryMillisOfDay_long1() throws Throwable { TimeOfDay test = TimeOfDay.fromMillisOfDay(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test factory (long, Chronology) */ public void testFactoryMillisOfDay_long1_Chronology() throws Throwable { TimeOfDay test = TimeOfDay.fromMillisOfDay(TEST_TIME1, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(1, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test factory (long, Chronology=null) */ public void testFactoryMillisOfDay_long_nullChronology() throws Throwable { TimeOfDay test = TimeOfDay.fromMillisOfDay(TEST_TIME1, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstructor() throws Throwable { TimeOfDay test = new TimeOfDay(); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } /** * Test constructor (DateTimeZone) */ public void testConstructor_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 30, 40, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris TimeOfDay test = new TimeOfDay(LONDON); assertEquals(ISO_UTC, test.getChronology()); assertEquals(23, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); test = new TimeOfDay(PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(0, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } /** * Test constructor (DateTimeZone=null) */ public void testConstructor_nullDateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 30, 40, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris TimeOfDay test = new TimeOfDay((DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(23, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } /** * Test constructor (Chronology) */ public void testConstructor_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay(JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(10 + OFFSET, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } /** * Test constructor (Chronology=null) */ public void testConstructor_nullChronology() throws Throwable { TimeOfDay test = new TimeOfDay((Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- /** * Test constructor (long) */ public void testConstructor_long1() throws Throwable { TimeOfDay test = new TimeOfDay(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test constructor (long) */ public void testConstructor_long2() throws Throwable { TimeOfDay test = new TimeOfDay(TEST_TIME2); assertEquals(ISO_UTC, test.getChronology()); assertEquals(5 + OFFSET, test.getHourOfDay()); assertEquals(6, test.getMinuteOfHour()); assertEquals(7, test.getSecondOfMinute()); assertEquals(8, test.getMillisOfSecond()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long1_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay(TEST_TIME1, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(1 + OFFSET, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long2_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay(TEST_TIME2, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(5 + OFFSET, test.getHourOfDay()); assertEquals(6, test.getMinuteOfHour()); assertEquals(7, test.getSecondOfMinute()); assertEquals(8, test.getMillisOfSecond()); } /** * Test constructor (long, Chronology=null) */ public void testConstructor_long_nullChronology() throws Throwable { TimeOfDay test = new TimeOfDay(TEST_TIME1, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } //----------------------------------------------------------------------- /** * Test constructor (Object) */ public void testConstructor_Object1() throws Throwable { Date date = new Date(TEST_TIME1); TimeOfDay test = new TimeOfDay(date); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test constructor (Object) */ public void testConstructor_Object2() throws Throwable { Calendar cal = new GregorianCalendar(); cal.setTime(new Date(TEST_TIME1)); TimeOfDay test = new TimeOfDay(cal); assertEquals(GJChronology.getInstanceUTC(), test.getChronology()); assertEquals(1 + OFFSET, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test constructor (Object=null) */ public void testConstructor_nullObject() throws Throwable { TimeOfDay test = new TimeOfDay((Object) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } /** * Test constructor (Object) */ public void testConstructor_todObject() throws Throwable { TimeOfDay base = new TimeOfDay(10, 20, 30, 40, CopticChronology.getInstance(PARIS)); TimeOfDay test = new TimeOfDay(base); assertEquals(CopticChronology.getInstanceUTC(), test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString1() throws Throwable { TimeOfDay test = new TimeOfDay("10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString2() throws Throwable { TimeOfDay test = new TimeOfDay("10:20:30.040+04:00"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET - 4, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString3() throws Throwable { TimeOfDay test = new TimeOfDay("T10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString4() throws Throwable { TimeOfDay test = new TimeOfDay("T10:20:30.040+04:00"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET - 4, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString5() throws Throwable { TimeOfDay test = new TimeOfDay("10:20"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectString6() throws Throwable { TimeOfDay test = new TimeOfDay("10"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectStringEx1() throws Throwable { try { new TimeOfDay("1970-04-06"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx2() throws Throwable { try { new TimeOfDay("1970-04-06T+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx3() throws Throwable { try { new TimeOfDay("1970-04-06T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx4() throws Throwable { try { new TimeOfDay("1970-04-06T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Test constructor (Object, Chronology) */ public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); TimeOfDay test = new TimeOfDay(date, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(1 + OFFSET, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test constructor (Object, Chronology) */ public void testConstructor2_Object_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay("T10:20"); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new TimeOfDay("T1020"); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null, Chronology) */ public void testConstructor_nullObject_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay((Object) null, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(10 + OFFSET, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } /** * Test constructor (Object, Chronology=null) */ public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); TimeOfDay test = new TimeOfDay(date, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } /** * Test constructor (Object=null, Chronology=null) */ public void testConstructor_nullObject_nullChronology() throws Throwable { TimeOfDay test = new TimeOfDay((Object) null, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- /** * Test constructor (int, int) */ public void testConstructor_int_int() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new TimeOfDay(-1, 20); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(24, 20); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, -1); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 60); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology) */ public void testConstructor_int_int_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new TimeOfDay(-1, 20, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(24, 20, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, -1, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 60, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology=null) */ public void testConstructor_int_int_nullChronology() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } /** * Test constructor (int, int, int) */ public void testConstructor_int_int_int() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, 30); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new TimeOfDay(-1, 20, 30); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(24, 20, 30); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, -1, 30); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 60, 30); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, -1); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 60); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology) */ public void testConstructor_int_int_int_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, 30, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new TimeOfDay(-1, 20, 30, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(24, 20, 30, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, -1, 30, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 60, 30, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, -1, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 60, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology=null) */ public void testConstructor_int_int_int_nullChronology() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, 30, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } /** * Test constructor (int, int, int, int) */ public void testConstructor_int_int_int_int() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new TimeOfDay(-1, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(24, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, -1, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 60, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, -1, 40); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 60, 40); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 30, -1); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 30, 1000); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, int, Chronology) */ public void testConstructor_int_int_int_int_Chronology() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, 30, 40, JulianChronology.getInstance()); assertEquals(JulianChronology.getInstanceUTC(), test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new TimeOfDay(-1, 20, 30, 40, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(24, 20, 30, 40, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, -1, 30, 40, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 60, 30, 40, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, -1, 40, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 60, 40, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 30, -1, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new TimeOfDay(10, 20, 30, 1000, JulianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, int, Chronology=null) */ public void testConstructor_int_int_int_int_nullChronology() throws Throwable { TimeOfDay test = new TimeOfDay(10, 20, 30, 40, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalDateTime_Basics.java0000644000175000017500000014121112200504227025340 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for LocalDate. * * @author Stephen Colebourne */ public class TestLocalDateTime_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final GJChronology GJ_UTC = GJChronology.getInstanceUTC(); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology GREGORIAN_UTC = GregorianChronology.getInstanceUTC(); private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); // private long TEST_TIME1 = // (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 12L * DateTimeConstants.MILLIS_PER_HOUR // + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // // private long TEST_TIME2 = // (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 14L * DateTimeConstants.MILLIS_PER_HOUR // + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private int MILLIS_OF_DAY_UTC = (int) (10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L); private long TEST_TIME_NOW_UTC = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY + MILLIS_OF_DAY_UTC; private DateTimeZone zone = null; private Locale systemDefaultLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalDateTime_Basics.class); } public TestLocalDateTime_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW_UTC); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); systemDefaultLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; Locale.setDefault(systemDefaultLocale); systemDefaultLocale = null; } //----------------------------------------------------------------------- public void testGet_DateTimeFieldType() { LocalDateTime test = new LocalDateTime(1970, 6, 9, 10, 20, 30, 40); assertEquals(1970, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); assertEquals(2, test.get(DateTimeFieldType.dayOfWeek())); assertEquals(160, test.get(DateTimeFieldType.dayOfYear())); assertEquals(24, test.get(DateTimeFieldType.weekOfWeekyear())); assertEquals(1970, test.get(DateTimeFieldType.weekyear())); assertEquals(10, test.get(DateTimeFieldType.hourOfDay())); assertEquals(20, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(30, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(40, test.get(DateTimeFieldType.millisOfSecond())); assertEquals(MILLIS_OF_DAY_UTC / 60000 , test.get(DateTimeFieldType.minuteOfDay())); assertEquals(MILLIS_OF_DAY_UTC / 1000 , test.get(DateTimeFieldType.secondOfDay())); assertEquals(MILLIS_OF_DAY_UTC , test.get(DateTimeFieldType.millisOfDay())); assertEquals(10, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(DateTimeConstants.AM, test.get(DateTimeFieldType.halfdayOfDay())); test = new LocalDateTime(1970, 6, 9, 12, 30); assertEquals(0, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(12, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(12, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(DateTimeConstants.PM, test.get(DateTimeFieldType.halfdayOfDay())); test = new LocalDateTime(1970, 6, 9, 14, 30); assertEquals(2, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(2, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(14, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(DateTimeConstants.PM, test.get(DateTimeFieldType.halfdayOfDay())); test = new LocalDateTime(1970, 6, 9, 0, 30); assertEquals(0, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(12, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(24, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(DateTimeConstants.AM, test.get(DateTimeFieldType.halfdayOfDay())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { LocalDateTime test = new LocalDateTime(); assertEquals(4, test.size()); } public void testGetFieldType_int() { LocalDateTime test = new LocalDateTime(COPTIC_PARIS); assertSame(DateTimeFieldType.year(), test.getFieldType(0)); assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(1)); assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(2)); assertSame(DateTimeFieldType.millisOfDay(), test.getFieldType(3)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { LocalDateTime test = new LocalDateTime(COPTIC_PARIS); DateTimeFieldType[] fields = test.getFieldTypes(); assertSame(DateTimeFieldType.year(), fields[0]); assertSame(DateTimeFieldType.monthOfYear(), fields[1]); assertSame(DateTimeFieldType.dayOfMonth(), fields[2]); assertSame(DateTimeFieldType.millisOfDay(), fields[3]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField_int() { LocalDateTime test = new LocalDateTime(COPTIC_PARIS); assertSame(COPTIC_UTC.year(), test.getField(0)); assertSame(COPTIC_UTC.monthOfYear(), test.getField(1)); assertSame(COPTIC_UTC.dayOfMonth(), test.getField(2)); assertSame(COPTIC_UTC.millisOfDay(), test.getField(3)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { LocalDateTime test = new LocalDateTime(COPTIC_PARIS); DateTimeField[] fields = test.getFields(); assertSame(COPTIC_UTC.year(), fields[0]); assertSame(COPTIC_UTC.monthOfYear(), fields[1]); assertSame(COPTIC_UTC.dayOfMonth(), fields[2]); assertSame(COPTIC_UTC.millisOfDay(), fields[3]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue_int() { LocalDateTime test = new LocalDateTime(ISO_UTC); assertEquals(1970, test.getValue(0)); assertEquals(6, test.getValue(1)); assertEquals(9, test.getValue(2)); assertEquals(MILLIS_OF_DAY_UTC, test.getValue(3)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { LocalDateTime test = new LocalDateTime(ISO_UTC); int[] values = test.getValues(); assertEquals(1970, values[0]); assertEquals(6, values[1]); assertEquals(9, values[2]); assertEquals(MILLIS_OF_DAY_UTC, values[3]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported_DateTimeFieldType() { LocalDateTime test = new LocalDateTime(); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfWeek())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.weekOfWeekyear())); assertEquals(true, test.isSupported(DateTimeFieldType.weekyear())); assertEquals(true, test.isSupported(DateTimeFieldType.yearOfCentury())); assertEquals(true, test.isSupported(DateTimeFieldType.yearOfEra())); assertEquals(true, test.isSupported(DateTimeFieldType.centuryOfEra())); assertEquals(true, test.isSupported(DateTimeFieldType.weekyearOfCentury())); assertEquals(true, test.isSupported(DateTimeFieldType.era())); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfHour())); assertEquals(true, test.isSupported(DateTimeFieldType.secondOfMinute())); assertEquals(true, test.isSupported(DateTimeFieldType.millisOfSecond())); assertEquals(true, test.isSupported(DateTimeFieldType.minuteOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.secondOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.millisOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.hourOfHalfday())); assertEquals(true, test.isSupported(DateTimeFieldType.halfdayOfDay())); assertEquals(true, test.isSupported(DateTimeFieldType.clockhourOfHalfday())); assertEquals(true, test.isSupported(DateTimeFieldType.clockhourOfDay())); assertEquals(false, test.isSupported((DateTimeFieldType) null)); } public void testIsSupported_DurationFieldType() { LocalDateTime test = new LocalDateTime(); assertEquals(false, test.isSupported(DurationFieldType.eras())); assertEquals(true, test.isSupported(DurationFieldType.centuries())); assertEquals(true, test.isSupported(DurationFieldType.years())); assertEquals(true, test.isSupported(DurationFieldType.months())); assertEquals(true, test.isSupported(DurationFieldType.weekyears())); assertEquals(true, test.isSupported(DurationFieldType.weeks())); assertEquals(true, test.isSupported(DurationFieldType.days())); assertEquals(true, test.isSupported(DurationFieldType.hours())); assertEquals(true, test.isSupported(DurationFieldType.minutes())); assertEquals(true, test.isSupported(DurationFieldType.seconds())); assertEquals(true, test.isSupported(DurationFieldType.millis())); assertEquals(true, test.isSupported(DurationFieldType.halfdays())); assertEquals(false, test.isSupported((DurationFieldType) null)); } public void testEqualsHashCode() { LocalDateTime test1 = new LocalDateTime(1970, 6, 9, 10, 20, 30, 40, COPTIC_PARIS); LocalDateTime test2 = new LocalDateTime(1970, 6, 9, 10, 20, 30, 40, COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); LocalDateTime test3 = new LocalDateTime(1971, 6, 9, 10, 20, 30, 40); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInstant())); Partial partial = new Partial( new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth(), DateTimeFieldType.millisOfDay()}, new int[] {1970, 6, 9, MILLIS_OF_DAY_UTC}, COPTIC_PARIS); assertEquals(true, test1.equals(partial)); assertEquals(true, test1.hashCode() == partial.hashCode()); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); } class MockInstant extends MockPartial { public Chronology getChronology() { return COPTIC_UTC; } public DateTimeField[] getFields() { return new DateTimeField[] { COPTIC_UTC.year(), COPTIC_UTC.monthOfYear(), COPTIC_UTC.dayOfMonth(), COPTIC_UTC.millisOfDay(), }; } public int[] getValues() { return new int[] {1970, 6, 9, MILLIS_OF_DAY_UTC}; } } //----------------------------------------------------------------------- public void testCompareTo() { LocalDateTime test1 = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); LocalDateTime test1a = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); LocalDateTime test2 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); LocalDateTime test3 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40, GREGORIAN_UTC); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth(), DateTimeFieldType.millisOfDay(), }; int[] values = new int[] {2005, 6, 2, MILLIS_OF_DAY_UTC}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} try { @SuppressWarnings("deprecation") YearMonthDay ymd = new YearMonthDay(); test1.compareTo(ymd); fail(); } catch (ClassCastException ex) {} try { @SuppressWarnings("deprecation") TimeOfDay tod = new TimeOfDay(); test1.compareTo(tod); fail(); } catch (ClassCastException ex) {} Partial partial = new Partial() .with(DateTimeFieldType.centuryOfEra(), 1) .with(DateTimeFieldType.halfdayOfDay(), 0) .with(DateTimeFieldType.dayOfMonth(), 9); try { new LocalDateTime(1970, 6, 9, 10, 20, 30, 40).compareTo(partial); fail(); } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_LocalDateTime() { LocalDateTime test1 = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); LocalDateTime test1a = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); LocalDateTime test2 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); LocalDateTime test3 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40, GREGORIAN_UTC); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { new LocalDateTime(2005, 7, 2, 10, 20, 30, 40).isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_LocalDateTime() { LocalDateTime test1 = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); LocalDateTime test1a = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); LocalDateTime test2 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); LocalDateTime test3 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40, GREGORIAN_UTC); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new LocalDateTime(2005, 7, 2, 10, 20, 30, 40).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_LocalDateTime() { LocalDateTime test1 = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); LocalDateTime test1a = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); LocalDateTime test2 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); LocalDateTime test3 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40, GREGORIAN_UTC); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new LocalDateTime(2005, 7, 2, 10, 20, 30, 40).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithDate() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); LocalDateTime result = test.withDate(2006, 2, 1); check(test, 2004, 6, 9, 10, 20, 30, 40); check(result, 2006, 2, 1, 10, 20, 30, 40); } //----------------------------------------------------------------------- public void testWithTime() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); LocalDateTime result = test.withTime(9, 8, 7, 6); check(test, 2004, 6, 9, 10, 20, 30, 40); check(result, 2004, 6, 9, 9, 8, 7, 6); } //----------------------------------------------------------------------- public void testWithField_DateTimeFieldType_int_1() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); LocalDateTime result = test.withField(DateTimeFieldType.year(), 2006); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30, 40), test); assertEquals(new LocalDateTime(2006, 6, 9, 10, 20, 30, 40), result); } public void testWithField_DateTimeFieldType_int_2() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_DateTimeFieldType_int_3() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); LocalDateTime result = test.withField(DateTimeFieldType.year(), 2004); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30, 40), test); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded_DurationFieldType_int_1() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); LocalDateTime result = test.withFieldAdded(DurationFieldType.years(), 6); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30, 40), test); assertEquals(new LocalDateTime(2010, 6, 9, 10, 20, 30, 40), result); } public void testWithFieldAdded_DurationFieldType_int_2() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_DurationFieldType_int_3() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_DurationFieldType_int_4() { LocalDateTime test = new LocalDateTime(2004, 6, 9, 10, 20, 30, 40); LocalDateTime result = test.withFieldAdded(DurationFieldType.years(), 0); assertSame(test, result); } //----------------------------------------------------------------------- public void testPlus_RP() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plus(new Period(1, 2, 3, 4, 29, 6, 7, 8)); LocalDateTime expected = new LocalDateTime(2003, 7, 29, 15, 26, 37, 48, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusYears_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusYears(1); LocalDateTime expected = new LocalDateTime(2003, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusYears(0); assertSame(test, result); } public void testPlusMonths_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusMonths(1); LocalDateTime expected = new LocalDateTime(2002, 6, 3, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusMonths(0); assertSame(test, result); } public void testPlusWeeks_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusWeeks(1); LocalDateTime expected = new LocalDateTime(2002, 5, 10, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusWeeks(0); assertSame(test, result); } public void testPlusDays_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusDays(1); LocalDateTime expected = new LocalDateTime(2002, 5, 4, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusDays(0); assertSame(test, result); } public void testPlusHours_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusHours(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 11, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusHours(0); assertSame(test, result); } public void testPlusMinutes_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusMinutes(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 10, 21, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusMinutes(0); assertSame(test, result); } public void testPlusSeconds_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusSeconds(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 10, 20, 31, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusSeconds(0); assertSame(test, result); } public void testPlusMillis_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.plusMillis(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 10, 20, 30, 41, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); LocalDateTime expected = new LocalDateTime(2001, 3, 26, 9, 19, 29, 39, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusYears_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusYears(1); LocalDateTime expected = new LocalDateTime(2001, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusYears(0); assertSame(test, result); } public void testMinusMonths_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusMonths(1); LocalDateTime expected = new LocalDateTime(2002, 4, 3, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusMonths(0); assertSame(test, result); } public void testMinusWeeks_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusWeeks(1); LocalDateTime expected = new LocalDateTime(2002, 4, 26, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusWeeks(0); assertSame(test, result); } public void testMinusDays_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusDays(1); LocalDateTime expected = new LocalDateTime(2002, 5, 2, 10, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusDays(0); assertSame(test, result); } public void testMinusHours_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusHours(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 9, 20, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusHours(0); assertSame(test, result); } public void testMinusMinutes_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusMinutes(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 10, 19, 30, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusMinutes(0); assertSame(test, result); } public void testMinusSeconds_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusSeconds(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 10, 20, 29, 40, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusSeconds(0); assertSame(test, result); } public void testMinusMillis_int() { LocalDateTime test = new LocalDateTime(2002, 5, 3, 10, 20, 30, 40, BUDDHIST_LONDON); LocalDateTime result = test.minusMillis(1); LocalDateTime expected = new LocalDateTime(2002, 5, 3, 10, 20, 30, 39, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusMillis(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testGetters() { LocalDateTime test = new LocalDateTime(1970, 6, 9, 10, 20, 30, 40, GJ_UTC); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(160, test.getDayOfYear()); assertEquals(2, test.getDayOfWeek()); assertEquals(24, test.getWeekOfWeekyear()); assertEquals(1970, test.getWeekyear()); assertEquals(70, test.getYearOfCentury()); assertEquals(20, test.getCenturyOfEra()); assertEquals(1970, test.getYearOfEra()); assertEquals(DateTimeConstants.AD, test.getEra()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(MILLIS_OF_DAY_UTC, test.getMillisOfDay()); } //----------------------------------------------------------------------- public void testWithers() { LocalDateTime test = new LocalDateTime(1970, 6, 9, 10, 20, 30, 40, GJ_UTC); check(test.withYear(2000), 2000, 6, 9, 10, 20, 30, 40); check(test.withMonthOfYear(2), 1970, 2, 9, 10, 20, 30, 40); check(test.withDayOfMonth(2), 1970, 6, 2, 10, 20, 30, 40); check(test.withDayOfYear(6), 1970, 1, 6, 10, 20, 30, 40); check(test.withDayOfWeek(6), 1970, 6, 13, 10, 20, 30, 40); check(test.withWeekOfWeekyear(6), 1970, 2, 3, 10, 20, 30, 40); check(test.withWeekyear(1971), 1971, 6, 15, 10, 20, 30, 40); check(test.withYearOfCentury(60), 1960, 6, 9, 10, 20, 30, 40); check(test.withCenturyOfEra(21), 2070, 6, 9, 10, 20, 30, 40); check(test.withYearOfEra(1066), 1066, 6, 9, 10, 20, 30, 40); check(test.withEra(DateTimeConstants.BC), -1970, 6, 9, 10, 20, 30, 40); check(test.withHourOfDay(6), 1970, 6, 9, 6, 20, 30, 40); check(test.withMinuteOfHour(6), 1970, 6, 9, 10, 6, 30, 40); check(test.withSecondOfMinute(6), 1970, 6, 9, 10, 20, 6, 40); check(test.withMillisOfSecond(6), 1970, 6, 9, 10, 20, 30, 6); check(test.withMillisOfDay(61234), 1970, 6, 9, 0, 1, 1, 234); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testToDateTime() { LocalDateTime base = new LocalDateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_PARIS); // PARIS irrelevant DateTime test = base.toDateTime(); check(base, 2005, 6, 9, 6, 7, 8, 9); DateTime expected = new DateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_LONDON); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTime_Zone() { LocalDateTime base = new LocalDateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_PARIS); // PARIS irrelevant DateTime test = base.toDateTime(TOKYO); check(base, 2005, 6, 9, 6, 7, 8, 9); DateTime expected = new DateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_TOKYO); assertEquals(expected, test); } public void testToDateTime_nullZone() { LocalDateTime base = new LocalDateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_PARIS); // PARIS irrelevant DateTime test = base.toDateTime((DateTimeZone) null); check(base, 2005, 6, 9, 6, 7, 8, 9); DateTime expected = new DateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_LONDON); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToLocalDate() { LocalDateTime base = new LocalDateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_PARIS); // PARIS irrelevant LocalDate expected = new LocalDate(2005, 6, 9, COPTIC_LONDON); assertEquals(expected,base.toLocalDate()); } public void testToLocalTime() { LocalDateTime base = new LocalDateTime(2005, 6, 9, 6, 7, 8, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime expected = new LocalTime(6, 7, 8, 9, COPTIC_LONDON); assertEquals(expected,base.toLocalTime()); } //----------------------------------------------------------------------- public void testToDateTime_RI() { LocalDateTime base = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40, COPTIC_PARIS); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7, BUDDHIST_TOKYO); DateTime test = base.toDateTime(dt); check(base, 2005, 6, 9, 10, 20, 30, 40); DateTime expected = new DateTime(2005, 6, 9, 10, 20, 30, 40, BUDDHIST_TOKYO); assertEquals(expected, test); } public void testToDateTime_nullRI() { LocalDateTime base = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40, COPTIC_PARIS); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 2005, 6, 9, 10, 20, 30, 40); DateTime expected = new DateTime(2005, 6, 9, 10, 20, 30, 40, ISO_LONDON); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDate_summer() { LocalDateTime base = new LocalDateTime(2005, 7, 9, 10, 20, 30, 40, COPTIC_PARIS); Date test = base.toDate(); check(base, 2005, 7, 9, 10, 20, 30, 40); GregorianCalendar gcal = new GregorianCalendar(); gcal.clear(); gcal.set(Calendar.YEAR, 2005); gcal.set(Calendar.MONTH, Calendar.JULY); gcal.set(Calendar.DAY_OF_MONTH, 9); gcal.set(Calendar.HOUR_OF_DAY, 10); gcal.set(Calendar.MINUTE, 20); gcal.set(Calendar.SECOND, 30); gcal.set(Calendar.MILLISECOND, 40); assertEquals(gcal.getTime(), test); } public void testToDate_winter() { LocalDateTime base = new LocalDateTime(2005, 1, 9, 10, 20, 30, 40, COPTIC_PARIS); Date test = base.toDate(); check(base, 2005, 1, 9, 10, 20, 30, 40); GregorianCalendar gcal = new GregorianCalendar(); gcal.clear(); gcal.set(Calendar.YEAR, 2005); gcal.set(Calendar.MONTH, Calendar.JANUARY); gcal.set(Calendar.DAY_OF_MONTH, 9); gcal.set(Calendar.HOUR_OF_DAY, 10); gcal.set(Calendar.MINUTE, 20); gcal.set(Calendar.SECOND, 30); gcal.set(Calendar.MILLISECOND, 40); assertEquals(gcal.getTime(), test); } public void testToDate_springDST() { LocalDateTime base = new LocalDateTime(2007, 4, 2, 0, 20, 0, 0); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(); check(base, 2007, 4, 2, 0, 20, 0, 0); assertEquals("Mon Apr 02 01:00:00 GMT+02:00 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } public void testToDate_springDST_2Hour40Savings() { LocalDateTime base = new LocalDateTime(2007, 4, 2, 0, 20, 0, 0); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000, (3600000 / 6) * 16); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(); check(base, 2007, 4, 2, 0, 20, 0, 0); assertEquals("Mon Apr 02 02:40:00 GMT+03:40 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } public void testToDate_autumnDST() { LocalDateTime base = new LocalDateTime(2007, 10, 2, 0, 20, 30, 0); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(); check(base, 2007, 10, 2, 0, 20, 30, 0); assertEquals("Tue Oct 02 00:20:30 GMT+02:00 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } //----------------------------------------------------------------------- public void testToDate_summer_Zone() { LocalDateTime base = new LocalDateTime(2005, 7, 9, 10, 20, 30, 40, COPTIC_PARIS); Date test = base.toDate(TimeZone.getDefault()); check(base, 2005, 7, 9, 10, 20, 30, 40); GregorianCalendar gcal = new GregorianCalendar(); gcal.clear(); gcal.set(Calendar.YEAR, 2005); gcal.set(Calendar.MONTH, Calendar.JULY); gcal.set(Calendar.DAY_OF_MONTH, 9); gcal.set(Calendar.HOUR_OF_DAY, 10); gcal.set(Calendar.MINUTE, 20); gcal.set(Calendar.SECOND, 30); gcal.set(Calendar.MILLISECOND, 40); assertEquals(gcal.getTime(), test); } public void testToDate_winter_Zone() { LocalDateTime base = new LocalDateTime(2005, 1, 9, 10, 20, 30, 40, COPTIC_PARIS); Date test = base.toDate(TimeZone.getDefault()); check(base, 2005, 1, 9, 10, 20, 30, 40); GregorianCalendar gcal = new GregorianCalendar(); gcal.clear(); gcal.set(Calendar.YEAR, 2005); gcal.set(Calendar.MONTH, Calendar.JANUARY); gcal.set(Calendar.DAY_OF_MONTH, 9); gcal.set(Calendar.HOUR_OF_DAY, 10); gcal.set(Calendar.MINUTE, 20); gcal.set(Calendar.SECOND, 30); gcal.set(Calendar.MILLISECOND, 40); assertEquals(gcal.getTime(), test); } public void testToDate_springDST_Zone() { LocalDateTime base = new LocalDateTime(2007, 4, 2, 0, 20, 0, 0); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(TimeZone.getDefault()); check(base, 2007, 4, 2, 0, 20, 0, 0); assertEquals("Mon Apr 02 01:00:00 GMT+02:00 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } public void testToDate_springDST_2Hour40Savings_Zone() { LocalDateTime base = new LocalDateTime(2007, 4, 2, 0, 20, 0, 0); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000, (3600000 / 6) * 16); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(TimeZone.getDefault()); check(base, 2007, 4, 2, 0, 20, 0, 0); assertEquals("Mon Apr 02 02:40:00 GMT+03:40 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } public void testToDate_autumnDST_Zone() { LocalDateTime base = new LocalDateTime(2007, 10, 2, 0, 20, 30, 0); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(TimeZone.getDefault()); check(base, 2007, 10, 2, 0, 20, 30, 0); assertEquals("Tue Oct 02 00:20:30 GMT+02:00 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } //----------------------------------------------------------------------- public void testProperty() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40, GJ_UTC); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear())); assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth())); assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek())); assertEquals(test.dayOfYear(), test.property(DateTimeFieldType.dayOfYear())); assertEquals(test.weekOfWeekyear(), test.property(DateTimeFieldType.weekOfWeekyear())); assertEquals(test.weekyear(), test.property(DateTimeFieldType.weekyear())); assertEquals(test.yearOfCentury(), test.property(DateTimeFieldType.yearOfCentury())); assertEquals(test.yearOfEra(), test.property(DateTimeFieldType.yearOfEra())); assertEquals(test.centuryOfEra(), test.property(DateTimeFieldType.centuryOfEra())); assertEquals(test.era(), test.property(DateTimeFieldType.era())); assertEquals(test.hourOfDay(), test.property(DateTimeFieldType.hourOfDay())); assertEquals(test.minuteOfHour(), test.property(DateTimeFieldType.minuteOfHour())); assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute())); assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond())); assertEquals(test.millisOfDay(), test.property(DateTimeFieldType.millisOfDay())); try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(test, test.property(DateTimeFieldType.minuteOfDay()).getLocalDateTime()); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { LocalDateTime test = new LocalDateTime(1972, 6, 9, 10, 20, 30, 40, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); LocalDateTime result = (LocalDateTime) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); assertTrue(result.isSupported(DateTimeFieldType.dayOfMonth())); // check deserialization } //----------------------------------------------------------------------- public void testToString() { LocalDateTime test = new LocalDateTime(2002, 6, 9, 10, 20, 30, 40); assertEquals("2002-06-09T10:20:30.040", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { LocalDateTime test = new LocalDateTime(2002, 6, 9, 10, 20, 30, 40); assertEquals("2002 10", test.toString("yyyy HH")); assertEquals("2002-06-09T10:20:30.040", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { LocalDateTime test = new LocalDateTime(1970, 6, 9, 10, 20, 30, 40); assertEquals("Tue 9/6", test.toString("EEE d/M", Locale.ENGLISH)); assertEquals("mar. 9/6", test.toString("EEE d/M", Locale.FRENCH)); assertEquals("1970-06-09T10:20:30.040", test.toString(null, Locale.ENGLISH)); assertEquals("Tue 9/6", test.toString("EEE d/M", null)); assertEquals("1970-06-09T10:20:30.040", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { LocalDateTime test = new LocalDateTime(2002, 6, 9, 10, 20, 30, 40); assertEquals("2002 10", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("2002-06-09T10:20:30.040", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private void check(LocalDateTime test, int year, int month, int day, int hour, int min, int sec, int mil) { assertEquals(year, test.getYear()); assertEquals(month, test.getMonthOfYear()); assertEquals(day, test.getDayOfMonth()); assertEquals(hour, test.getHourOfDay()); assertEquals(min, test.getMinuteOfHour()); assertEquals(sec, test.getSecondOfMinute()); assertEquals(mil, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutableInterval_Updates.java0000644000175000017500000003724011564251364026213 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractInterval; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for Instant. * * @author Stephen Colebourne */ public class TestMutableInterval_Updates extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutableInterval_Updates.class); } public TestMutableInterval_Updates(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testSetInterval_long_long1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setInterval(TEST_TIME1 - 1, TEST_TIME2 + 1); assertEquals(TEST_TIME1 - 1, test.getStartMillis()); assertEquals(TEST_TIME2 + 1, test.getEndMillis()); } public void testSetInterval_long_long2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setInterval(TEST_TIME1 - 1, TEST_TIME1 - 2); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetInterval_RI_RI1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setInterval(new Instant(TEST_TIME1 - 1), new Instant(TEST_TIME2 + 1)); assertEquals(TEST_TIME1 - 1, test.getStartMillis()); assertEquals(TEST_TIME2 + 1, test.getEndMillis()); } public void testSetInterval_RI_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setInterval(new Instant(TEST_TIME1 - 1), new Instant(TEST_TIME1 - 2)); fail(); } catch (IllegalArgumentException ex) {} } public void testSetInterval_RI_RI3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setInterval(null, new Instant(TEST_TIME2 + 1)); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME2 + 1, test.getEndMillis()); } public void testSetInterval_RI_RI4() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setInterval(new Instant(TEST_TIME1 - 1), null); assertEquals(TEST_TIME1 - 1, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testSetInterval_RI_RI5() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setInterval(null, null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } //----------------------------------------------------------------------- public void testSetInterval_RInterval1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setInterval(new Interval(TEST_TIME1 - 1, TEST_TIME2 + 1)); assertEquals(TEST_TIME1 - 1, test.getStartMillis()); assertEquals(TEST_TIME2 + 1, test.getEndMillis()); } public void testSetInterval_RInterval2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setInterval(new MockBadInterval()); fail(); } catch (IllegalArgumentException ex) {} } class MockBadInterval extends AbstractInterval { public Chronology getChronology() { return ISOChronology.getInstance(); } public long getStartMillis() { return TEST_TIME1 - 1; } public long getEndMillis() { return TEST_TIME1 - 2; } } public void testSetInterval_RInterval3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setInterval(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetStartMillis_long1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setStartMillis(TEST_TIME1 - 1); assertEquals(TEST_TIME1 - 1, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } public void testSetStartMillis_long2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setStartMillis(TEST_TIME2 + 1); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetStart_RI1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setStart(new Instant(TEST_TIME1 - 1)); assertEquals(TEST_TIME1 - 1, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } public void testSetStart_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setStart(new Instant(TEST_TIME2 + 1)); fail(); } catch (IllegalArgumentException ex) {} } public void testSetStart_RI3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setStart(null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } //----------------------------------------------------------------------- public void testSetEndMillis_long1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setEndMillis(TEST_TIME2 + 1); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME2 + 1, test.getEndMillis()); } public void testSetEndMillis_long2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setEndMillis(TEST_TIME1 - 1); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetEnd_RI1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setEnd(new Instant(TEST_TIME2 + 1)); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME2 + 1, test.getEndMillis()); } public void testSetEnd_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setEnd(new Instant(TEST_TIME1 - 1)); fail(); } catch (IllegalArgumentException ex) {} } public void testSetEnd_RI3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setEnd(null); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } //----------------------------------------------------------------------- public void testSetDurationAfterStart_long1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setDurationAfterStart(123L); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME1 + 123L, test.getEndMillis()); } public void testSeDurationAfterStart_long2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setDurationAfterStart(-1); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetDurationAfterStart_RI1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setDurationAfterStart(new Duration(123L)); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME1 + 123L, test.getEndMillis()); } public void testSeDurationAfterStart_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setDurationAfterStart(new Duration(-1)); fail(); } catch (IllegalArgumentException ex) {} } public void testSetDurationAfterStart_RI3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setDurationAfterStart(null); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME1, test.getEndMillis()); } //----------------------------------------------------------------------- public void testSetDurationBeforeEnd_long1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setDurationBeforeEnd(123L); assertEquals(TEST_TIME2 - 123L, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } public void testSeDurationBeforeEnd_long2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setDurationBeforeEnd(-1); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSetDurationBeforeEnd_RI1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setDurationBeforeEnd(new Duration(123L)); assertEquals(TEST_TIME2 - 123L, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } public void testSeDurationBeforeEnd_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setDurationBeforeEnd(new Duration(-1)); fail(); } catch (IllegalArgumentException ex) {} } public void testSetDurationBeforeEnd_RI3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setDurationBeforeEnd(null); assertEquals(TEST_TIME2, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } //----------------------------------------------------------------------- public void testSetPeriodAfterStart_RI1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setPeriodAfterStart(new Period(123L)); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME1 + 123L, test.getEndMillis()); } public void testSePeriodAfterStart_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setPeriodAfterStart(new Period(-1L)); fail(); } catch (IllegalArgumentException ex) {} } public void testSetPeriodAfterStart_RI3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setPeriodAfterStart(null); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME1, test.getEndMillis()); } //----------------------------------------------------------------------- public void testSetPeriodBeforeEnd_RI1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setPeriodBeforeEnd(new Period(123L)); assertEquals(TEST_TIME2 - 123L, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } public void testSePeriodBeforeEnd_RI2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); try { test.setPeriodBeforeEnd(new Period(-1L)); fail(); } catch (IllegalArgumentException ex) {} } public void testSetPeriodBeforeEnd_RI3() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); test.setPeriodBeforeEnd(null); assertEquals(TEST_TIME2, test.getStartMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); } } joda-time-2.3/src/test/java/org/joda/time/TestAbstractPartial.java0000644000175000017500000001677411564251363024520 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractPartial; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractPartialFieldProperty; /** * This class is a Junit unit test for YearMonthDay. * * @author Stephen Colebourne */ public class TestAbstractPartial extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestAbstractPartial.class); } public TestAbstractPartial(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testGetValue() throws Throwable { MockPartial mock = new MockPartial(); assertEquals(1970, mock.getValue(0)); assertEquals(1, mock.getValue(1)); try { mock.getValue(-1); fail(); } catch (IndexOutOfBoundsException ex) {} try { mock.getValue(2); fail(); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() throws Throwable { MockPartial mock = new MockPartial(); int[] vals = mock.getValues(); assertEquals(2, vals.length); assertEquals(1970, vals[0]); assertEquals(1, vals[1]); } public void testGetField() throws Throwable { MockPartial mock = new MockPartial(); assertEquals(BuddhistChronology.getInstanceUTC().year(), mock.getField(0)); assertEquals(BuddhistChronology.getInstanceUTC().monthOfYear(), mock.getField(1)); try { mock.getField(-1); fail(); } catch (IndexOutOfBoundsException ex) {} try { mock.getField(2); fail(); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldType() throws Throwable { MockPartial mock = new MockPartial(); assertEquals(DateTimeFieldType.year(), mock.getFieldType(0)); assertEquals(DateTimeFieldType.monthOfYear(), mock.getFieldType(1)); try { mock.getFieldType(-1); fail(); } catch (IndexOutOfBoundsException ex) {} try { mock.getFieldType(2); fail(); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() throws Throwable { MockPartial mock = new MockPartial(); DateTimeFieldType[] vals = mock.getFieldTypes(); assertEquals(2, vals.length); assertEquals(DateTimeFieldType.year(), vals[0]); assertEquals(DateTimeFieldType.monthOfYear(), vals[1]); } public void testGetPropertyEquals() throws Throwable { MockProperty0 prop0 = new MockProperty0(); assertEquals(true, prop0.equals(prop0)); assertEquals(true, prop0.equals(new MockProperty0())); assertEquals(false, prop0.equals(new MockProperty1())); assertEquals(false, prop0.equals(new MockProperty0Val())); assertEquals(false, prop0.equals(new MockProperty0Field())); assertEquals(false, prop0.equals(new MockProperty0Chrono())); assertEquals(false, prop0.equals("")); assertEquals(false, prop0.equals(null)); } //----------------------------------------------------------------------- static class MockPartial extends AbstractPartial { int[] val = new int[] {1970, 1}; MockPartial() { super(); } protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case 0: return chrono.year(); case 1: return chrono.monthOfYear(); default: throw new IndexOutOfBoundsException(); } } public int size() { return 2; } public int getValue(int index) { return val[index]; } public void setValue(int index, int value) { val[index] = value; } public Chronology getChronology() { return BuddhistChronology.getInstanceUTC(); } } static class MockProperty0 extends AbstractPartialFieldProperty { MockPartial partial = new MockPartial(); public DateTimeField getField() { return partial.getField(0); } public ReadablePartial getReadablePartial() { return partial; } public int get() { return partial.getValue(0); } } static class MockProperty1 extends AbstractPartialFieldProperty { MockPartial partial = new MockPartial(); public DateTimeField getField() { return partial.getField(1); } public ReadablePartial getReadablePartial() { return partial; } public int get() { return partial.getValue(1); } } static class MockProperty0Field extends MockProperty0 { public DateTimeField getField() { return BuddhistChronology.getInstanceUTC().hourOfDay(); } } static class MockProperty0Val extends MockProperty0 { public int get() { return 99; } } static class MockProperty0Chrono extends MockProperty0 { public ReadablePartial getReadablePartial() { return new MockPartial() { public Chronology getChronology() { return ISOChronology.getInstanceUTC(); } }; } } } joda-time-2.3/src/test/java/org/joda/time/MockNullZoneChronology.java0000644000175000017500000000241511564251363025207 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.time.chrono.BaseChronology; import org.joda.time.chrono.ISOChronology; /** * Mock class for unit testing. * * @author Stephen Colebourne */ class MockNullZoneChronology extends BaseChronology { public DateTimeZone getZone() { return null; } public Chronology withUTC() { return this; } public Chronology withZone(DateTimeZone zone) { return this; } public DateTimeField dayOfMonth() { // for DateMidnight test return ISOChronology.getInstance().dayOfMonth(); } public String toString() { return ""; } } joda-time-2.3/src/test/java/org/joda/time/TestDateTimeConstants.java0000644000175000017500000001015011564251363025007 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case. * * @author Stephen Colebourne */ public class TestDateTimeConstants extends TestCase { /** * The main method for this test program. * @param args command line arguments. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * TestSuite is a junit required method. */ public static TestSuite suite() { return new TestSuite(TestDateTimeConstants.class); } /** * TestDateTimeComparator constructor. * @param name */ public TestDateTimeConstants(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { DateTimeConstants c = new DateTimeConstants() { }; c.toString(); } public void testHalfdaysOfDay() { assertEquals(0, DateTimeConstants.AM); assertEquals(1, DateTimeConstants.PM); } public void testDaysOfWeek() { assertEquals(1, DateTimeConstants.MONDAY); assertEquals(2, DateTimeConstants.TUESDAY); assertEquals(3, DateTimeConstants.WEDNESDAY); assertEquals(4, DateTimeConstants.THURSDAY); assertEquals(5, DateTimeConstants.FRIDAY); assertEquals(6, DateTimeConstants.SATURDAY); assertEquals(7, DateTimeConstants.SUNDAY); } public void testMonthsOfYear() { assertEquals(1, DateTimeConstants.JANUARY); assertEquals(2, DateTimeConstants.FEBRUARY); assertEquals(3, DateTimeConstants.MARCH); assertEquals(4, DateTimeConstants.APRIL); assertEquals(5, DateTimeConstants.MAY); assertEquals(6, DateTimeConstants.JUNE); assertEquals(7, DateTimeConstants.JULY); assertEquals(8, DateTimeConstants.AUGUST); assertEquals(9, DateTimeConstants.SEPTEMBER); assertEquals(10, DateTimeConstants.OCTOBER); assertEquals(11, DateTimeConstants.NOVEMBER); assertEquals(12, DateTimeConstants.DECEMBER); } public void testEras() { assertEquals(0, DateTimeConstants.BC); assertEquals(0, DateTimeConstants.BCE); assertEquals(1, DateTimeConstants.AD); assertEquals(1, DateTimeConstants.CE); } public void testMaths() { assertEquals(1000, DateTimeConstants.MILLIS_PER_SECOND); assertEquals(60 * 1000, DateTimeConstants.MILLIS_PER_MINUTE); assertEquals(60 * 60 * 1000, DateTimeConstants.MILLIS_PER_HOUR); assertEquals(24 * 60 * 60 * 1000, DateTimeConstants.MILLIS_PER_DAY); assertEquals(7 * 24 * 60 * 60 * 1000, DateTimeConstants.MILLIS_PER_WEEK); assertEquals(60, DateTimeConstants.SECONDS_PER_MINUTE); assertEquals(60 * 60, DateTimeConstants.SECONDS_PER_HOUR); assertEquals(24 * 60 * 60, DateTimeConstants.SECONDS_PER_DAY); assertEquals(7 * 24 * 60 * 60, DateTimeConstants.SECONDS_PER_WEEK); assertEquals(60, DateTimeConstants.MINUTES_PER_HOUR); assertEquals(24 * 60, DateTimeConstants.MINUTES_PER_DAY); assertEquals(7 * 24 * 60, DateTimeConstants.MINUTES_PER_WEEK); assertEquals(24, DateTimeConstants.HOURS_PER_DAY); assertEquals(7 * 24, DateTimeConstants.HOURS_PER_WEEK); assertEquals(7, DateTimeConstants.DAYS_PER_WEEK); } } joda-time-2.3/src/test/java/org/joda/time/TestPeriod_Basics.java0000644000175000017500000020166311720737641024141 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.BasePeriod; import org.joda.time.format.PeriodFormat; import org.joda.time.format.PeriodFormatter; /** * This class is a Junit unit test for Duration. * * @author Stephen Colebourne */ public class TestPeriod_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) //private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPeriod_Basics.class); } public TestPeriod_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGetPeriodType() { Period test = new Period(0L); assertEquals(PeriodType.standard(), test.getPeriodType()); } public void testGetMethods() { Period test = new Period(0L); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testValueIndexMethods() { Period test = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); assertEquals(6, test.size()); assertEquals(1, test.getValue(0)); assertEquals(4, test.getValue(1)); assertEquals(5, test.getValue(2)); assertEquals(6, test.getValue(3)); assertEquals(7, test.getValue(4)); assertEquals(8, test.getValue(5)); assertEquals(true, Arrays.equals(new int[] {1, 4, 5, 6, 7, 8}, test.getValues())); } public void testTypeIndexMethods() { Period test = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); assertEquals(6, test.size()); assertEquals(DurationFieldType.years(), test.getFieldType(0)); assertEquals(DurationFieldType.days(), test.getFieldType(1)); assertEquals(DurationFieldType.hours(), test.getFieldType(2)); assertEquals(DurationFieldType.minutes(), test.getFieldType(3)); assertEquals(DurationFieldType.seconds(), test.getFieldType(4)); assertEquals(DurationFieldType.millis(), test.getFieldType(5)); assertEquals(true, Arrays.equals(new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.days(), DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis()}, test.getFieldTypes())); } public void testIsSupported() { Period test = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); assertEquals(true, test.isSupported(DurationFieldType.years())); assertEquals(false, test.isSupported(DurationFieldType.months())); assertEquals(false, test.isSupported(DurationFieldType.weeks())); assertEquals(true, test.isSupported(DurationFieldType.days())); assertEquals(true, test.isSupported(DurationFieldType.hours())); assertEquals(true, test.isSupported(DurationFieldType.minutes())); assertEquals(true, test.isSupported(DurationFieldType.seconds())); assertEquals(true, test.isSupported(DurationFieldType.millis())); } public void testIndexOf() { Period test = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); assertEquals(0, test.indexOf(DurationFieldType.years())); assertEquals(-1, test.indexOf(DurationFieldType.months())); assertEquals(-1, test.indexOf(DurationFieldType.weeks())); assertEquals(1, test.indexOf(DurationFieldType.days())); assertEquals(2, test.indexOf(DurationFieldType.hours())); assertEquals(3, test.indexOf(DurationFieldType.minutes())); assertEquals(4, test.indexOf(DurationFieldType.seconds())); assertEquals(5, test.indexOf(DurationFieldType.millis())); } public void testGet() { Period test = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime()); assertEquals(1, test.get(DurationFieldType.years())); assertEquals(0, test.get(DurationFieldType.months())); assertEquals(0, test.get(DurationFieldType.weeks())); assertEquals(4, test.get(DurationFieldType.days())); assertEquals(5, test.get(DurationFieldType.hours())); assertEquals(6, test.get(DurationFieldType.minutes())); assertEquals(7, test.get(DurationFieldType.seconds())); assertEquals(8, test.get(DurationFieldType.millis())); } public void testEqualsHashCode() { Period test1 = new Period(123L); Period test2 = new Period(123L); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); Period test3 = new Period(321L); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockPeriod(123L))); assertEquals(false, test1.equals(new Period(123L, PeriodType.dayTime()))); } class MockPeriod extends BasePeriod { public MockPeriod(long value) { super(value, null, null); } } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Period test = new Period(123L); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Period result = (Period) ois.readObject(); ois.close(); assertEquals(test, result); } // //----------------------------------------------------------------------- // public void testAddTo1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, 1); // assertEquals(expected, added); // } // // public void testAddTo2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, -2); // assertEquals(expected, added); // } // // public void testAddTo3() { // long expected = TEST_TIME_NOW; // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, 0); // assertEquals(expected, added); // } // // public void testAddTo4() { // long expected = TEST_TIME_NOW + 100L; // Period test = new Period(100L); // long added = test.addTo(TEST_TIME_NOW, 1); // assertEquals(expected, added); // } // // //----------------------------------------------------------------------- // public void testAddToWithChronology1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); // long added = test.addTo(TEST_TIME_NOW, 1, ISOChronology.getInstance()); // assertEquals(expected, added); // } // // public void testAddToWithChronology2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstanceUTC().years().add(expected, -2); // expected = ISOChronology.getInstanceUTC().months().add(expected, -4); // expected = ISOChronology.getInstanceUTC().weeks().add(expected, -6); // expected = ISOChronology.getInstanceUTC().days().add(expected, -8); // expected = ISOChronology.getInstanceUTC().hours().add(expected, -10); // expected = ISOChronology.getInstanceUTC().minutes().add(expected, -12); // expected = ISOChronology.getInstanceUTC().seconds().add(expected, -14); // expected = ISOChronology.getInstanceUTC().millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // long added = test.addTo(TEST_TIME_NOW, -2, ISOChronology.getInstanceUTC()); // local specified so use it // assertEquals(expected, added); // } // // public void testAddToWithChronology3() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // long added = test.addTo(TEST_TIME_NOW, -2, null); // no chrono specified so use default // assertEquals(expected, added); // } // // //----------------------------------------------------------------------- // public void testAddToRI1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); // DateTime added = test.addTo(new Instant(), 1); // Instant has no time zone, use default // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(), added.getChronology()); // } // // public void testAddToRI2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(new Instant(), -2); // Instant has no time zone, use default // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(), added.getChronology()); // } // // public void testAddToRI3() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstanceUTC().years().add(expected, -2); // expected = ISOChronology.getInstanceUTC().months().add(expected, -4); // expected = ISOChronology.getInstanceUTC().weeks().add(expected, -6); // expected = ISOChronology.getInstanceUTC().days().add(expected, -8); // expected = ISOChronology.getInstanceUTC().hours().add(expected, -10); // expected = ISOChronology.getInstanceUTC().minutes().add(expected, -12); // expected = ISOChronology.getInstanceUTC().seconds().add(expected, -14); // expected = ISOChronology.getInstanceUTC().millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(new DateTime(ISOChronology.getInstanceUTC()), -2); // DateTime has UTC time zone // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstanceUTC(), added.getChronology()); // } // // public void testAddToRI4() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance(PARIS).years().add(expected, -2); // expected = ISOChronology.getInstance(PARIS).months().add(expected, -4); // expected = ISOChronology.getInstance(PARIS).weeks().add(expected, -6); // expected = ISOChronology.getInstance(PARIS).days().add(expected, -8); // expected = ISOChronology.getInstance(PARIS).hours().add(expected, -10); // expected = ISOChronology.getInstance(PARIS).minutes().add(expected, -12); // expected = ISOChronology.getInstance(PARIS).seconds().add(expected, -14); // expected = ISOChronology.getInstance(PARIS).millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(new DateTime(PARIS), -2); // DateTime has PARIS time zone // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(PARIS), added.getChronology()); // } // // public void testAddToRI5() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // DateTime added = test.addTo(null, -2); // null has no time zone, use default // assertEquals(expected, added.getMillis()); // assertEquals(ISOChronology.getInstance(), added.getChronology()); // } // // //----------------------------------------------------------------------- // public void testAddIntoRWI1() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, 1); // expected = ISOChronology.getInstance().months().add(expected, 2); // expected = ISOChronology.getInstance().weeks().add(expected, 3); // expected = ISOChronology.getInstance().days().add(expected, 4); // expected = ISOChronology.getInstance().hours().add(expected, 5); // expected = ISOChronology.getInstance().minutes().add(expected, 6); // expected = ISOChronology.getInstance().seconds().add(expected, 7); // expected = ISOChronology.getInstance().millis().add(expected, 8); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); // MutableDateTime mdt = new MutableDateTime(); // test.addInto(mdt, 1); // assertEquals(expected, mdt.getMillis()); // } // // public void testAddIntoRWI2() { // long expected = TEST_TIME_NOW; // expected = ISOChronology.getInstance().years().add(expected, -2); // expected = ISOChronology.getInstance().months().add(expected, -4); // expected = ISOChronology.getInstance().weeks().add(expected, -6); // expected = ISOChronology.getInstance().days().add(expected, -8); // expected = ISOChronology.getInstance().hours().add(expected, -10); // expected = ISOChronology.getInstance().minutes().add(expected, -12); // expected = ISOChronology.getInstance().seconds().add(expected, -14); // expected = ISOChronology.getInstance().millis().add(expected, -16); // // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); // MutableDateTime mdt = new MutableDateTime(); // test.addInto(mdt, -2); // MutableDateTime has a chronology, use it // assertEquals(expected, mdt.getMillis()); // } // // public void testAddIntoRWI3() { // Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); // try { // test.addInto(null, 1); // fail(); // } catch (IllegalArgumentException ex) {} // } //----------------------------------------------------------------------- public void testToString() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); assertEquals("P1Y2M3W4DT5H6M7.008S", test.toString()); test = new Period(0, 0, 0, 0, 0, 0, 0, 0); assertEquals("PT0S", test.toString()); test = new Period(12345L); assertEquals("PT12.345S", test.toString()); } //----------------------------------------------------------------------- public void testToString_PeriodFormatter() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); assertEquals("1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", test.toString(PeriodFormat.getDefault())); test = new Period(0, 0, 0, 0, 0, 0, 0, 0); assertEquals("0 milliseconds", test.toString(PeriodFormat.getDefault())); } public void testToString_nullPeriodFormatter() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); assertEquals("P1Y2M3W4DT5H6M7.008S", test.toString((PeriodFormatter) null)); } //----------------------------------------------------------------------- public void testToPeriod() { Period test = new Period(123L); Period result = test.toPeriod(); assertSame(test, result); } public void testToMutablePeriod() { Period test = new Period(123L); MutablePeriod result = test.toMutablePeriod(); assertEquals(test, result); } //----------------------------------------------------------------------- // public void testToDurationMillisFrom() { // Period test = new Period(123L); // assertEquals(123L, test.toDurationMillisFrom(0L, null)); // } public void testToDurationFrom() { Period test = new Period(123L); assertEquals(new Duration(123L), test.toDurationFrom(new Instant(0L))); } public void testToDurationTo() { Period test = new Period(123L); assertEquals(new Duration(123L), test.toDurationTo(new Instant(123L))); } //----------------------------------------------------------------------- public void testWithPeriodType1() { Period test = new Period(123L); Period result = test.withPeriodType(PeriodType.standard()); assertSame(test, result); } public void testWithPeriodType2() { Period test = new Period(3123L); Period result = test.withPeriodType(PeriodType.dayTime()); assertEquals(3, result.getSeconds()); assertEquals(123, result.getMillis()); assertEquals(PeriodType.dayTime(), result.getPeriodType()); } public void testWithPeriodType3() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard()); try { test.withPeriodType(PeriodType.dayTime()); fail(); } catch (IllegalArgumentException ex) {} } public void testWithPeriodType4() { Period test = new Period(3123L); Period result = test.withPeriodType(null); assertEquals(3, result.getSeconds()); assertEquals(123, result.getMillis()); assertEquals(PeriodType.standard(), result.getPeriodType()); } public void testWithPeriodType5() { Period test = new Period(1, 2, 0, 4, 5, 6, 7, 8, PeriodType.standard()); Period result = test.withPeriodType(PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), result.getPeriodType()); assertEquals(1, result.getYears()); assertEquals(2, result.getMonths()); assertEquals(0, result.getWeeks()); assertEquals(4, result.getDays()); assertEquals(5, result.getHours()); assertEquals(6, result.getMinutes()); assertEquals(7, result.getSeconds()); assertEquals(8, result.getMillis()); } //----------------------------------------------------------------------- public void testWithFields1() { Period test1 = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period test2 = new Period(0, 0, 0, 0, 0, 0, 0, 9, PeriodType.millis()); Period result = test1.withFields(test2); assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 8), test1); assertEquals(new Period(0, 0, 0, 0, 0, 0, 0, 9, PeriodType.millis()), test2); assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 9), result); } public void testWithFields2() { Period test1 = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period test2 = null; Period result = test1.withFields(test2); assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 8), test1); assertSame(test1, result); } public void testWithFields3() { Period test1 = new Period(0, 0, 0, 0, 0, 0, 0, 9, PeriodType.millis()); Period test2 = new Period(1, 2, 3, 4, 5, 6, 7, 8); try { test1.withFields(test2); fail(); } catch (IllegalArgumentException ex) {} assertEquals(new Period(0, 0, 0, 0, 0, 0, 0, 9, PeriodType.millis()), test1); assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 8), test2); } //----------------------------------------------------------------------- public void testWithField1() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period result = test.withField(DurationFieldType.years(), 6); assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 8), test); assertEquals(new Period(6, 2, 3, 4, 5, 6, 7, 8), result); } public void testWithField2() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField3() { Period test = new Period(0, 0, 0, 0, 5, 6, 7, 8, PeriodType.time()); try { test.withField(DurationFieldType.years(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField4() { Period test = new Period(0, 0, 0, 0, 5, 6, 7, 8, PeriodType.time()); Period result = test.withField(DurationFieldType.years(), 0); assertEquals(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded1() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period result = test.withFieldAdded(DurationFieldType.years(), 6); assertEquals(new Period(1, 2, 3, 4, 5, 6, 7, 8), test); assertEquals(new Period(7, 2, 3, 4, 5, 6, 7, 8), result); } public void testWithFieldAdded2() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded3() { Period test = new Period(0, 0, 0, 0, 5, 6, 7, 8, PeriodType.time()); try { test.withFieldAdded(DurationFieldType.years(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded4() { Period test = new Period(0, 0, 0, 0, 5, 6, 7, 8, PeriodType.time()); Period result = test.withFieldAdded(DurationFieldType.years(), 0); assertEquals(test, result); } //----------------------------------------------------------------------- public void testPeriodStatics() { Period test; test = Period.years(1); assertEquals(test, new Period(1, 0, 0, 0, 0, 0, 0, 0, PeriodType.standard())); test = Period.months(1); assertEquals(test, new Period(0, 1, 0, 0, 0, 0, 0, 0, PeriodType.standard())); test = Period.weeks(1); assertEquals(test, new Period(0, 0, 1, 0, 0, 0, 0, 0, PeriodType.standard())); test = Period.days(1); assertEquals(test, new Period(0, 0, 0, 1, 0, 0, 0, 0, PeriodType.standard())); test = Period.hours(1); assertEquals(test, new Period(0, 0, 0, 0, 1, 0, 0, 0, PeriodType.standard())); test = Period.minutes(1); assertEquals(test, new Period(0, 0, 0, 0, 0, 1, 0, 0, PeriodType.standard())); test = Period.seconds(1); assertEquals(test, new Period(0, 0, 0, 0, 0, 0, 1, 0, PeriodType.standard())); test = Period.millis(1); assertEquals(test, new Period(0, 0, 0, 0, 0, 0, 0, 1, PeriodType.standard())); } //----------------------------------------------------------------------- public void testWith() { Period test; test = Period.years(5).withYears(1); assertEquals(test, new Period(1, 0, 0, 0, 0, 0, 0, 0, PeriodType.standard())); test = Period.months(5).withMonths(1); assertEquals(test, new Period(0, 1, 0, 0, 0, 0, 0, 0, PeriodType.standard())); test = Period.weeks(5).withWeeks(1); assertEquals(test, new Period(0, 0, 1, 0, 0, 0, 0, 0, PeriodType.standard())); test = Period.days(5).withDays(1); assertEquals(test, new Period(0, 0, 0, 1, 0, 0, 0, 0, PeriodType.standard())); test = Period.hours(5).withHours(1); assertEquals(test, new Period(0, 0, 0, 0, 1, 0, 0, 0, PeriodType.standard())); test = Period.minutes(5).withMinutes(1); assertEquals(test, new Period(0, 0, 0, 0, 0, 1, 0, 0, PeriodType.standard())); test = Period.seconds(5).withSeconds(1); assertEquals(test, new Period(0, 0, 0, 0, 0, 0, 1, 0, PeriodType.standard())); test = Period.millis(5).withMillis(1); assertEquals(test, new Period(0, 0, 0, 0, 0, 0, 0, 1, PeriodType.standard())); test = new Period(0L, PeriodType.millis()); try { test.withYears(1); fail(); } catch (UnsupportedOperationException ex) {} } //----------------------------------------------------------------------- public void testPlus() { Period base = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period baseDaysOnly = new Period(0, 0, 0, 10, 0, 0, 0, 0, PeriodType.days()); Period test = base.plus((ReadablePeriod) null); assertSame(base, test); test = base.plus(Period.years(10)); assertEquals(11, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = base.plus(Years.years(10)); assertEquals(11, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = base.plus(Period.days(10)); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = baseDaysOnly.plus(Period.years(0)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(10, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); test = baseDaysOnly.plus(baseDaysOnly); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(20, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); try { baseDaysOnly.plus(Period.years(1)); fail(); } catch (UnsupportedOperationException ex) {} try { Period.days(Integer.MAX_VALUE).plus(Period.days(1)); fail(); } catch (ArithmeticException ex) {} try { Period.days(Integer.MIN_VALUE).plus(Period.days(-1)); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void testMinus() { Period base = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period baseDaysOnly = new Period(0, 0, 0, 10, 0, 0, 0, 0, PeriodType.days()); Period test = base.minus((ReadablePeriod) null); assertSame(base, test); test = base.minus(Period.years(10)); assertEquals(-9, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = base.minus(Years.years(10)); assertEquals(-9, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = base.minus(Period.days(10)); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(-6, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = baseDaysOnly.minus(Period.years(0)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(10, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); test = baseDaysOnly.minus(baseDaysOnly); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); try { baseDaysOnly.minus(Period.years(1)); fail(); } catch (UnsupportedOperationException ex) {} try { Period.days(Integer.MAX_VALUE).minus(Period.days(-1)); fail(); } catch (ArithmeticException ex) {} try { Period.days(Integer.MIN_VALUE).minus(Period.days(1)); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void testPlusFields() { Period test; test = Period.years(1).plusYears(1); assertEquals(new Period(2, 0, 0, 0, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.months(1).plusMonths(1); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.weeks(1).plusWeeks(1); assertEquals(new Period(0, 0, 2, 0, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.days(1).plusDays(1); assertEquals(new Period(0, 0, 0, 2, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.hours(1).plusHours(1); assertEquals(new Period(0, 0, 0, 0, 2, 0, 0, 0, PeriodType.standard()), test); test = Period.minutes(1).plusMinutes(1); assertEquals(new Period(0, 0, 0, 0, 0, 2, 0, 0, PeriodType.standard()), test); test = Period.seconds(1).plusSeconds(1); assertEquals(new Period(0, 0, 0, 0, 0, 0, 2, 0, PeriodType.standard()), test); test = Period.millis(1).plusMillis(1); assertEquals(new Period(0, 0, 0, 0, 0, 0, 0, 2, PeriodType.standard()), test); test = new Period(0L, PeriodType.millis()); try { test.plusYears(1); fail(); } catch (UnsupportedOperationException ex) {} } public void testPlusFieldsZero() { Period test, result; test = Period.years(1); result = test.plusYears(0); assertSame(test, result); test = Period.months(1); result = test.plusMonths(0); assertSame(test, result); test = Period.weeks(1); result = test.plusWeeks(0); assertSame(test, result); test = Period.days(1); result = test.plusDays(0); assertSame(test, result); test = Period.hours(1); result = test.plusHours(0); assertSame(test, result); test = Period.minutes(1); result = test.plusMinutes(0); assertSame(test, result); test = Period.seconds(1); result = test.plusSeconds(0); assertSame(test, result); test = Period.millis(1); result = test.plusMillis(0); assertSame(test, result); } public void testMinusFields() { Period test; test = Period.years(3).minusYears(1); assertEquals(new Period(2, 0, 0, 0, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.months(3).minusMonths(1); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.weeks(3).minusWeeks(1); assertEquals(new Period(0, 0, 2, 0, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.days(3).minusDays(1); assertEquals(new Period(0, 0, 0, 2, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.hours(3).minusHours(1); assertEquals(new Period(0, 0, 0, 0, 2, 0, 0, 0, PeriodType.standard()), test); test = Period.minutes(3).minusMinutes(1); assertEquals(new Period(0, 0, 0, 0, 0, 2, 0, 0, PeriodType.standard()), test); test = Period.seconds(3).minusSeconds(1); assertEquals(new Period(0, 0, 0, 0, 0, 0, 2, 0, PeriodType.standard()), test); test = Period.millis(3).minusMillis(1); assertEquals(new Period(0, 0, 0, 0, 0, 0, 0, 2, PeriodType.standard()), test); test = new Period(0L, PeriodType.millis()); try { test.minusYears(1); fail(); } catch (UnsupportedOperationException ex) {} } //----------------------------------------------------------------------- public void testMultipliedBy() { Period base = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period test = base.multipliedBy(1); assertSame(base, test); test = base.multipliedBy(0); assertEquals(Period.ZERO, test); test = base.multipliedBy(2); assertEquals(2, test.getYears()); assertEquals(4, test.getMonths()); assertEquals(6, test.getWeeks()); assertEquals(8, test.getDays()); assertEquals(10, test.getHours()); assertEquals(12, test.getMinutes()); assertEquals(14, test.getSeconds()); assertEquals(16, test.getMillis()); test = base.multipliedBy(3); assertEquals(3, test.getYears()); assertEquals(6, test.getMonths()); assertEquals(9, test.getWeeks()); assertEquals(12, test.getDays()); assertEquals(15, test.getHours()); assertEquals(18, test.getMinutes()); assertEquals(21, test.getSeconds()); assertEquals(24, test.getMillis()); test = base.multipliedBy(-4); assertEquals(-4, test.getYears()); assertEquals(-8, test.getMonths()); assertEquals(-12, test.getWeeks()); assertEquals(-16, test.getDays()); assertEquals(-20, test.getHours()); assertEquals(-24, test.getMinutes()); assertEquals(-28, test.getSeconds()); assertEquals(-32, test.getMillis()); try { Period.days(Integer.MAX_VALUE).multipliedBy(2); fail(); } catch (ArithmeticException ex) {} try { Period.days(Integer.MIN_VALUE).multipliedBy(2); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void testNegated() { Period base = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period test = Period.ZERO.negated(); assertEquals(Period.ZERO, test); test = base.negated(); assertEquals(-1, test.getYears()); assertEquals(-2, test.getMonths()); assertEquals(-3, test.getWeeks()); assertEquals(-4, test.getDays()); assertEquals(-5, test.getHours()); assertEquals(-6, test.getMinutes()); assertEquals(-7, test.getSeconds()); assertEquals(-8, test.getMillis()); test = Period.days(Integer.MAX_VALUE).negated(); assertEquals(-Integer.MAX_VALUE, test.getDays()); try { Period.days(Integer.MIN_VALUE).negated(); fail(); } catch (ArithmeticException ex) {} } //----------------------------------------------------------------------- public void testToStandardWeeks() { Period test = new Period(0, 0, 3, 4, 5, 6, 7, 8); assertEquals(3, test.toStandardWeeks().getWeeks()); test = new Period(0, 0, 3, 7, 0, 0, 0, 0); assertEquals(4, test.toStandardWeeks().getWeeks()); test = new Period(0, 0, 0, 6, 23, 59, 59, 1000); assertEquals(1, test.toStandardWeeks().getWeeks()); test = new Period(0, 0, Integer.MAX_VALUE, 0, 0, 0, 0, 0); assertEquals(Integer.MAX_VALUE, test.toStandardWeeks().getWeeks()); test = new Period(0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); long intMax = Integer.MAX_VALUE; BigInteger expected = BigInteger.valueOf(intMax); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_SECOND)); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_MINUTE)); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_HOUR)); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_DAY)); expected = expected.divide(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_WEEK)); assertTrue(expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0); assertEquals(expected.longValue(), test.toStandardWeeks().getWeeks()); test = new Period(0, 0, Integer.MAX_VALUE, 7, 0, 0, 0, 0); try { test.toStandardWeeks(); fail(); } catch (ArithmeticException ex) {} } public void testToStandardWeeks_years() { Period test = Period.years(1); try { test.toStandardWeeks(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(-1); try { test.toStandardWeeks(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(0); assertEquals(0, test.toStandardWeeks().getWeeks()); } public void testToStandardWeeks_months() { Period test = Period.months(1); try { test.toStandardWeeks(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardWeeks(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardWeeks().getWeeks()); } //----------------------------------------------------------------------- public void testToStandardDays() { Period test = new Period(0, 0, 0, 4, 5, 6, 7, 8); assertEquals(4, test.toStandardDays().getDays()); test = new Period(0, 0, 1, 4, 0, 0, 0, 0); assertEquals(11, test.toStandardDays().getDays()); test = new Period(0, 0, 0, 0, 23, 59, 59, 1000); assertEquals(1, test.toStandardDays().getDays()); test = new Period(0, 0, 0, Integer.MAX_VALUE, 0, 0, 0, 0); assertEquals(Integer.MAX_VALUE, test.toStandardDays().getDays()); test = new Period(0, 0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); long intMax = Integer.MAX_VALUE; BigInteger expected = BigInteger.valueOf(intMax); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_SECOND)); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_MINUTE)); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_HOUR)); expected = expected.divide(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_DAY)); assertTrue(expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0); assertEquals(expected.longValue(), test.toStandardDays().getDays()); test = new Period(0, 0, 0, Integer.MAX_VALUE, 24, 0, 0, 0); try { test.toStandardDays(); fail(); } catch (ArithmeticException ex) {} } public void testToStandardDays_years() { Period test = Period.years(1); try { test.toStandardDays(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(-1); try { test.toStandardDays(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(0); assertEquals(0, test.toStandardDays().getDays()); } public void testToStandardDays_months() { Period test = Period.months(1); try { test.toStandardDays(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardDays(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardDays().getDays()); } //----------------------------------------------------------------------- public void testToStandardHours() { Period test = new Period(0, 0, 0, 0, 5, 6, 7, 8); assertEquals(5, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 1, 5, 0, 0, 0); assertEquals(29, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, 0, 59, 59, 1000); assertEquals(1, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, Integer.MAX_VALUE, 0, 0, 0); assertEquals(Integer.MAX_VALUE, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); long intMax = Integer.MAX_VALUE; BigInteger expected = BigInteger.valueOf(intMax); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_SECOND)); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_MINUTE)); expected = expected.divide(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_HOUR)); assertTrue(expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0); assertEquals(expected.longValue(), test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, Integer.MAX_VALUE, 60, 0, 0); try { test.toStandardHours(); fail(); } catch (ArithmeticException ex) {} } public void testToStandardHours_years() { Period test = Period.years(1); try { test.toStandardHours(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(-1); try { test.toStandardHours(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(0); assertEquals(0, test.toStandardHours().getHours()); } public void testToStandardHours_months() { Period test = Period.months(1); try { test.toStandardHours(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardHours(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardHours().getHours()); } //----------------------------------------------------------------------- public void testToStandardMinutes() { Period test = new Period(0, 0, 0, 0, 0, 6, 7, 8); assertEquals(6, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 1, 6, 0, 0); assertEquals(66, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, 0, 59, 1000); assertEquals(1, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, Integer.MAX_VALUE, 0, 0); assertEquals(Integer.MAX_VALUE, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE); long intMax = Integer.MAX_VALUE; BigInteger expected = BigInteger.valueOf(intMax); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_SECOND)); expected = expected.divide(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_MINUTE)); assertTrue(expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0); assertEquals(expected.longValue(), test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, Integer.MAX_VALUE, 60, 0); try { test.toStandardMinutes(); fail(); } catch (ArithmeticException ex) {} } public void testToStandardMinutes_years() { Period test = Period.years(1); try { test.toStandardMinutes(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(-1); try { test.toStandardMinutes(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(0); assertEquals(0, test.toStandardMinutes().getMinutes()); } public void testToStandardMinutes_months() { Period test = Period.months(1); try { test.toStandardMinutes(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardMinutes(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardMinutes().getMinutes()); } //----------------------------------------------------------------------- public void testToStandardSeconds() { Period test = new Period(0, 0, 0, 0, 0, 0, 7, 8); assertEquals(7, test.toStandardSeconds().getSeconds()); test = new Period(0, 0, 0, 0, 0, 1, 3, 0); assertEquals(63, test.toStandardSeconds().getSeconds()); test = new Period(0, 0, 0, 0, 0, 0, 0, 1000); assertEquals(1, test.toStandardSeconds().getSeconds()); test = new Period(0, 0, 0, 0, 0, 0, Integer.MAX_VALUE, 0); assertEquals(Integer.MAX_VALUE, test.toStandardSeconds().getSeconds()); test = new Period(0, 0, 0, 0, 0, 0, 20, Integer.MAX_VALUE); long expected = 20; expected += ((long) Integer.MAX_VALUE) / DateTimeConstants.MILLIS_PER_SECOND; assertEquals(expected, test.toStandardSeconds().getSeconds()); test = new Period(0, 0, 0, 0, 0, 0, Integer.MAX_VALUE, 1000); try { test.toStandardSeconds(); fail(); } catch (ArithmeticException ex) {} } public void testToStandardSeconds_years() { Period test = Period.years(1); try { test.toStandardSeconds(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(-1); try { test.toStandardSeconds(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(0); assertEquals(0, test.toStandardSeconds().getSeconds()); } public void testToStandardSeconds_months() { Period test = Period.months(1); try { test.toStandardSeconds(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardSeconds(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardSeconds().getSeconds()); } //----------------------------------------------------------------------- public void testToStandardDuration() { Period test = new Period(0, 0, 0, 0, 0, 0, 0, 8); assertEquals(8, test.toStandardDuration().getMillis()); test = new Period(0, 0, 0, 0, 0, 0, 1, 20); assertEquals(1020, test.toStandardDuration().getMillis()); test = new Period(0, 0, 0, 0, 0, 0, 0, Integer.MAX_VALUE); assertEquals(Integer.MAX_VALUE, test.toStandardDuration().getMillis()); test = new Period(0, 0, 0, 0, 0, 10, 20, Integer.MAX_VALUE); long expected = Integer.MAX_VALUE; expected += 10L * ((long) DateTimeConstants.MILLIS_PER_MINUTE); expected += 20L * ((long) DateTimeConstants.MILLIS_PER_SECOND); assertEquals(expected, test.toStandardDuration().getMillis()); // proof that overflow does not occur BigInteger intMax = BigInteger.valueOf(Integer.MAX_VALUE); BigInteger exp = intMax; exp = exp.add(intMax.multiply(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_SECOND))); exp = exp.add(intMax.multiply(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_MINUTE))); exp = exp.add(intMax.multiply(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_HOUR))); exp = exp.add(intMax.multiply(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_DAY))); exp = exp.add(intMax.multiply(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_WEEK))); assertTrue(exp.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0); // test = new Period(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); // try { // test.toStandardDuration(); // fail(); // } catch (ArithmeticException ex) {} } public void testToStandardDuration_years() { Period test = Period.years(1); try { test.toStandardDuration(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(-1); try { test.toStandardDuration(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.years(0); assertEquals(0, test.toStandardDuration().getMillis()); } public void testToStandardDuration_months() { Period test = Period.months(1); try { test.toStandardDuration(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardDuration(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardDuration().getMillis()); } //----------------------------------------------------------------------- public void testNormalizedStandard_yearMonth1() { Period test = new Period(1, 15, 0, 0, 0, 0, 0, 0); Period result = test.normalizedStandard(); assertEquals(new Period(1, 15, 0, 0, 0, 0, 0, 0), test); assertEquals(new Period(2, 3, 0, 0, 0, 0, 0, 0), result); } public void testNormalizedStandard_yearMonth2() { Period test = new Period(Integer.MAX_VALUE, 15, 0, 0, 0, 0, 0, 0); try { test.normalizedStandard(); fail(); } catch (ArithmeticException ex) {} } public void testNormalizedStandard_weekDay1() { Period test = new Period(0, 0, 1, 12, 0, 0, 0, 0); Period result = test.normalizedStandard(); assertEquals(new Period(0, 0, 1, 12, 0, 0, 0, 0), test); assertEquals(new Period(0, 0, 2, 5, 0, 0, 0, 0), result); } public void testNormalizedStandard_weekDay2() { Period test = new Period(0, 0, Integer.MAX_VALUE, 7, 0, 0, 0, 0); try { test.normalizedStandard(); fail(); } catch (ArithmeticException ex) {} } public void testNormalizedStandard_yearMonthWeekDay() { Period test = new Period(1, 15, 1, 12, 0, 0, 0, 0); Period result = test.normalizedStandard(); assertEquals(new Period(1, 15, 1, 12, 0, 0, 0, 0), test); assertEquals(new Period(2, 3, 2, 5, 0, 0, 0, 0), result); } public void testNormalizedStandard_yearMonthDay() { Period test = new Period(1, 15, 0, 36, 0, 0, 0, 0); Period result = test.normalizedStandard(); assertEquals(new Period(1, 15, 0, 36, 0, 0, 0, 0), test); assertEquals(new Period(2, 3, 5, 1, 0, 0, 0, 0), result); } public void testNormalizedStandard_negative() { Period test = new Period(0, 0, 0, 0, 2, -10, 0, 0); Period result = test.normalizedStandard(); assertEquals(new Period(0, 0, 0, 0, 2, -10, 0, 0), test); assertEquals(new Period(0, 0, 0, 0, 1, 50, 0, 0), result); } public void testNormalizedStandard_fullNegative() { Period test = new Period(0, 0, 0, 0, 1, -70, 0, 0); Period result = test.normalizedStandard(); assertEquals(new Period(0, 0, 0, 0, 1, -70, 0, 0), test); assertEquals(new Period(0, 0, 0, 0, 0, -10, 0, 0), result); } //----------------------------------------------------------------------- public void testNormalizedStandard_periodType_yearMonth1() { Period test = new Period(1, 15, 0, 0, 0, 0, 0, 0); Period result = test.normalizedStandard((PeriodType) null); assertEquals(new Period(1, 15, 0, 0, 0, 0, 0, 0), test); assertEquals(new Period(2, 3, 0, 0, 0, 0, 0, 0), result); } public void testNormalizedStandard_periodType_yearMonth2() { Period test = new Period(Integer.MAX_VALUE, 15, 0, 0, 0, 0, 0, 0); try { test.normalizedStandard((PeriodType) null); fail(); } catch (ArithmeticException ex) {} } public void testNormalizedStandard_periodType_yearMonth3() { Period test = new Period(1, 15, 3, 4, 0, 0, 0, 0); try { test.normalizedStandard(PeriodType.dayTime()); fail(); } catch (UnsupportedOperationException ex) {} } public void testNormalizedStandard_periodType_weekDay1() { Period test = new Period(0, 0, 1, 12, 0, 0, 0, 0); Period result = test.normalizedStandard((PeriodType) null); assertEquals(new Period(0, 0, 1, 12, 0, 0, 0, 0), test); assertEquals(new Period(0, 0, 2, 5, 0, 0, 0, 0), result); } public void testNormalizedStandard_periodType_weekDay2() { Period test = new Period(0, 0, Integer.MAX_VALUE, 7, 0, 0, 0, 0); try { test.normalizedStandard((PeriodType) null); fail(); } catch (ArithmeticException ex) {} } public void testNormalizedStandard_periodType_weekDay3() { Period test = new Period(0, 0, 1, 12, 0, 0, 0, 0); Period result = test.normalizedStandard(PeriodType.dayTime()); assertEquals(new Period(0, 0, 1, 12, 0, 0, 0, 0), test); assertEquals(new Period(0, 0, 0, 19, 0, 0, 0, 0, PeriodType.dayTime()), result); } public void testNormalizedStandard_periodType_yearMonthWeekDay() { Period test = new Period(1, 15, 1, 12, 0, 0, 0, 0); Period result = test.normalizedStandard(PeriodType.yearMonthDayTime()); assertEquals(new Period(1, 15, 1, 12, 0, 0, 0, 0), test); assertEquals(new Period(2, 3, 0, 19, 0, 0, 0, 0, PeriodType.yearMonthDayTime()), result); } public void testNormalizedStandard_periodType_yearMonthDay() { Period test = new Period(1, 15, 0, 36, 27, 0, 0, 0); Period result = test.normalizedStandard(PeriodType.yearMonthDayTime()); assertEquals(new Period(1, 15, 0, 36, 27, 0, 0, 0), test); assertEquals(new Period(2, 3, 0, 37, 3, 0, 0, 0, PeriodType.yearMonthDayTime()), result); } } joda-time-2.3/src/test/java/org/joda/time/TestDateMidnight_Constructors.java0000644000175000017500000006037712200501234026546 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Date; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.MockZeroNullIntegerConverter; import org.joda.time.format.DateTimeFormat; /** * This class is a Junit unit test for DateMidnight. * * @author Stephen Colebourne */ @SuppressWarnings("deprecation") public class TestDateMidnight_Constructors extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW_UTC = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME_NOW_LONDON = TEST_TIME_NOW_UTC - DateTimeConstants.MILLIS_PER_HOUR; private long TEST_TIME_NOW_PARIS = TEST_TIME_NOW_UTC - 2*DateTimeConstants.MILLIS_PER_HOUR; // 2002-04-05 private long TEST_TIME1_UTC = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME1_LONDON = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY - DateTimeConstants.MILLIS_PER_HOUR; private long TEST_TIME1_PARIS = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY - 2*DateTimeConstants.MILLIS_PER_HOUR; // 2003-05-06 private long TEST_TIME2_UTC = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2_LONDON = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY - DateTimeConstants.MILLIS_PER_HOUR; private long TEST_TIME2_PARIS = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY - 2*DateTimeConstants.MILLIS_PER_HOUR; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateMidnight_Constructors.class); } public TestDateMidnight_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW_UTC); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); Locale.setDefault(locale); zone = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW_UTC).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1_UTC).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2_UTC).toString()); } //----------------------------------------------------------------------- /** * Test now () */ public void test_now() throws Throwable { DateMidnight test = DateMidnight.now(); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } /** * Test now (DateTimeZone) */ public void test_now_DateTimeZone() throws Throwable { DateMidnight test = DateMidnight.now(PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW_PARIS, test.getMillis()); } /** * Test now (DateTimeZone=null) */ public void test_now_nullDateTimeZone() throws Throwable { try { DateMidnight.now((DateTimeZone) null); fail(); } catch (NullPointerException ex) {} } /** * Test now (Chronology) */ public void test_now_Chronology() throws Throwable { DateMidnight test = DateMidnight.now(GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } /** * Test now (Chronology=null) */ public void test_now_nullChronology() throws Throwable { try { DateMidnight.now((Chronology) null); fail(); } catch (NullPointerException ex) {} } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new DateMidnight(2010, 6, 30, ISOChronology.getInstance(LONDON)), DateMidnight.parse("2010-06-30")); assertEquals(new DateMidnight(2010, 1, 2, ISOChronology.getInstance(LONDON)), DateMidnight.parse("2010-002")); } public void testParse_formatter() throws Throwable { assertEquals(new DateMidnight(2010, 6, 30, ISOChronology.getInstance(LONDON)), DateMidnight.parse("2010--30 06", DateTimeFormat.forPattern("yyyy--dd MM"))); } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstructor() throws Throwable { DateMidnight test = new DateMidnight(); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } /** * Test constructor (DateTimeZone) */ public void testConstructor_DateTimeZone() throws Throwable { DateMidnight test = new DateMidnight(PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW_PARIS, test.getMillis()); } /** * Test constructor (DateTimeZone=null) */ public void testConstructor_nullDateTimeZone() throws Throwable { DateMidnight test = new DateMidnight((DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } /** * Test constructor (Chronology) */ public void testConstructor_Chronology() throws Throwable { DateMidnight test = new DateMidnight(GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } /** * Test constructor (Chronology=null) */ public void testConstructor_nullChronology() throws Throwable { DateMidnight test = new DateMidnight((Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (long) */ public void testConstructor_long1() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME1_UTC); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } /** * Test constructor (long) */ public void testConstructor_long2() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME2_UTC); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME2_LONDON, test.getMillis()); } /** * Test constructor (long, DateTimeZone) */ public void testConstructor_long1_DateTimeZone() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME1_UTC, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME1_PARIS, test.getMillis()); } /** * Test constructor (long, DateTimeZone) */ public void testConstructor_long2_DateTimeZone() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME2_UTC, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME2_PARIS, test.getMillis()); } /** * Test constructor (long, DateTimeZone=null) */ public void testConstructor_long_nullDateTimeZone() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME1_UTC, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long1_Chronology() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME1_UTC, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long2_Chronology() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME2_UTC, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME2_LONDON, test.getMillis()); } /** * Test constructor (long, Chronology=null) */ public void testConstructor_long_nullChronology() throws Throwable { DateMidnight test = new DateMidnight(TEST_TIME1_UTC, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (Object) */ public void testConstructor_Object() throws Throwable { Date date = new Date(TEST_TIME1_UTC); DateMidnight test = new DateMidnight(date); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } /** * Test constructor (Object) */ public void testConstructor_invalidObject() throws Throwable { try { new DateMidnight(new Object()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null) */ public void testConstructor_nullObject() throws Throwable { DateMidnight test = new DateMidnight((Object) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } /** * Test constructor (Object=null) */ public void testConstructor_badconverterObject() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); DateMidnight test = new DateMidnight(new Integer(0)); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L - DateTimeConstants.MILLIS_PER_HOUR, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_Object_DateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1_UTC); DateMidnight test = new DateMidnight(date, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME1_PARIS, test.getMillis()); } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_invalidObject_DateTimeZone() throws Throwable { try { new DateMidnight(new Object(), PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null, DateTimeZone) */ public void testConstructor_nullObject_DateTimeZone() throws Throwable { DateMidnight test = new DateMidnight((Object) null, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW_PARIS, test.getMillis()); } /** * Test constructor (Object, DateTimeZone=null) */ public void testConstructor_Object_nullDateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1_UTC); DateMidnight test = new DateMidnight(date, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } /** * Test constructor (Object=null, DateTimeZone=null) */ public void testConstructor_nullObject_nullDateTimeZone() throws Throwable { DateMidnight test = new DateMidnight((Object) null, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } /** * Test constructor (Object, DateTimeZone) */ public void testConstructor_badconverterObject_DateTimeZone() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); DateMidnight test = new DateMidnight(new Integer(0), GregorianChronology.getInstance()); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L - DateTimeConstants.MILLIS_PER_HOUR, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } /** * Test constructor (Object, Chronology) */ public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1_UTC); DateMidnight test = new DateMidnight(date, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } /** * Test constructor (Object, Chronology) */ public void testConstructor_invalidObject_Chronology() throws Throwable { try { new DateMidnight(new Object(), GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (Object=null, Chronology) */ public void testConstructor_nullObject_Chronology() throws Throwable { DateMidnight test = new DateMidnight((Object) null, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } /** * Test constructor (Object, Chronology=null) */ public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1_UTC); DateMidnight test = new DateMidnight(date, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME1_LONDON, test.getMillis()); } /** * Test constructor (Object=null, Chronology=null) */ public void testConstructor_nullObject_nullChronology() throws Throwable { DateMidnight test = new DateMidnight((Object) null, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); } /** * Test constructor (Object, Chronology) */ public void testConstructor_badconverterObject_Chronology() throws Throwable { try { ConverterManager.getInstance().addInstantConverter(MockZeroNullIntegerConverter.INSTANCE); DateMidnight test = new DateMidnight(new Integer(0), GregorianChronology.getInstance()); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(0L - DateTimeConstants.MILLIS_PER_HOUR, test.getMillis()); } finally { ConverterManager.getInstance().removeInstantConverter(MockZeroNullIntegerConverter.INSTANCE); } } //----------------------------------------------------------------------- /** * Test constructor (int, int, int) */ public void testConstructor_int_int_int() throws Throwable { DateMidnight test = new DateMidnight(2002, 6, 9); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(LONDON, test.getZone()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); try { new DateMidnight(Integer.MIN_VALUE, 6, 9); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(Integer.MAX_VALUE, 6, 9); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 0, 9); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 13, 9); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 6, 0); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 6, 31); fail(); } catch (IllegalArgumentException ex) {} new DateMidnight(2002, 7, 31); try { new DateMidnight(2002, 7, 32); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, DateTimeZone) */ public void testConstructor_int_int_int_DateTimeZone() throws Throwable { DateMidnight test = new DateMidnight(2002, 6, 9, PARIS); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); assertEquals(TEST_TIME_NOW_PARIS, test.getMillis()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); try { new DateMidnight(Integer.MIN_VALUE, 6, 9, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(Integer.MAX_VALUE, 6, 9, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 0, 9, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 13, 9, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 6, 0, PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 6, 31, PARIS); fail(); } catch (IllegalArgumentException ex) {} new DateMidnight(2002, 7, 31, PARIS); try { new DateMidnight(2002, 7, 32, PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, DateTimeZone=null) */ public void testConstructor_int_int_int_nullDateTimeZone() throws Throwable { DateMidnight test = new DateMidnight(2002, 6, 9, (DateTimeZone) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } /** * Test constructor (int, int, int, Chronology) */ public void testConstructor_int_int_int_Chronology() throws Throwable { DateMidnight test = new DateMidnight(2002, 6, 9, GregorianChronology.getInstance()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); try { new DateMidnight(Integer.MIN_VALUE, 6, 9, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(Integer.MAX_VALUE, 6, 9, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 0, 9, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 13, 9, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 6, 0, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} try { new DateMidnight(2002, 6, 31, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} new DateMidnight(2002, 7, 31, GregorianChronology.getInstance()); try { new DateMidnight(2002, 7, 32, GregorianChronology.getInstance()); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, int, Chronology=null) */ public void testConstructor_int_int_int_nullChronology() throws Throwable { DateMidnight test = new DateMidnight(2002, 6, 9, (Chronology) null); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(TEST_TIME_NOW_LONDON, test.getMillis()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalTime_Constructors.java0000644000175000017500000007656212200501234026061 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for LocalTime. * * @author Stephen Colebourne */ public class TestLocalTime_Constructors extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final DateTimeZone NEW_YORK = DateTimeZone.forID("America/New_York"); private static final ISOChronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final JulianChronology JULIAN_LONDON = JulianChronology.getInstance(LONDON); private static final JulianChronology JULIAN_PARIS = JulianChronology.getInstance(PARIS); private static final JulianChronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private static final int OFFSET_LONDON = LONDON.getOffset(0L) / DateTimeConstants.MILLIS_PER_HOUR; private static final int OFFSET_PARIS = PARIS.getOffset(0L) / DateTimeConstants.MILLIS_PER_HOUR; private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME1 = 1L * DateTimeConstants.MILLIS_PER_HOUR + 2L * DateTimeConstants.MILLIS_PER_MINUTE + 3L * DateTimeConstants.MILLIS_PER_SECOND + 4L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalTime_Constructors.class); } public TestLocalTime_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); java.util.TimeZone.setDefault(LONDON.toTimeZone()); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); java.util.TimeZone.setDefault(zone.toTimeZone()); zone = null; } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstantMidnight() throws Throwable { LocalTime test = LocalTime.MIDNIGHT; assertEquals(ISO_UTC, test.getChronology()); assertEquals(0, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new LocalTime(1, 20), LocalTime.parse("01:20")); assertEquals(new LocalTime(14, 50, 30, 432), LocalTime.parse("14:50:30.432")); } public void testParse_formatter() throws Throwable { DateTimeFormatter f = DateTimeFormat.forPattern("HH mm").withChronology(ISOChronology.getInstance(PARIS)); assertEquals(new LocalTime(13, 30), LocalTime.parse("13 30", f)); } //----------------------------------------------------------------------- public void testFactory_FromCalendarFields_Calendar() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalTime expected = new LocalTime(4, 5, 6, 7); assertEquals(expected, LocalTime.fromCalendarFields(cal)); try { LocalTime.fromCalendarFields((Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFactory_FromDateFields_after1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalTime expected = new LocalTime(4, 5, 6, 7); assertEquals(expected, LocalTime.fromDateFields(cal.getTime())); } public void testFactory_FromDateFields_before1970() throws Exception { GregorianCalendar cal = new GregorianCalendar(1969, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); LocalTime expected = new LocalTime(4, 5, 6, 7); assertEquals(expected, LocalTime.fromDateFields(cal.getTime())); } public void testFactory_FromDateFields_null() throws Exception { try { LocalTime.fromDateFields((Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFactoryMillisOfDay_long() throws Throwable { LocalTime test = LocalTime.fromMillisOfDay(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testFactoryMillisOfDay_long_Chronology() throws Throwable { LocalTime test = LocalTime.fromMillisOfDay(TEST_TIME1, JULIAN_LONDON); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(1, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testFactoryMillisOfDay_long_nullChronology() throws Throwable { LocalTime test = LocalTime.fromMillisOfDay(TEST_TIME1, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor() throws Throwable { LocalTime test = new LocalTime(); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(test, LocalTime.now()); } //----------------------------------------------------------------------- public void testConstructor_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 30, 40, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris LocalTime test = new LocalTime(LONDON); assertEquals(ISO_UTC, test.getChronology()); assertEquals(23, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(test, LocalTime.now(LONDON)); test = new LocalTime(PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(0, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(test, LocalTime.now(PARIS)); } public void testConstructor_nullDateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 8, 23, 59, 30, 40, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris LocalTime test = new LocalTime((DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(23, test.getHourOfDay()); assertEquals(59, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_Chronology() throws Throwable { LocalTime test = new LocalTime(JULIAN_LONDON); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(10 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); assertEquals(test, LocalTime.now(JULIAN_LONDON)); } public void testConstructor_nullChronology() throws Throwable { LocalTime test = new LocalTime((Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_long1() throws Throwable { LocalTime test = new LocalTime(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_long2() throws Throwable { LocalTime test = new LocalTime(TEST_TIME2); assertEquals(ISO_UTC, test.getChronology()); assertEquals(5 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(6, test.getMinuteOfHour()); assertEquals(7, test.getSecondOfMinute()); assertEquals(8, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_long_DateTimeZone() throws Throwable { LocalTime test = new LocalTime(TEST_TIME1, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_long_DateTimeZone_2() throws Throwable { DateTime dt = new DateTime(2007, 6, 9, 1, 2, 3, 4, PARIS); DateTime dtUTC = new DateTime(1970, 1, 1, 1, 2, 3, 4, DateTimeZone.UTC); LocalTime test = new LocalTime(dt.getMillis(), PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); assertEquals(dtUTC.getMillis(), test.getLocalMillis()); } public void testConstructor_long_nullDateTimeZone() throws Throwable { LocalTime test = new LocalTime(TEST_TIME1, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_long1_Chronology() throws Throwable { LocalTime test = new LocalTime(TEST_TIME1, JULIAN_PARIS); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(1 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_long2_Chronology() throws Throwable { LocalTime test = new LocalTime(TEST_TIME2, JULIAN_LONDON); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(5 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(6, test.getMinuteOfHour()); assertEquals(7, test.getSecondOfMinute()); assertEquals(8, test.getMillisOfSecond()); } public void testConstructor_long_nullChronology() throws Throwable { LocalTime test = new LocalTime(TEST_TIME1, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_Object1() throws Throwable { Date date = new Date(TEST_TIME1); LocalTime test = new LocalTime(date); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_Object2() throws Throwable { Calendar cal = new GregorianCalendar(); cal.setTime(new Date(TEST_TIME1)); LocalTime test = new LocalTime(cal); assertEquals(GJChronology.getInstanceUTC(), test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_nullObject() throws Throwable { LocalTime test = new LocalTime((Object) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString1() throws Throwable { LocalTime test = new LocalTime("10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString1Tokyo() throws Throwable { DateTimeZone.setDefault(TOKYO); LocalTime test = new LocalTime("10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString1NewYork() throws Throwable { DateTimeZone.setDefault(NEW_YORK); LocalTime test = new LocalTime("10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString2() throws Throwable { LocalTime test = new LocalTime("T10:20:30.040"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectString3() throws Throwable { LocalTime test = new LocalTime("10:20"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectString4() throws Throwable { LocalTime test = new LocalTime("10"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); } public void testConstructor_ObjectStringEx1() throws Throwable { try { new LocalTime("1970-04-06"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx2() throws Throwable { try { new LocalTime("1970-04-06T+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx3() throws Throwable { try { new LocalTime("1970-04-06T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx4() throws Throwable { try { new LocalTime("1970-04-06T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx5() throws Throwable { try { new LocalTime("T10:20:30.040+04:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectStringEx6() throws Throwable { try { new LocalTime("10:20:30.040+04:00"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectLocalTime() throws Throwable { LocalTime time = new LocalTime(10, 20, 30, 40, BUDDHIST_UTC); LocalTime test = new LocalTime(time); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_ObjectLocalDate() throws Throwable { LocalDate date = new LocalDate(1970, 4, 6, BUDDHIST_UTC); try { new LocalTime(date); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_ObjectLocalDateTime() throws Throwable { LocalDateTime dt = new LocalDateTime(1970, 5, 6, 10, 20, 30, 40, BUDDHIST_UTC); LocalTime test = new LocalTime(dt); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } @SuppressWarnings("deprecation") public void testConstructor_ObjectTimeOfDay() throws Throwable { TimeOfDay time = new TimeOfDay(10, 20, 30, 40, BUDDHIST_UTC); LocalTime test = new LocalTime(time); assertEquals(BUDDHIST_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_Object1_DateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); LocalTime test = new LocalTime(date, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_ObjectString_DateTimeZoneLondon() throws Throwable { LocalTime test = new LocalTime("04:20", LONDON); assertEquals(4, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); } public void testConstructor_ObjectString_DateTimeZoneTokyo() throws Throwable { LocalTime test = new LocalTime("04:20", TOKYO); assertEquals(ISO_UTC, test.getChronology()); assertEquals(4, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); } public void testConstructor_ObjectString_DateTimeZoneNewYork() throws Throwable { LocalTime test = new LocalTime("04:20", NEW_YORK); assertEquals(ISO_UTC, test.getChronology()); assertEquals(4, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); } public void testConstructor_nullObject_DateTimeZone() throws Throwable { LocalTime test = new LocalTime((Object) null, PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET_PARIS, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_Object_nullDateTimeZone() throws Throwable { Date date = new Date(TEST_TIME1); LocalTime test = new LocalTime(date, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_nullObject_nullDateTimeZone() throws Throwable { LocalTime test = new LocalTime((Object) null, (DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_Object1_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); LocalTime test = new LocalTime(date, JULIAN_LONDON); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_Object2_Chronology() throws Throwable { LocalTime test = new LocalTime("T10:20"); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new LocalTime("T1020"); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_nullObject_Chronology() throws Throwable { LocalTime test = new LocalTime((Object) null, JULIAN_LONDON); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(10 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); LocalTime test = new LocalTime(date, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(2, test.getMinuteOfHour()); assertEquals(3, test.getSecondOfMinute()); assertEquals(4, test.getMillisOfSecond()); } public void testConstructor_nullObject_nullChronology() throws Throwable { LocalTime test = new LocalTime((Object) null, (Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10 + OFFSET_LONDON, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testConstructor_int_int() throws Throwable { LocalTime test = new LocalTime(10, 20); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(0, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new LocalTime(-1, 20); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(24, 20); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, -1); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 60); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int() throws Throwable { LocalTime test = new LocalTime(10, 20, 30); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new LocalTime(-1, 20, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(24, 20, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, -1, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 60, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, -1); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 60); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int_int() throws Throwable { LocalTime test = new LocalTime(10, 20, 30, 40); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new LocalTime(-1, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(24, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, -1, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 60, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, -1, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 60, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 30, -1); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 30, 1000); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int_int_Chronology() throws Throwable { LocalTime test = new LocalTime(10, 20, 30, 40, JULIAN_LONDON); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new LocalTime(-1, 20, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(24, 20, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, -1, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 60, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, -1, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 60, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 30, -1, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 30, 1000, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_int_int_int_int_nullChronology() throws Throwable { LocalTime test = new LocalTime(10, 20, 30, 40, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/chrono/0000755000175000017500000000000012205344143021176 5ustar ebourgebourgjoda-time-2.3/src/test/java/org/joda/time/chrono/TestJulianChronology.java0000644000175000017500000003731011564251364026204 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; /** * This class is a Junit unit test for JulianChronology. * * @author Stephen Colebourne */ public class TestJulianChronology extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestJulianChronology.class); } public TestJulianChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, JulianChronology.getInstanceUTC().getZone()); assertSame(JulianChronology.class, JulianChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, JulianChronology.getInstance().getZone()); assertSame(JulianChronology.class, JulianChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, JulianChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, JulianChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, JulianChronology.getInstance(null).getZone()); assertSame(JulianChronology.class, JulianChronology.getInstance(TOKYO).getClass()); } public void testFactory_Zone_int() { JulianChronology chrono = JulianChronology.getInstance(TOKYO, 2); assertEquals(TOKYO, chrono.getZone()); assertEquals(2, chrono.getMinimumDaysInFirstWeek()); try { JulianChronology.getInstance(TOKYO, 0); fail(); } catch (IllegalArgumentException ex) {} try { JulianChronology.getInstance(TOKYO, 8); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testEquality() { assertSame(JulianChronology.getInstance(TOKYO), JulianChronology.getInstance(TOKYO)); assertSame(JulianChronology.getInstance(LONDON), JulianChronology.getInstance(LONDON)); assertSame(JulianChronology.getInstance(PARIS), JulianChronology.getInstance(PARIS)); assertSame(JulianChronology.getInstanceUTC(), JulianChronology.getInstanceUTC()); assertSame(JulianChronology.getInstance(), JulianChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(JulianChronology.getInstanceUTC(), JulianChronology.getInstance(LONDON).withUTC()); assertSame(JulianChronology.getInstanceUTC(), JulianChronology.getInstance(TOKYO).withUTC()); assertSame(JulianChronology.getInstanceUTC(), JulianChronology.getInstanceUTC().withUTC()); assertSame(JulianChronology.getInstanceUTC(), JulianChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(JulianChronology.getInstance(TOKYO), JulianChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(JulianChronology.getInstance(LONDON), JulianChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(JulianChronology.getInstance(PARIS), JulianChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(JulianChronology.getInstance(LONDON), JulianChronology.getInstance(TOKYO).withZone(null)); assertSame(JulianChronology.getInstance(PARIS), JulianChronology.getInstance().withZone(PARIS)); assertSame(JulianChronology.getInstance(PARIS), JulianChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("JulianChronology[Europe/London]", JulianChronology.getInstance(LONDON).toString()); assertEquals("JulianChronology[Asia/Tokyo]", JulianChronology.getInstance(TOKYO).toString()); assertEquals("JulianChronology[Europe/London]", JulianChronology.getInstance().toString()); assertEquals("JulianChronology[UTC]", JulianChronology.getInstanceUTC().toString()); assertEquals("JulianChronology[UTC,mdfw=2]", JulianChronology.getInstance(DateTimeZone.UTC, 2).toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", JulianChronology.getInstance().eras().getName()); assertEquals("centuries", JulianChronology.getInstance().centuries().getName()); assertEquals("years", JulianChronology.getInstance().years().getName()); assertEquals("weekyears", JulianChronology.getInstance().weekyears().getName()); assertEquals("months", JulianChronology.getInstance().months().getName()); assertEquals("weeks", JulianChronology.getInstance().weeks().getName()); assertEquals("days", JulianChronology.getInstance().days().getName()); assertEquals("halfdays", JulianChronology.getInstance().halfdays().getName()); assertEquals("hours", JulianChronology.getInstance().hours().getName()); assertEquals("minutes", JulianChronology.getInstance().minutes().getName()); assertEquals("seconds", JulianChronology.getInstance().seconds().getName()); assertEquals("millis", JulianChronology.getInstance().millis().getName()); assertEquals(false, JulianChronology.getInstance().eras().isSupported()); assertEquals(true, JulianChronology.getInstance().centuries().isSupported()); assertEquals(true, JulianChronology.getInstance().years().isSupported()); assertEquals(true, JulianChronology.getInstance().weekyears().isSupported()); assertEquals(true, JulianChronology.getInstance().months().isSupported()); assertEquals(true, JulianChronology.getInstance().weeks().isSupported()); assertEquals(true, JulianChronology.getInstance().days().isSupported()); assertEquals(true, JulianChronology.getInstance().halfdays().isSupported()); assertEquals(true, JulianChronology.getInstance().hours().isSupported()); assertEquals(true, JulianChronology.getInstance().minutes().isSupported()); assertEquals(true, JulianChronology.getInstance().seconds().isSupported()); assertEquals(true, JulianChronology.getInstance().millis().isSupported()); assertEquals(false, JulianChronology.getInstance().centuries().isPrecise()); assertEquals(false, JulianChronology.getInstance().years().isPrecise()); assertEquals(false, JulianChronology.getInstance().weekyears().isPrecise()); assertEquals(false, JulianChronology.getInstance().months().isPrecise()); assertEquals(false, JulianChronology.getInstance().weeks().isPrecise()); assertEquals(false, JulianChronology.getInstance().days().isPrecise()); assertEquals(false, JulianChronology.getInstance().halfdays().isPrecise()); assertEquals(true, JulianChronology.getInstance().hours().isPrecise()); assertEquals(true, JulianChronology.getInstance().minutes().isPrecise()); assertEquals(true, JulianChronology.getInstance().seconds().isPrecise()); assertEquals(true, JulianChronology.getInstance().millis().isPrecise()); assertEquals(false, JulianChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, JulianChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, JulianChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, JulianChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, JulianChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, JulianChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, JulianChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, JulianChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, JulianChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, JulianChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, JulianChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, JulianChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, JulianChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, JulianChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, JulianChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, JulianChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, JulianChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, JulianChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, JulianChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, JulianChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, JulianChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, JulianChronology.getInstance(gmt).millis().isPrecise()); } public void testDateFields() { assertEquals("era", JulianChronology.getInstance().era().getName()); assertEquals("centuryOfEra", JulianChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", JulianChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", JulianChronology.getInstance().yearOfEra().getName()); assertEquals("year", JulianChronology.getInstance().year().getName()); assertEquals("monthOfYear", JulianChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", JulianChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", JulianChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", JulianChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", JulianChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", JulianChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", JulianChronology.getInstance().dayOfWeek().getName()); assertEquals(true, JulianChronology.getInstance().era().isSupported()); assertEquals(true, JulianChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, JulianChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, JulianChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, JulianChronology.getInstance().year().isSupported()); assertEquals(true, JulianChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, JulianChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, JulianChronology.getInstance().weekyear().isSupported()); assertEquals(true, JulianChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, JulianChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, JulianChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, JulianChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", JulianChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", JulianChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", JulianChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", JulianChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", JulianChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", JulianChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", JulianChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", JulianChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", JulianChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", JulianChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", JulianChronology.getInstance().millisOfSecond().getName()); assertEquals(true, JulianChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, JulianChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, JulianChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, JulianChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, JulianChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, JulianChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, JulianChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, JulianChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, JulianChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, JulianChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, JulianChronology.getInstance().millisOfSecond().isSupported()); } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestISOChronology.java0000644000175000017500000005607311564251364025423 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.IllegalFieldValueException; import org.joda.time.Partial; import org.joda.time.TimeOfDay; import org.joda.time.YearMonthDay; /** * This class is a Junit unit test for ISOChronology. * * @author Stephen Colebourne */ public class TestISOChronology extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestISOChronology.class); } public TestISOChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, ISOChronology.getInstanceUTC().getZone()); assertSame(ISOChronology.class, ISOChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, ISOChronology.getInstance().getZone()); assertSame(ISOChronology.class, ISOChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, ISOChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, ISOChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, ISOChronology.getInstance(null).getZone()); assertSame(ISOChronology.class, ISOChronology.getInstance(TOKYO).getClass()); } //----------------------------------------------------------------------- public void testEquality() { assertSame(ISOChronology.getInstance(TOKYO), ISOChronology.getInstance(TOKYO)); assertSame(ISOChronology.getInstance(LONDON), ISOChronology.getInstance(LONDON)); assertSame(ISOChronology.getInstance(PARIS), ISOChronology.getInstance(PARIS)); assertSame(ISOChronology.getInstanceUTC(), ISOChronology.getInstanceUTC()); assertSame(ISOChronology.getInstance(), ISOChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(ISOChronology.getInstanceUTC(), ISOChronology.getInstance(LONDON).withUTC()); assertSame(ISOChronology.getInstanceUTC(), ISOChronology.getInstance(TOKYO).withUTC()); assertSame(ISOChronology.getInstanceUTC(), ISOChronology.getInstanceUTC().withUTC()); assertSame(ISOChronology.getInstanceUTC(), ISOChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(ISOChronology.getInstance(TOKYO), ISOChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(ISOChronology.getInstance(LONDON), ISOChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(ISOChronology.getInstance(PARIS), ISOChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(ISOChronology.getInstance(LONDON), ISOChronology.getInstance(TOKYO).withZone(null)); assertSame(ISOChronology.getInstance(PARIS), ISOChronology.getInstance().withZone(PARIS)); assertSame(ISOChronology.getInstance(PARIS), ISOChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("ISOChronology[Europe/London]", ISOChronology.getInstance(LONDON).toString()); assertEquals("ISOChronology[Asia/Tokyo]", ISOChronology.getInstance(TOKYO).toString()); assertEquals("ISOChronology[Europe/London]", ISOChronology.getInstance().toString()); assertEquals("ISOChronology[UTC]", ISOChronology.getInstanceUTC().toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", ISOChronology.getInstance().eras().getName()); assertEquals("centuries", ISOChronology.getInstance().centuries().getName()); assertEquals("years", ISOChronology.getInstance().years().getName()); assertEquals("weekyears", ISOChronology.getInstance().weekyears().getName()); assertEquals("months", ISOChronology.getInstance().months().getName()); assertEquals("weeks", ISOChronology.getInstance().weeks().getName()); assertEquals("days", ISOChronology.getInstance().days().getName()); assertEquals("halfdays", ISOChronology.getInstance().halfdays().getName()); assertEquals("hours", ISOChronology.getInstance().hours().getName()); assertEquals("minutes", ISOChronology.getInstance().minutes().getName()); assertEquals("seconds", ISOChronology.getInstance().seconds().getName()); assertEquals("millis", ISOChronology.getInstance().millis().getName()); assertEquals(false, ISOChronology.getInstance().eras().isSupported()); assertEquals(true, ISOChronology.getInstance().centuries().isSupported()); assertEquals(true, ISOChronology.getInstance().years().isSupported()); assertEquals(true, ISOChronology.getInstance().weekyears().isSupported()); assertEquals(true, ISOChronology.getInstance().months().isSupported()); assertEquals(true, ISOChronology.getInstance().weeks().isSupported()); assertEquals(true, ISOChronology.getInstance().days().isSupported()); assertEquals(true, ISOChronology.getInstance().halfdays().isSupported()); assertEquals(true, ISOChronology.getInstance().hours().isSupported()); assertEquals(true, ISOChronology.getInstance().minutes().isSupported()); assertEquals(true, ISOChronology.getInstance().seconds().isSupported()); assertEquals(true, ISOChronology.getInstance().millis().isSupported()); assertEquals(false, ISOChronology.getInstance().centuries().isPrecise()); assertEquals(false, ISOChronology.getInstance().years().isPrecise()); assertEquals(false, ISOChronology.getInstance().weekyears().isPrecise()); assertEquals(false, ISOChronology.getInstance().months().isPrecise()); assertEquals(false, ISOChronology.getInstance().weeks().isPrecise()); assertEquals(false, ISOChronology.getInstance().days().isPrecise()); assertEquals(false, ISOChronology.getInstance().halfdays().isPrecise()); assertEquals(true, ISOChronology.getInstance().hours().isPrecise()); assertEquals(true, ISOChronology.getInstance().minutes().isPrecise()); assertEquals(true, ISOChronology.getInstance().seconds().isPrecise()); assertEquals(true, ISOChronology.getInstance().millis().isPrecise()); assertEquals(false, ISOChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, ISOChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, ISOChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, ISOChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, ISOChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, ISOChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, ISOChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, ISOChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, ISOChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, ISOChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, ISOChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, ISOChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, ISOChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, ISOChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, ISOChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, ISOChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, ISOChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, ISOChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, ISOChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, ISOChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, ISOChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, ISOChronology.getInstance(gmt).millis().isPrecise()); DateTimeZone offset = DateTimeZone.forOffsetHours(1); assertEquals(false, ISOChronology.getInstance(offset).centuries().isPrecise()); assertEquals(false, ISOChronology.getInstance(offset).years().isPrecise()); assertEquals(false, ISOChronology.getInstance(offset).weekyears().isPrecise()); assertEquals(false, ISOChronology.getInstance(offset).months().isPrecise()); assertEquals(true, ISOChronology.getInstance(offset).weeks().isPrecise()); assertEquals(true, ISOChronology.getInstance(offset).days().isPrecise()); assertEquals(true, ISOChronology.getInstance(offset).halfdays().isPrecise()); assertEquals(true, ISOChronology.getInstance(offset).hours().isPrecise()); assertEquals(true, ISOChronology.getInstance(offset).minutes().isPrecise()); assertEquals(true, ISOChronology.getInstance(offset).seconds().isPrecise()); assertEquals(true, ISOChronology.getInstance(offset).millis().isPrecise()); } public void testDateFields() { assertEquals("era", ISOChronology.getInstance().era().getName()); assertEquals("centuryOfEra", ISOChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", ISOChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", ISOChronology.getInstance().yearOfEra().getName()); assertEquals("year", ISOChronology.getInstance().year().getName()); assertEquals("monthOfYear", ISOChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", ISOChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", ISOChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", ISOChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", ISOChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", ISOChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", ISOChronology.getInstance().dayOfWeek().getName()); assertEquals(true, ISOChronology.getInstance().era().isSupported()); assertEquals(true, ISOChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, ISOChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, ISOChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, ISOChronology.getInstance().year().isSupported()); assertEquals(true, ISOChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, ISOChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, ISOChronology.getInstance().weekyear().isSupported()); assertEquals(true, ISOChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, ISOChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, ISOChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, ISOChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", ISOChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", ISOChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", ISOChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", ISOChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", ISOChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", ISOChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", ISOChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", ISOChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", ISOChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", ISOChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", ISOChronology.getInstance().millisOfSecond().getName()); assertEquals(true, ISOChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, ISOChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, ISOChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, ISOChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, ISOChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, ISOChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, ISOChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, ISOChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, ISOChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, ISOChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, ISOChronology.getInstance().millisOfSecond().isSupported()); } public void testMaxYear() { final ISOChronology chrono = ISOChronology.getInstanceUTC(); final int maxYear = chrono.year().getMaximumValue(); DateTime start = new DateTime(maxYear, 1, 1, 0, 0, 0, 0, chrono); DateTime end = new DateTime(maxYear, 12, 31, 23, 59, 59, 999, chrono); assertTrue(start.getMillis() > 0); assertTrue(end.getMillis() > start.getMillis()); assertEquals(maxYear, start.getYear()); assertEquals(maxYear, end.getYear()); long delta = end.getMillis() - start.getMillis(); long expectedDelta = (start.year().isLeap() ? 366L : 365L) * DateTimeConstants.MILLIS_PER_DAY - 1; assertEquals(expectedDelta, delta); assertEquals(start, new DateTime(maxYear + "-01-01T00:00:00.000Z", chrono)); assertEquals(end, new DateTime(maxYear + "-12-31T23:59:59.999Z", chrono)); try { start.plusYears(1); fail(); } catch (IllegalFieldValueException e) { } try { end.plusYears(1); fail(); } catch (IllegalFieldValueException e) { } assertEquals(maxYear + 1, chrono.year().get(Long.MAX_VALUE)); } public void testMinYear() { final ISOChronology chrono = ISOChronology.getInstanceUTC(); final int minYear = chrono.year().getMinimumValue(); DateTime start = new DateTime(minYear, 1, 1, 0, 0, 0, 0, chrono); DateTime end = new DateTime(minYear, 12, 31, 23, 59, 59, 999, chrono); assertTrue(start.getMillis() < 0); assertTrue(end.getMillis() > start.getMillis()); assertEquals(minYear, start.getYear()); assertEquals(minYear, end.getYear()); long delta = end.getMillis() - start.getMillis(); long expectedDelta = (start.year().isLeap() ? 366L : 365L) * DateTimeConstants.MILLIS_PER_DAY - 1; assertEquals(expectedDelta, delta); assertEquals(start, new DateTime(minYear + "-01-01T00:00:00.000Z", chrono)); assertEquals(end, new DateTime(minYear + "-12-31T23:59:59.999Z", chrono)); try { start.minusYears(1); fail(); } catch (IllegalFieldValueException e) { } try { end.minusYears(1); fail(); } catch (IllegalFieldValueException e) { } assertEquals(minYear - 1, chrono.year().get(Long.MIN_VALUE)); } public void testCutoverAddYears() { testAdd("1582-01-01", DurationFieldType.years(), 1, "1583-01-01"); testAdd("1582-02-15", DurationFieldType.years(), 1, "1583-02-15"); testAdd("1582-02-28", DurationFieldType.years(), 1, "1583-02-28"); testAdd("1582-03-01", DurationFieldType.years(), 1, "1583-03-01"); testAdd("1582-09-30", DurationFieldType.years(), 1, "1583-09-30"); testAdd("1582-10-01", DurationFieldType.years(), 1, "1583-10-01"); testAdd("1582-10-04", DurationFieldType.years(), 1, "1583-10-04"); testAdd("1582-10-15", DurationFieldType.years(), 1, "1583-10-15"); testAdd("1582-10-16", DurationFieldType.years(), 1, "1583-10-16"); testAdd("1580-01-01", DurationFieldType.years(), 4, "1584-01-01"); testAdd("1580-02-29", DurationFieldType.years(), 4, "1584-02-29"); testAdd("1580-10-01", DurationFieldType.years(), 4, "1584-10-01"); testAdd("1580-10-10", DurationFieldType.years(), 4, "1584-10-10"); testAdd("1580-10-15", DurationFieldType.years(), 4, "1584-10-15"); testAdd("1580-12-31", DurationFieldType.years(), 4, "1584-12-31"); } public void testAddMonths() { testAdd("1582-01-01", DurationFieldType.months(), 1, "1582-02-01"); testAdd("1582-01-01", DurationFieldType.months(), 6, "1582-07-01"); testAdd("1582-01-01", DurationFieldType.months(), 12, "1583-01-01"); testAdd("1582-11-15", DurationFieldType.months(), 1, "1582-12-15"); testAdd("1582-09-04", DurationFieldType.months(), 2, "1582-11-04"); testAdd("1582-09-05", DurationFieldType.months(), 2, "1582-11-05"); testAdd("1582-09-10", DurationFieldType.months(), 2, "1582-11-10"); testAdd("1582-09-15", DurationFieldType.months(), 2, "1582-11-15"); testAdd("1580-01-01", DurationFieldType.months(), 48, "1584-01-01"); testAdd("1580-02-29", DurationFieldType.months(), 48, "1584-02-29"); testAdd("1580-10-01", DurationFieldType.months(), 48, "1584-10-01"); testAdd("1580-10-10", DurationFieldType.months(), 48, "1584-10-10"); testAdd("1580-10-15", DurationFieldType.months(), 48, "1584-10-15"); testAdd("1580-12-31", DurationFieldType.months(), 48, "1584-12-31"); } private void testAdd(String start, DurationFieldType type, int amt, String end) { DateTime dtStart = new DateTime(start, ISOChronology.getInstanceUTC()); DateTime dtEnd = new DateTime(end, ISOChronology.getInstanceUTC()); assertEquals(dtEnd, dtStart.withFieldAdded(type, amt)); assertEquals(dtStart, dtEnd.withFieldAdded(type, -amt)); DurationField field = type.getField(ISOChronology.getInstanceUTC()); int diff = field.getDifference(dtEnd.getMillis(), dtStart.getMillis()); assertEquals(amt, diff); if (type == DurationFieldType.years() || type == DurationFieldType.months() || type == DurationFieldType.days()) { YearMonthDay ymdStart = new YearMonthDay(start, ISOChronology.getInstanceUTC()); YearMonthDay ymdEnd = new YearMonthDay(end, ISOChronology.getInstanceUTC()); assertEquals(ymdEnd, ymdStart.withFieldAdded(type, amt)); assertEquals(ymdStart, ymdEnd.withFieldAdded(type, -amt)); } } public void testTimeOfDayAdd() { TimeOfDay start = new TimeOfDay(12, 30); TimeOfDay end = new TimeOfDay(10, 30); assertEquals(end, start.plusHours(22)); assertEquals(start, end.minusHours(22)); assertEquals(end, start.plusMinutes(22 * 60)); assertEquals(start, end.minusMinutes(22 * 60)); } public void testPartialDayOfYearAdd() { Partial start = new Partial().with(DateTimeFieldType.year(), 2000).with(DateTimeFieldType.dayOfYear(), 366); Partial end = new Partial().with(DateTimeFieldType.year(), 2004).with(DateTimeFieldType.dayOfYear(), 366); assertEquals(end, start.withFieldAdded(DurationFieldType.days(), 365 + 365 + 365 + 366)); assertEquals(start, end.withFieldAdded(DurationFieldType.days(), -(365 + 365 + 365 + 366))); } public void testMaximumValue() { DateMidnight dt = new DateMidnight(1570, 1, 1); while (dt.getYear() < 1590) { dt = dt.plusDays(1); YearMonthDay ymd = dt.toYearMonthDay(); assertEquals(dt.year().getMaximumValue(), ymd.year().getMaximumValue()); assertEquals(dt.monthOfYear().getMaximumValue(), ymd.monthOfYear().getMaximumValue()); assertEquals(dt.dayOfMonth().getMaximumValue(), ymd.dayOfMonth().getMaximumValue()); } } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestGJDate.java0000644000175000017500000001271012203425714024002 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; /** * Test. */ public class TestGJDate extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestGJDate.class); } public TestGJDate(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- private static final Chronology GJ_CHRONOLOGY = GJChronology.getInstanceUTC(); //----------------------------------------------------------------------- public void test_plusYears_positiveToPositive() { LocalDate date = new LocalDate(3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(7, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(4)); } public void test_plusYears_positiveToZero() { LocalDate date = new LocalDate(3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(-1, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(-3)); } public void test_plusYears_positiveToNegative() { LocalDate date = new LocalDate(3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(-2, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(-4)); } //----------------------------------------------------------------------- public void test_plusYears_negativeToNegative() { LocalDate date = new LocalDate(-3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(-1, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(2)); } public void test_plusYears_negativeToZero() { LocalDate date = new LocalDate(-3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(1, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(3)); } public void test_plusYears_negativeToPositive() { LocalDate date = new LocalDate(-3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(2, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(4)); } //----------------------------------------------------------------------- public void test_plusYears_positiveToPositive_crossCutover() { LocalDate date = new LocalDate(3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(2007, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(2004)); } public void test_plusYears_positiveToZero_crossCutover() { LocalDate date = new LocalDate(2003, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(-1, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(-2003)); } public void test_plusYears_positiveToNegative_crossCutover() { LocalDate date = new LocalDate(2003, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(-2, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(-2004)); } public void test_plusYears_negativeToPositive_crossCutover() { LocalDate date = new LocalDate(-3, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(2002, 6, 30, GJ_CHRONOLOGY); assertEquals(expected, date.plusYears(2004)); } //----------------------------------------------------------------------- public void test_plusWeekyears_positiveToZero_crossCutover() { LocalDate date = new LocalDate(2003, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(-1, 6, 30, GJ_CHRONOLOGY).withWeekOfWeekyear(date.getWeekOfWeekyear()).withDayOfWeek(date.getDayOfWeek()); assertEquals(expected, date.weekyear().addToCopy(-2003)); } public void test_plusWeekyears_positiveToNegative_crossCutover() { LocalDate date = new LocalDate(2003, 6, 30, GJ_CHRONOLOGY); LocalDate expected = new LocalDate(-2, 6, 30, GJ_CHRONOLOGY).withWeekOfWeekyear(date.getWeekOfWeekyear()).withDayOfWeek(date.getDayOfWeek()); assertEquals(expected, date.weekyear().addToCopy(-2004)); } //----------------------------------------------------------------------- public void test_cutoverPreZero() { DateTime cutover = new LocalDate(-2, 6, 30, ISOChronology.getInstanceUTC()).toDateTimeAtStartOfDay(DateTimeZone.UTC); try { GJChronology.getInstance(DateTimeZone.UTC, cutover); fail(); } catch (IllegalArgumentException ex) { // expected } } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestGregorianChronology.java0000644000175000017500000004130511564251364026676 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateMidnight; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.YearMonthDay; /** * This class is a Junit unit test for GregorianChronology. * * @author Stephen Colebourne */ public class TestGregorianChronology extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestGregorianChronology.class); } public TestGregorianChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, GregorianChronology.getInstanceUTC().getZone()); assertSame(GregorianChronology.class, GregorianChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, GregorianChronology.getInstance().getZone()); assertSame(GregorianChronology.class, GregorianChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, GregorianChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, GregorianChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, GregorianChronology.getInstance(null).getZone()); assertSame(GregorianChronology.class, GregorianChronology.getInstance(TOKYO).getClass()); } public void testFactory_Zone_int() { GregorianChronology chrono = GregorianChronology.getInstance(TOKYO, 2); assertEquals(TOKYO, chrono.getZone()); assertEquals(2, chrono.getMinimumDaysInFirstWeek()); try { GregorianChronology.getInstance(TOKYO, 0); fail(); } catch (IllegalArgumentException ex) {} try { GregorianChronology.getInstance(TOKYO, 8); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testEquality() { assertSame(GregorianChronology.getInstance(TOKYO), GregorianChronology.getInstance(TOKYO)); assertSame(GregorianChronology.getInstance(LONDON), GregorianChronology.getInstance(LONDON)); assertSame(GregorianChronology.getInstance(PARIS), GregorianChronology.getInstance(PARIS)); assertSame(GregorianChronology.getInstanceUTC(), GregorianChronology.getInstanceUTC()); assertSame(GregorianChronology.getInstance(), GregorianChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(GregorianChronology.getInstanceUTC(), GregorianChronology.getInstance(LONDON).withUTC()); assertSame(GregorianChronology.getInstanceUTC(), GregorianChronology.getInstance(TOKYO).withUTC()); assertSame(GregorianChronology.getInstanceUTC(), GregorianChronology.getInstanceUTC().withUTC()); assertSame(GregorianChronology.getInstanceUTC(), GregorianChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(GregorianChronology.getInstance(TOKYO), GregorianChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(GregorianChronology.getInstance(LONDON), GregorianChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(GregorianChronology.getInstance(PARIS), GregorianChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(GregorianChronology.getInstance(LONDON), GregorianChronology.getInstance(TOKYO).withZone(null)); assertSame(GregorianChronology.getInstance(PARIS), GregorianChronology.getInstance().withZone(PARIS)); assertSame(GregorianChronology.getInstance(PARIS), GregorianChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("GregorianChronology[Europe/London]", GregorianChronology.getInstance(LONDON).toString()); assertEquals("GregorianChronology[Asia/Tokyo]", GregorianChronology.getInstance(TOKYO).toString()); assertEquals("GregorianChronology[Europe/London]", GregorianChronology.getInstance().toString()); assertEquals("GregorianChronology[UTC]", GregorianChronology.getInstanceUTC().toString()); assertEquals("GregorianChronology[UTC,mdfw=2]", GregorianChronology.getInstance(DateTimeZone.UTC, 2).toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", GregorianChronology.getInstance().eras().getName()); assertEquals("centuries", GregorianChronology.getInstance().centuries().getName()); assertEquals("years", GregorianChronology.getInstance().years().getName()); assertEquals("weekyears", GregorianChronology.getInstance().weekyears().getName()); assertEquals("months", GregorianChronology.getInstance().months().getName()); assertEquals("weeks", GregorianChronology.getInstance().weeks().getName()); assertEquals("days", GregorianChronology.getInstance().days().getName()); assertEquals("halfdays", GregorianChronology.getInstance().halfdays().getName()); assertEquals("hours", GregorianChronology.getInstance().hours().getName()); assertEquals("minutes", GregorianChronology.getInstance().minutes().getName()); assertEquals("seconds", GregorianChronology.getInstance().seconds().getName()); assertEquals("millis", GregorianChronology.getInstance().millis().getName()); assertEquals(false, GregorianChronology.getInstance().eras().isSupported()); assertEquals(true, GregorianChronology.getInstance().centuries().isSupported()); assertEquals(true, GregorianChronology.getInstance().years().isSupported()); assertEquals(true, GregorianChronology.getInstance().weekyears().isSupported()); assertEquals(true, GregorianChronology.getInstance().months().isSupported()); assertEquals(true, GregorianChronology.getInstance().weeks().isSupported()); assertEquals(true, GregorianChronology.getInstance().days().isSupported()); assertEquals(true, GregorianChronology.getInstance().halfdays().isSupported()); assertEquals(true, GregorianChronology.getInstance().hours().isSupported()); assertEquals(true, GregorianChronology.getInstance().minutes().isSupported()); assertEquals(true, GregorianChronology.getInstance().seconds().isSupported()); assertEquals(true, GregorianChronology.getInstance().millis().isSupported()); assertEquals(false, GregorianChronology.getInstance().centuries().isPrecise()); assertEquals(false, GregorianChronology.getInstance().years().isPrecise()); assertEquals(false, GregorianChronology.getInstance().weekyears().isPrecise()); assertEquals(false, GregorianChronology.getInstance().months().isPrecise()); assertEquals(false, GregorianChronology.getInstance().weeks().isPrecise()); assertEquals(false, GregorianChronology.getInstance().days().isPrecise()); assertEquals(false, GregorianChronology.getInstance().halfdays().isPrecise()); assertEquals(true, GregorianChronology.getInstance().hours().isPrecise()); assertEquals(true, GregorianChronology.getInstance().minutes().isPrecise()); assertEquals(true, GregorianChronology.getInstance().seconds().isPrecise()); assertEquals(true, GregorianChronology.getInstance().millis().isPrecise()); assertEquals(false, GregorianChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, GregorianChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, GregorianChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, GregorianChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, GregorianChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, GregorianChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, GregorianChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, GregorianChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, GregorianChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, GregorianChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, GregorianChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, GregorianChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, GregorianChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, GregorianChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, GregorianChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, GregorianChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, GregorianChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, GregorianChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, GregorianChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, GregorianChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, GregorianChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, GregorianChronology.getInstance(gmt).millis().isPrecise()); } public void testDateFields() { assertEquals("era", GregorianChronology.getInstance().era().getName()); assertEquals("centuryOfEra", GregorianChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", GregorianChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", GregorianChronology.getInstance().yearOfEra().getName()); assertEquals("year", GregorianChronology.getInstance().year().getName()); assertEquals("monthOfYear", GregorianChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", GregorianChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", GregorianChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", GregorianChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", GregorianChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", GregorianChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", GregorianChronology.getInstance().dayOfWeek().getName()); assertEquals(true, GregorianChronology.getInstance().era().isSupported()); assertEquals(true, GregorianChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, GregorianChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, GregorianChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, GregorianChronology.getInstance().year().isSupported()); assertEquals(true, GregorianChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, GregorianChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, GregorianChronology.getInstance().weekyear().isSupported()); assertEquals(true, GregorianChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, GregorianChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, GregorianChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, GregorianChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", GregorianChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", GregorianChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", GregorianChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", GregorianChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", GregorianChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", GregorianChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", GregorianChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", GregorianChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", GregorianChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", GregorianChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", GregorianChronology.getInstance().millisOfSecond().getName()); assertEquals(true, GregorianChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, GregorianChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, GregorianChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, GregorianChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, GregorianChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, GregorianChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, GregorianChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, GregorianChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, GregorianChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, GregorianChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, GregorianChronology.getInstance().millisOfSecond().isSupported()); } public void testMaximumValue() { YearMonthDay ymd1 = new YearMonthDay(1999, DateTimeConstants.FEBRUARY, 1); DateMidnight dm1 = new DateMidnight(1999, DateTimeConstants.FEBRUARY, 1); Chronology chrono = GregorianChronology.getInstance(); assertEquals(28, chrono.dayOfMonth().getMaximumValue(ymd1)); assertEquals(28, chrono.dayOfMonth().getMaximumValue(dm1.getMillis())); } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestLenientChronology.java0000644000175000017500000001613111564251364026356 0ustar ebourgebourg/* * Copyright 2001-2007 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.MockZone; /** * * @author Brian S O'Neill * @author Blair Martin */ public class TestLenientChronology extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLenientChronology.class); } public TestLenientChronology(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_setYear() { Chronology zone = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); DateTime dt = new DateTime(2007, 1, 1, 0, 0 ,0, 0, zone); assertEquals("2007-01-01T00:00:00.000Z", dt.toString()); dt = dt.withYear(2008); assertEquals("2008-01-01T00:00:00.000Z", dt.toString()); } //----------------------------------------------------------------------- public void test_setMonthOfYear() { Chronology zone = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); DateTime dt = new DateTime(2007, 1, 1, 0, 0 ,0, 0, zone); assertEquals("2007-01-01T00:00:00.000Z", dt.toString()); dt = dt.withMonthOfYear(13); assertEquals("2008-01-01T00:00:00.000Z", dt.toString()); dt = dt.withMonthOfYear(0); assertEquals("2007-12-01T00:00:00.000Z", dt.toString()); } //----------------------------------------------------------------------- public void test_setDayOfMonth() { Chronology zone = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); DateTime dt = new DateTime(2007, 1, 1, 0, 0 ,0, 0, zone); assertEquals("2007-01-01T00:00:00.000Z", dt.toString()); dt = dt.withDayOfMonth(32); assertEquals("2007-02-01T00:00:00.000Z", dt.toString()); dt = dt.withDayOfMonth(0); assertEquals("2007-01-31T00:00:00.000Z", dt.toString()); } //----------------------------------------------------------------------- public void test_setHourOfDay() { Chronology zone = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); DateTime dt = new DateTime(2007, 1, 1, 0, 0 ,0, 0, zone); assertEquals("2007-01-01T00:00:00.000Z", dt.toString()); dt = dt.withHourOfDay(24); assertEquals("2007-01-02T00:00:00.000Z", dt.toString()); dt = dt.withHourOfDay(-1); assertEquals("2007-01-01T23:00:00.000Z", dt.toString()); } //----------------------------------------------------------------------- //------------------------ Bug ------------------------------------------ //----------------------------------------------------------------------- public void testNearDstTransition() { // This is just a regression test. Test case provided by Blair Martin. int hour = 23; DateTime dt; dt = new DateTime(2006, 10, 29, hour, 0, 0, 0, ISOChronology.getInstance(DateTimeZone.forID("America/Los_Angeles"))); assertEquals(hour, dt.getHourOfDay()); // OK - no LenientChronology dt = new DateTime(2006, 10, 29, hour, 0, 0, 0, LenientChronology.getInstance (ISOChronology.getInstance(DateTimeZone.forOffsetHours(-8)))); assertEquals(hour, dt.getHourOfDay()); // OK - no TZ ID dt = new DateTime(2006, 10, 29, hour, 0, 0, 0, LenientChronology.getInstance (ISOChronology.getInstance(DateTimeZone.forID("America/Los_Angeles")))); assertEquals(hour, dt.getHourOfDay()); // Used to fail - hour was 22 } //----------------------------------------------------------------------- //------------------------ Bug [1755161] -------------------------------- //----------------------------------------------------------------------- /** Mock zone simulating America/Grand_Turk cutover at midnight 2007-04-01 */ private static long CUTOVER_TURK = 1175403600000L; private static int OFFSET_TURK = -18000000; // -05:00 private static final DateTimeZone MOCK_TURK = new MockZone(CUTOVER_TURK, OFFSET_TURK, 3600); //----------------------------------------------------------------------- public void test_MockTurkIsCorrect() { DateTime pre = new DateTime(CUTOVER_TURK - 1L, MOCK_TURK); assertEquals("2007-03-31T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_TURK + 1L, MOCK_TURK); assertEquals("2007-04-01T01:00:00.001-04:00", post.toString()); } public void test_lenientChrononolgy_Chicago() { DateTimeZone zone = DateTimeZone.forID("America/Chicago"); Chronology lenient = LenientChronology.getInstance(ISOChronology.getInstance(zone)); DateTime dt = new DateTime(2007, 3, 11, 2, 30, 0, 0, lenient); assertEquals("2007-03-11T03:30:00.000-05:00", dt.toString()); } public void test_lenientChrononolgy_Turk() { Chronology lenient = LenientChronology.getInstance(ISOChronology.getInstance(MOCK_TURK)); DateTime dt = new DateTime(2007, 4, 1, 0, 30, 0, 0, lenient); assertEquals("2007-04-01T01:30:00.000-04:00", dt.toString()); } public void test_strictChrononolgy_Chicago() { DateTimeZone zone = DateTimeZone.forID("America/Chicago"); Chronology lenient = StrictChronology.getInstance(ISOChronology.getInstance(zone)); try { new DateTime(2007, 3, 11, 2, 30, 0, 0, lenient); fail(); } catch (IllegalArgumentException ex) { // expected } } public void test_isoChrononolgy_Chicago() { DateTimeZone zone = DateTimeZone.forID("America/Chicago"); Chronology lenient = ISOChronology.getInstance(zone); try { new DateTime(2007, 3, 11, 2, 30, 0, 0, lenient); fail(); } catch (IllegalArgumentException ex) { // expected } } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestAll.java0000644000175000017500000000352112203425603023411 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Entry point for all tests in this package. * * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public class TestAll extends TestCase { public static boolean FAST = false; public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestBuddhistChronology.suite()); suite.addTest(TestCopticChronology.suite()); suite.addTest(TestEthiopicChronology.suite()); suite.addTest(TestGJChronology.suite()); suite.addTest(TestGregorianChronology.suite()); suite.addTest(TestIslamicChronology.suite()); suite.addTest(TestJulianChronology.suite()); suite.addTest(TestISOChronology.suite()); suite.addTest(TestLenientChronology.suite()); suite.addTest(TestGJDate.suite()); return suite; } public static void main(String args[]) { FAST = false; TestRunner.run(TestAll.suite()); } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestCopticChronology.java0000644000175000017500000007402411564251364026206 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.DateTime.Property; /** * This class is a Junit unit test for CopticChronology. * * @author Stephen Colebourne */ public class TestCopticChronology extends TestCase { private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; private static long SKIP = 1 * MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { SKIP = 1 * MILLIS_PER_DAY; return new TestSuite(TestCopticChronology.class); } public TestCopticChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, CopticChronology.getInstanceUTC().getZone()); assertSame(CopticChronology.class, CopticChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, CopticChronology.getInstance().getZone()); assertSame(CopticChronology.class, CopticChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, CopticChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, CopticChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, CopticChronology.getInstance(null).getZone()); assertSame(CopticChronology.class, CopticChronology.getInstance(TOKYO).getClass()); } //----------------------------------------------------------------------- public void testEquality() { assertSame(CopticChronology.getInstance(TOKYO), CopticChronology.getInstance(TOKYO)); assertSame(CopticChronology.getInstance(LONDON), CopticChronology.getInstance(LONDON)); assertSame(CopticChronology.getInstance(PARIS), CopticChronology.getInstance(PARIS)); assertSame(CopticChronology.getInstanceUTC(), CopticChronology.getInstanceUTC()); assertSame(CopticChronology.getInstance(), CopticChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(CopticChronology.getInstanceUTC(), CopticChronology.getInstance(LONDON).withUTC()); assertSame(CopticChronology.getInstanceUTC(), CopticChronology.getInstance(TOKYO).withUTC()); assertSame(CopticChronology.getInstanceUTC(), CopticChronology.getInstanceUTC().withUTC()); assertSame(CopticChronology.getInstanceUTC(), CopticChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(CopticChronology.getInstance(TOKYO), CopticChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(CopticChronology.getInstance(LONDON), CopticChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(CopticChronology.getInstance(PARIS), CopticChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(CopticChronology.getInstance(LONDON), CopticChronology.getInstance(TOKYO).withZone(null)); assertSame(CopticChronology.getInstance(PARIS), CopticChronology.getInstance().withZone(PARIS)); assertSame(CopticChronology.getInstance(PARIS), CopticChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("CopticChronology[Europe/London]", CopticChronology.getInstance(LONDON).toString()); assertEquals("CopticChronology[Asia/Tokyo]", CopticChronology.getInstance(TOKYO).toString()); assertEquals("CopticChronology[Europe/London]", CopticChronology.getInstance().toString()); assertEquals("CopticChronology[UTC]", CopticChronology.getInstanceUTC().toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", CopticChronology.getInstance().eras().getName()); assertEquals("centuries", CopticChronology.getInstance().centuries().getName()); assertEquals("years", CopticChronology.getInstance().years().getName()); assertEquals("weekyears", CopticChronology.getInstance().weekyears().getName()); assertEquals("months", CopticChronology.getInstance().months().getName()); assertEquals("weeks", CopticChronology.getInstance().weeks().getName()); assertEquals("days", CopticChronology.getInstance().days().getName()); assertEquals("halfdays", CopticChronology.getInstance().halfdays().getName()); assertEquals("hours", CopticChronology.getInstance().hours().getName()); assertEquals("minutes", CopticChronology.getInstance().minutes().getName()); assertEquals("seconds", CopticChronology.getInstance().seconds().getName()); assertEquals("millis", CopticChronology.getInstance().millis().getName()); assertEquals(false, CopticChronology.getInstance().eras().isSupported()); assertEquals(true, CopticChronology.getInstance().centuries().isSupported()); assertEquals(true, CopticChronology.getInstance().years().isSupported()); assertEquals(true, CopticChronology.getInstance().weekyears().isSupported()); assertEquals(true, CopticChronology.getInstance().months().isSupported()); assertEquals(true, CopticChronology.getInstance().weeks().isSupported()); assertEquals(true, CopticChronology.getInstance().days().isSupported()); assertEquals(true, CopticChronology.getInstance().halfdays().isSupported()); assertEquals(true, CopticChronology.getInstance().hours().isSupported()); assertEquals(true, CopticChronology.getInstance().minutes().isSupported()); assertEquals(true, CopticChronology.getInstance().seconds().isSupported()); assertEquals(true, CopticChronology.getInstance().millis().isSupported()); assertEquals(false, CopticChronology.getInstance().centuries().isPrecise()); assertEquals(false, CopticChronology.getInstance().years().isPrecise()); assertEquals(false, CopticChronology.getInstance().weekyears().isPrecise()); assertEquals(false, CopticChronology.getInstance().months().isPrecise()); assertEquals(false, CopticChronology.getInstance().weeks().isPrecise()); assertEquals(false, CopticChronology.getInstance().days().isPrecise()); assertEquals(false, CopticChronology.getInstance().halfdays().isPrecise()); assertEquals(true, CopticChronology.getInstance().hours().isPrecise()); assertEquals(true, CopticChronology.getInstance().minutes().isPrecise()); assertEquals(true, CopticChronology.getInstance().seconds().isPrecise()); assertEquals(true, CopticChronology.getInstance().millis().isPrecise()); assertEquals(false, CopticChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, CopticChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, CopticChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, CopticChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, CopticChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, CopticChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, CopticChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, CopticChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, CopticChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, CopticChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, CopticChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, CopticChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, CopticChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, CopticChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, CopticChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, CopticChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, CopticChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, CopticChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, CopticChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, CopticChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, CopticChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, CopticChronology.getInstance(gmt).millis().isPrecise()); } public void testDateFields() { assertEquals("era", CopticChronology.getInstance().era().getName()); assertEquals("centuryOfEra", CopticChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", CopticChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", CopticChronology.getInstance().yearOfEra().getName()); assertEquals("year", CopticChronology.getInstance().year().getName()); assertEquals("monthOfYear", CopticChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", CopticChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", CopticChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", CopticChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", CopticChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", CopticChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", CopticChronology.getInstance().dayOfWeek().getName()); assertEquals(true, CopticChronology.getInstance().era().isSupported()); assertEquals(true, CopticChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, CopticChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, CopticChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, CopticChronology.getInstance().year().isSupported()); assertEquals(true, CopticChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, CopticChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, CopticChronology.getInstance().weekyear().isSupported()); assertEquals(true, CopticChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, CopticChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, CopticChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, CopticChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", CopticChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", CopticChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", CopticChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", CopticChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", CopticChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", CopticChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", CopticChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", CopticChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", CopticChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", CopticChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", CopticChronology.getInstance().millisOfSecond().getName()); assertEquals(true, CopticChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, CopticChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, CopticChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, CopticChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, CopticChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, CopticChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, CopticChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, CopticChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, CopticChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, CopticChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, CopticChronology.getInstance().millisOfSecond().isSupported()); } //----------------------------------------------------------------------- public void testEpoch() { DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, COPTIC_UTC); assertEquals(new DateTime(284, 8, 29, 0, 0, 0, 0, JULIAN_UTC), epoch.withChronology(JULIAN_UTC)); } public void testEra() { assertEquals(1, CopticChronology.AM); try { new DateTime(-1, 13, 5, 0, 0, 0, 0, COPTIC_UTC); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */ public void testCalendar() { if (TestAll.FAST) { return; } System.out.println("\nTestCopticChronology.testCalendar"); DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, COPTIC_UTC); long millis = epoch.getMillis(); long end = new DateTime(3000, 1, 1, 0, 0, 0, 0, ISO_UTC).getMillis(); DateTimeField dayOfWeek = COPTIC_UTC.dayOfWeek(); DateTimeField dayOfYear = COPTIC_UTC.dayOfYear(); DateTimeField dayOfMonth = COPTIC_UTC.dayOfMonth(); DateTimeField monthOfYear = COPTIC_UTC.monthOfYear(); DateTimeField year = COPTIC_UTC.year(); DateTimeField yearOfEra = COPTIC_UTC.yearOfEra(); DateTimeField era = COPTIC_UTC.era(); int expectedDOW = new DateTime(284, 8, 29, 0, 0, 0, 0, JULIAN_UTC).getDayOfWeek(); int expectedDOY = 1; int expectedDay = 1; int expectedMonth = 1; int expectedYear = 1; while (millis < end) { int dowValue = dayOfWeek.get(millis); int doyValue = dayOfYear.get(millis); int dayValue = dayOfMonth.get(millis); int monthValue = monthOfYear.get(millis); int yearValue = year.get(millis); int yearOfEraValue = yearOfEra.get(millis); int monthLen = dayOfMonth.getMaximumValue(millis); if (monthValue < 1 || monthValue > 13) { fail("Bad month: " + millis); } // test era assertEquals(1, era.get(millis)); assertEquals("AM", era.getAsText(millis)); assertEquals("AM", era.getAsShortText(millis)); // test date assertEquals(expectedYear, yearValue); assertEquals(expectedYear, yearOfEraValue); assertEquals(expectedMonth, monthValue); assertEquals(expectedDay, dayValue); assertEquals(expectedDOW, dowValue); assertEquals(expectedDOY, doyValue); // test leap year assertEquals(yearValue % 4 == 3, year.isLeap(millis)); // test month length if (monthValue == 13) { assertEquals(yearValue % 4 == 3, monthOfYear.isLeap(millis)); if (yearValue % 4 == 3) { assertEquals(6, monthLen); } else { assertEquals(5, monthLen); } } else { assertEquals(30, monthLen); } // recalculate date expectedDOW = (((expectedDOW + 1) - 1) % 7) + 1; expectedDay++; expectedDOY++; if (expectedDay == 31 && expectedMonth < 13) { expectedDay = 1; expectedMonth++; } else if (expectedMonth == 13) { if (expectedYear % 4 == 3 && expectedDay == 7) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } else if (expectedYear % 4 != 3 && expectedDay == 6) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } } millis += SKIP; } } public void testSampleDate() { DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, ISO_UTC).withChronology(COPTIC_UTC); assertEquals(CopticChronology.AM, dt.getEra()); assertEquals(18, dt.getCenturyOfEra()); // TODO confirm assertEquals(20, dt.getYearOfCentury()); assertEquals(1720, dt.getYearOfEra()); assertEquals(1720, dt.getYear()); Property fld = dt.year(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(new DateTime(1721, 10, 2, 0, 0, 0, 0, COPTIC_UTC), fld.addToCopy(1)); assertEquals(10, dt.getMonthOfYear()); fld = dt.monthOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(13, fld.getMaximumValue()); assertEquals(13, fld.getMaximumValueOverall()); assertEquals(new DateTime(1721, 1, 2, 0, 0, 0, 0, COPTIC_UTC), fld.addToCopy(4)); assertEquals(new DateTime(1720, 1, 2, 0, 0, 0, 0, COPTIC_UTC), fld.addWrapFieldToCopy(4)); assertEquals(2, dt.getDayOfMonth()); fld = dt.dayOfMonth(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(30, fld.getMaximumValue()); assertEquals(30, fld.getMaximumValueOverall()); assertEquals(new DateTime(1720, 10, 3, 0, 0, 0, 0, COPTIC_UTC), fld.addToCopy(1)); assertEquals(DateTimeConstants.WEDNESDAY, dt.getDayOfWeek()); fld = dt.dayOfWeek(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(7, fld.getMaximumValue()); assertEquals(7, fld.getMaximumValueOverall()); assertEquals(new DateTime(1720, 10, 3, 0, 0, 0, 0, COPTIC_UTC), fld.addToCopy(1)); assertEquals(9 * 30 + 2, dt.getDayOfYear()); fld = dt.dayOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(365, fld.getMaximumValue()); assertEquals(366, fld.getMaximumValueOverall()); assertEquals(new DateTime(1720, 10, 3, 0, 0, 0, 0, COPTIC_UTC), fld.addToCopy(1)); assertEquals(0, dt.getHourOfDay()); assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testSampleDateWithZone() { DateTime dt = new DateTime(2004, 6, 9, 12, 0, 0, 0, PARIS).withChronology(COPTIC_UTC); assertEquals(CopticChronology.AM, dt.getEra()); assertEquals(1720, dt.getYear()); assertEquals(1720, dt.getYearOfEra()); assertEquals(10, dt.getMonthOfYear()); assertEquals(2, dt.getDayOfMonth()); assertEquals(10, dt.getHourOfDay()); // PARIS is UTC+2 in summer (12-2=10) assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testDurationYear() { // Leap 1723 DateTime dt20 = new DateTime(1720, 10, 2, 0, 0, 0, 0, COPTIC_UTC); DateTime dt21 = new DateTime(1721, 10, 2, 0, 0, 0, 0, COPTIC_UTC); DateTime dt22 = new DateTime(1722, 10, 2, 0, 0, 0, 0, COPTIC_UTC); DateTime dt23 = new DateTime(1723, 10, 2, 0, 0, 0, 0, COPTIC_UTC); DateTime dt24 = new DateTime(1724, 10, 2, 0, 0, 0, 0, COPTIC_UTC); DurationField fld = dt20.year().getDurationField(); assertEquals(COPTIC_UTC.years(), fld); assertEquals(1L * 365L * MILLIS_PER_DAY, fld.getMillis(1, dt20.getMillis())); assertEquals(2L * 365L * MILLIS_PER_DAY, fld.getMillis(2, dt20.getMillis())); assertEquals(3L * 365L * MILLIS_PER_DAY, fld.getMillis(3, dt20.getMillis())); assertEquals((4L * 365L + 1L) * MILLIS_PER_DAY, fld.getMillis(4, dt20.getMillis())); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getMillis(1)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 2, fld.getMillis(2)); assertEquals(1L * 365L * MILLIS_PER_DAY, fld.getMillis(1L, dt20.getMillis())); assertEquals(2L * 365L * MILLIS_PER_DAY, fld.getMillis(2L, dt20.getMillis())); assertEquals(3L * 365L * MILLIS_PER_DAY, fld.getMillis(3L, dt20.getMillis())); assertEquals((4L * 365L + 1L) * MILLIS_PER_DAY, fld.getMillis(4L, dt20.getMillis())); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getMillis(1L)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 2, fld.getMillis(2L)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getUnitMillis()); assertEquals(0, fld.getValue(1L * 365L * MILLIS_PER_DAY - 1L, dt20.getMillis())); assertEquals(1, fld.getValue(1L * 365L * MILLIS_PER_DAY, dt20.getMillis())); assertEquals(1, fld.getValue(1L * 365L * MILLIS_PER_DAY + 1L, dt20.getMillis())); assertEquals(1, fld.getValue(2L * 365L * MILLIS_PER_DAY - 1L, dt20.getMillis())); assertEquals(2, fld.getValue(2L * 365L * MILLIS_PER_DAY, dt20.getMillis())); assertEquals(2, fld.getValue(2L * 365L * MILLIS_PER_DAY + 1L, dt20.getMillis())); assertEquals(2, fld.getValue(3L * 365L * MILLIS_PER_DAY - 1L, dt20.getMillis())); assertEquals(3, fld.getValue(3L * 365L * MILLIS_PER_DAY, dt20.getMillis())); assertEquals(3, fld.getValue(3L * 365L * MILLIS_PER_DAY + 1L, dt20.getMillis())); assertEquals(3, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY - 1L, dt20.getMillis())); assertEquals(4, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY, dt20.getMillis())); assertEquals(4, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY + 1L, dt20.getMillis())); assertEquals(dt21.getMillis(), fld.add(dt20.getMillis(), 1)); assertEquals(dt22.getMillis(), fld.add(dt20.getMillis(), 2)); assertEquals(dt23.getMillis(), fld.add(dt20.getMillis(), 3)); assertEquals(dt24.getMillis(), fld.add(dt20.getMillis(), 4)); assertEquals(dt21.getMillis(), fld.add(dt20.getMillis(), 1L)); assertEquals(dt22.getMillis(), fld.add(dt20.getMillis(), 2L)); assertEquals(dt23.getMillis(), fld.add(dt20.getMillis(), 3L)); assertEquals(dt24.getMillis(), fld.add(dt20.getMillis(), 4L)); } public void testDurationMonth() { // Leap 1723 DateTime dt11 = new DateTime(1723, 11, 2, 0, 0, 0, 0, COPTIC_UTC); DateTime dt12 = new DateTime(1723, 12, 2, 0, 0, 0, 0, COPTIC_UTC); DateTime dt13 = new DateTime(1723, 13, 2, 0, 0, 0, 0, COPTIC_UTC); DateTime dt01 = new DateTime(1724, 1, 2, 0, 0, 0, 0, COPTIC_UTC); DurationField fld = dt11.monthOfYear().getDurationField(); assertEquals(COPTIC_UTC.months(), fld); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1, dt11.getMillis())); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2, dt11.getMillis())); assertEquals((2L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(3, dt11.getMillis())); assertEquals((3L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(4, dt11.getMillis())); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1)); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2)); assertEquals(13L * 30L * MILLIS_PER_DAY, fld.getMillis(13)); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1L, dt11.getMillis())); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2L, dt11.getMillis())); assertEquals((2L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(3L, dt11.getMillis())); assertEquals((3L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(4L, dt11.getMillis())); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1L)); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2L)); assertEquals(13L * 30L * MILLIS_PER_DAY, fld.getMillis(13L)); assertEquals(0, fld.getValue(1L * 30L * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(1, fld.getValue(1L * 30L * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(1, fld.getValue(1L * 30L * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(1, fld.getValue(2L * 30L * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(2, fld.getValue(2L * 30L * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(2, fld.getValue(2L * 30L * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(2, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(3, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(3, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(3, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(4, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(4, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(dt12.getMillis(), fld.add(dt11.getMillis(), 1)); assertEquals(dt13.getMillis(), fld.add(dt11.getMillis(), 2)); assertEquals(dt01.getMillis(), fld.add(dt11.getMillis(), 3)); assertEquals(dt12.getMillis(), fld.add(dt11.getMillis(), 1L)); assertEquals(dt13.getMillis(), fld.add(dt11.getMillis(), 2L)); assertEquals(dt01.getMillis(), fld.add(dt11.getMillis(), 3L)); } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestBuddhistChronology.java0000644000175000017500000005126011564251364026530 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.Period; /** * This class is a Junit unit test for BuddhistChronology. * * @author Stephen Colebourne */ public class TestBuddhistChronology extends TestCase { private static int SKIP = 1 * DateTimeConstants.MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology GJ_UTC = GJChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { SKIP = 1 * DateTimeConstants.MILLIS_PER_DAY; junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestBuddhistChronology.class); } public TestBuddhistChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, BuddhistChronology.getInstanceUTC().getZone()); assertSame(BuddhistChronology.class, BuddhistChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, BuddhistChronology.getInstance().getZone()); assertSame(BuddhistChronology.class, BuddhistChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, BuddhistChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, BuddhistChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, BuddhistChronology.getInstance(null).getZone()); assertSame(BuddhistChronology.class, BuddhistChronology.getInstance(TOKYO).getClass()); } //----------------------------------------------------------------------- public void testEquality() { assertSame(BuddhistChronology.getInstance(TOKYO), BuddhistChronology.getInstance(TOKYO)); assertSame(BuddhistChronology.getInstance(LONDON), BuddhistChronology.getInstance(LONDON)); assertSame(BuddhistChronology.getInstance(PARIS), BuddhistChronology.getInstance(PARIS)); assertSame(BuddhistChronology.getInstanceUTC(), BuddhistChronology.getInstanceUTC()); assertSame(BuddhistChronology.getInstance(), BuddhistChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(BuddhistChronology.getInstanceUTC(), BuddhistChronology.getInstance(LONDON).withUTC()); assertSame(BuddhistChronology.getInstanceUTC(), BuddhistChronology.getInstance(TOKYO).withUTC()); assertSame(BuddhistChronology.getInstanceUTC(), BuddhistChronology.getInstanceUTC().withUTC()); assertSame(BuddhistChronology.getInstanceUTC(), BuddhistChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(BuddhistChronology.getInstance(TOKYO), BuddhistChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(BuddhistChronology.getInstance(LONDON), BuddhistChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(BuddhistChronology.getInstance(PARIS), BuddhistChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(BuddhistChronology.getInstance(LONDON), BuddhistChronology.getInstance(TOKYO).withZone(null)); assertSame(BuddhistChronology.getInstance(PARIS), BuddhistChronology.getInstance().withZone(PARIS)); assertSame(BuddhistChronology.getInstance(PARIS), BuddhistChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("BuddhistChronology[Europe/London]", BuddhistChronology.getInstance(LONDON).toString()); assertEquals("BuddhistChronology[Asia/Tokyo]", BuddhistChronology.getInstance(TOKYO).toString()); assertEquals("BuddhistChronology[Europe/London]", BuddhistChronology.getInstance().toString()); assertEquals("BuddhistChronology[UTC]", BuddhistChronology.getInstanceUTC().toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", BuddhistChronology.getInstance().eras().getName()); assertEquals("centuries", BuddhistChronology.getInstance().centuries().getName()); assertEquals("years", BuddhistChronology.getInstance().years().getName()); assertEquals("weekyears", BuddhistChronology.getInstance().weekyears().getName()); assertEquals("months", BuddhistChronology.getInstance().months().getName()); assertEquals("weeks", BuddhistChronology.getInstance().weeks().getName()); assertEquals("days", BuddhistChronology.getInstance().days().getName()); assertEquals("halfdays", GregorianChronology.getInstance().halfdays().getName()); assertEquals("hours", BuddhistChronology.getInstance().hours().getName()); assertEquals("minutes", BuddhistChronology.getInstance().minutes().getName()); assertEquals("seconds", BuddhistChronology.getInstance().seconds().getName()); assertEquals("millis", BuddhistChronology.getInstance().millis().getName()); assertEquals(false, BuddhistChronology.getInstance().eras().isSupported()); assertEquals(true, BuddhistChronology.getInstance().centuries().isSupported()); assertEquals(true, BuddhistChronology.getInstance().years().isSupported()); assertEquals(true, BuddhistChronology.getInstance().weekyears().isSupported()); assertEquals(true, BuddhistChronology.getInstance().months().isSupported()); assertEquals(true, BuddhistChronology.getInstance().weeks().isSupported()); assertEquals(true, BuddhistChronology.getInstance().days().isSupported()); assertEquals(true, BuddhistChronology.getInstance().halfdays().isSupported()); assertEquals(true, BuddhistChronology.getInstance().hours().isSupported()); assertEquals(true, BuddhistChronology.getInstance().minutes().isSupported()); assertEquals(true, BuddhistChronology.getInstance().seconds().isSupported()); assertEquals(true, BuddhistChronology.getInstance().millis().isSupported()); assertEquals(false, BuddhistChronology.getInstance().centuries().isPrecise()); assertEquals(false, BuddhistChronology.getInstance().years().isPrecise()); assertEquals(false, BuddhistChronology.getInstance().weekyears().isPrecise()); assertEquals(false, BuddhistChronology.getInstance().months().isPrecise()); assertEquals(false, BuddhistChronology.getInstance().weeks().isPrecise()); assertEquals(false, BuddhistChronology.getInstance().days().isPrecise()); assertEquals(false, BuddhistChronology.getInstance().halfdays().isPrecise()); assertEquals(true, BuddhistChronology.getInstance().hours().isPrecise()); assertEquals(true, BuddhistChronology.getInstance().minutes().isPrecise()); assertEquals(true, BuddhistChronology.getInstance().seconds().isPrecise()); assertEquals(true, BuddhistChronology.getInstance().millis().isPrecise()); assertEquals(false, BuddhistChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, BuddhistChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, BuddhistChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, BuddhistChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, BuddhistChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, BuddhistChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, BuddhistChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, BuddhistChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, BuddhistChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, BuddhistChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, BuddhistChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, BuddhistChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, BuddhistChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, BuddhistChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, BuddhistChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, BuddhistChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, BuddhistChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, BuddhistChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, BuddhistChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, BuddhistChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, BuddhistChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, BuddhistChronology.getInstance(gmt).millis().isPrecise()); } public void testDateFields() { assertEquals("era", BuddhistChronology.getInstance().era().getName()); assertEquals("centuryOfEra", BuddhistChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", BuddhistChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", BuddhistChronology.getInstance().yearOfEra().getName()); assertEquals("year", BuddhistChronology.getInstance().year().getName()); assertEquals("monthOfYear", BuddhistChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", BuddhistChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", BuddhistChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", BuddhistChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", BuddhistChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", BuddhistChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", BuddhistChronology.getInstance().dayOfWeek().getName()); assertEquals(true, BuddhistChronology.getInstance().era().isSupported()); assertEquals(true, BuddhistChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, BuddhistChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, BuddhistChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, BuddhistChronology.getInstance().year().isSupported()); assertEquals(true, BuddhistChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, BuddhistChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, BuddhistChronology.getInstance().weekyear().isSupported()); assertEquals(true, BuddhistChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, BuddhistChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, BuddhistChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, BuddhistChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", BuddhistChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", BuddhistChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", BuddhistChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", BuddhistChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", BuddhistChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", BuddhistChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", BuddhistChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", BuddhistChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", BuddhistChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", BuddhistChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", BuddhistChronology.getInstance().millisOfSecond().getName()); assertEquals(true, BuddhistChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, BuddhistChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, BuddhistChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, BuddhistChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, BuddhistChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, BuddhistChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, BuddhistChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, BuddhistChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, BuddhistChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, BuddhistChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, BuddhistChronology.getInstance().millisOfSecond().isSupported()); } //----------------------------------------------------------------------- public void testEpoch() { DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); assertEquals(new DateTime(-543, 1, 1, 0, 0, 0, 0, JULIAN_UTC), epoch.withChronology(JULIAN_UTC)); } public void testEra() { assertEquals(1, BuddhistChronology.BE); try { new DateTime(-1, 13, 5, 0, 0, 0, 0, BUDDHIST_UTC); fail(); } catch (IllegalArgumentException ex) {} } public void testKeyYears() { DateTime bd = new DateTime(2513, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); DateTime jd = new DateTime(1970, 1, 1, 0, 0, 0, 0, GJ_UTC); assertEquals(jd, bd.withChronology(GJ_UTC)); assertEquals(2513, bd.getYear()); assertEquals(2513, bd.getYearOfEra()); assertEquals(2513, bd.plus(Period.weeks(1)).getWeekyear()); bd = new DateTime(2126, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); jd = new DateTime(1583, 1, 1, 0, 0, 0, 0, GJ_UTC); assertEquals(jd, bd.withChronology(GJ_UTC)); assertEquals(2126, bd.getYear()); assertEquals(2126, bd.getYearOfEra()); assertEquals(2126, bd.plus(Period.weeks(1)).getWeekyear()); bd = new DateTime(2125, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); jd = new DateTime(1582, 1, 1, 0, 0, 0, 0, GJ_UTC); assertEquals(jd, bd.withChronology(GJ_UTC)); assertEquals(2125, bd.getYear()); assertEquals(2125, bd.getYearOfEra()); assertEquals(2125, bd.plus(Period.weeks(1)).getWeekyear()); bd = new DateTime(544, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); jd = new DateTime(1, 1, 1, 0, 0, 0, 0, GJ_UTC); assertEquals(jd, bd.withChronology(GJ_UTC)); assertEquals(544, bd.getYear()); assertEquals(544, bd.getYearOfEra()); assertEquals(544, bd.plus(Period.weeks(1)).getWeekyear()); bd = new DateTime(543, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); jd = new DateTime(-1, 1, 1, 0, 0, 0, 0, GJ_UTC); assertEquals(jd, bd.withChronology(GJ_UTC)); assertEquals(543, bd.getYear()); assertEquals(543, bd.getYearOfEra()); assertEquals(543, bd.plus(Period.weeks(1)).getWeekyear()); bd = new DateTime(1, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); jd = new DateTime(-543, 1, 1, 0, 0, 0, 0, GJ_UTC); assertEquals(jd, bd.withChronology(GJ_UTC)); assertEquals(1, bd.getYear()); assertEquals(1, bd.getYearOfEra()); assertEquals(1, bd.plus(Period.weeks(1)).getWeekyear()); } public void testCalendar() { if (TestAll.FAST) { return; } System.out.println("\nTestBuddhistChronology.testCalendar"); DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, BUDDHIST_UTC); long millis = epoch.getMillis(); long end = new DateTime(3000, 1, 1, 0, 0, 0, 0, ISO_UTC).getMillis(); DateTimeField dayOfWeek = BUDDHIST_UTC.dayOfWeek(); DateTimeField weekOfWeekyear = GJ_UTC.weekOfWeekyear(); DateTimeField dayOfYear = BUDDHIST_UTC.dayOfYear(); DateTimeField dayOfMonth = BUDDHIST_UTC.dayOfMonth(); DateTimeField monthOfYear = BUDDHIST_UTC.monthOfYear(); DateTimeField year = BUDDHIST_UTC.year(); DateTimeField yearOfEra = BUDDHIST_UTC.yearOfEra(); DateTimeField era = BUDDHIST_UTC.era(); DateTimeField gjDayOfWeek = GJ_UTC.dayOfWeek(); DateTimeField gjWeekOfWeekyear = GJ_UTC.weekOfWeekyear(); DateTimeField gjDayOfYear = GJ_UTC.dayOfYear(); DateTimeField gjDayOfMonth = GJ_UTC.dayOfMonth(); DateTimeField gjMonthOfYear = GJ_UTC.monthOfYear(); DateTimeField gjYear = GJ_UTC.year(); DateTimeField gjYearOfEra = GJ_UTC.yearOfEra(); DateTimeField gjEra = GJ_UTC.era(); while (millis < end) { assertEquals(gjDayOfWeek.get(millis), dayOfWeek.get(millis)); assertEquals(gjDayOfYear.get(millis), dayOfYear.get(millis)); assertEquals(gjDayOfMonth.get(millis), dayOfMonth.get(millis)); assertEquals(gjMonthOfYear.get(millis), monthOfYear.get(millis)); assertEquals(gjWeekOfWeekyear.get(millis), weekOfWeekyear.get(millis)); assertEquals(1, era.get(millis)); int yearValue = gjYear.get(millis); if (yearValue <= 0) { yearValue++; } yearValue += 543; assertEquals(yearValue, year.get(millis)); assertEquals(yearValue, yearOfEra.get(millis)); millis += SKIP; } } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/0000755000175000017500000000000012205344143021576 5ustar ebourgebourgjoda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJDayOfYearField.java0000644000175000017500000000360311564251364026324 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * * @author Brian S O'Neill */ class TestGJDayOfYearField extends TestGJDateTimeField { public TestGJDayOfYearField(TestGJChronology chrono) { super(DateTimeFieldType.dayOfYear(), TestGJChronology.MILLIS_PER_DAY, chrono); } public int get(long millis) { int year = iChronology.gjYearFromMillis(millis); return (int)(iChronology.fixedFromMillis(millis) - iChronology.fixedFromGJ(year, 1, 1)) + 1; } public long set(long millis, int value) { return add(millis, (long) value - get(millis)); } public long add(long millis, long value) { return millis + value * TestGJChronology.MILLIS_PER_DAY; } public DurationField getRangeDurationField() { return iChronology.years(); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return 366; } public int getMaximumValue(long millis) { return iChronology.year().isLeap(millis) ? 366 : 365; } public long roundFloor(long millis) { return iChronology.getDateOnlyMillis(millis); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestJulianChronology.java0000644000175000017500000001204011564251364026575 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeField; /** * A reference Julian chronology implementation, intended for testing purposes * only. Correctness is favored over performance. The key functions for date * calculations are based on ones provided in "Calendrical Calculations", ISBN * 0-521-77752-6. * * @author Brian S O'Neill */ public final class TestJulianChronology extends TestGJChronology { private static final long JULIAN_EPOCH; static { // Constant as defined in book. JULIAN_EPOCH = new TestGregorianChronology().fixedFromGJ(0, 12, 30); } /** * Constructs with an epoch of 1969-12-19. */ public TestJulianChronology() { super(1969, 12, 19); } public TestJulianChronology(int epochYear, int epochMonth, int epochDay) { super(epochYear, epochMonth, epochDay); } public DateTimeField dayOfMonth() { return new TestJulianDayOfMonthField(this); } public DateTimeField weekyear() { return new TestJulianWeekyearField(this); } public DateTimeField monthOfYear() { return new TestJulianMonthOfYearField(this); } public DateTimeField year() { return new TestJulianYearField(this); } public String toString() { return "TestJulianChronology"; } long millisPerYear() { return (long)(365.25 * MILLIS_PER_DAY); } long millisPerMonth() { return (long)(365.25 * MILLIS_PER_DAY / 12); } boolean isLeapYear(int year) { if (year == 0) { throw new IllegalArgumentException("Illegal year: " + year); } return mod(year, 4) == (year > 0 ? 0 : 3); } /** * @return days from 0001-01-01 */ long fixedFromGJ(int year, int monthOfYear, int dayOfMonth) { if (year == 0) { throw new IllegalArgumentException("Illegal year: " + year); } int y = (year < 0) ? year + 1 : year; long y_m1 = y - 1; long f = JULIAN_EPOCH - 1 + 365 * y_m1 + div(y_m1, 4) + div(367 * monthOfYear - 362, 12) + dayOfMonth; if (monthOfYear > 2) { f += isLeapYear(year) ? -1 : -2; } return f; } /** * @param date days from 0001-01-01 * @return gj year */ int gjYearFromFixed(long date) { return gjFromFixed(date)[0]; } /** * @param date days from 0001-01-01 * @return gj year, monthOfYear, dayOfMonth */ int[] gjFromFixed(long date) { long approx = div(4 * (date - JULIAN_EPOCH) + 1464, 1461); long year = (approx <= 0) ? approx - 1 : approx; int year_i = (int)year; if (year_i != year) { throw new RuntimeException("year cannot be cast to an int: " + year); } long priorDays = date - fixedFromGJ(year_i, 1, 1); long correction; if (date < fixedFromGJ(year_i, 3, 1)) { correction = 0; } else if (isLeapYear(year_i)) { correction = 1; } else { correction = 2; } int monthOfYear = (int)div(12 * (priorDays + correction) + 373, 367); int day = (int)(date - fixedFromGJ(year_i, monthOfYear, 1) + 1); return new int[]{year_i, monthOfYear, day}; } long fixedFromISO(int weekyear, int weekOfWeekyear, int dayOfWeek) { if (weekyear == 0) { throw new IllegalArgumentException("Illegal weekyear: " + weekyear); } if (weekyear == 1) { weekyear = -1; } else { weekyear--; } return nthWeekday(weekOfWeekyear, 0, weekyear, 12, 28) + dayOfWeek; } /** * @param date days from 0001-01-01 * @return iso weekyear, weekOfWeekyear, dayOfWeek (1=Monday to 7) */ int[] isoFromFixed(long date) { int weekyear = gjYearFromFixed(date - 3); int nextWeekyear; if (weekyear == -1) { nextWeekyear = 1; } else { nextWeekyear = weekyear + 1; } if (date >= fixedFromISO(nextWeekyear, 1, 1)) { weekyear = nextWeekyear; } int weekOfWeekyear = (int)(div(date - fixedFromISO(weekyear, 1, 1), 7) + 1); int dayOfWeek = (int)amod(date, 7); return new int[]{weekyear, weekOfWeekyear, dayOfWeek}; } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJMonthOfYearField.java0000644000175000017500000000601511564251364026674 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * * @author Brian S O'Neill */ class TestGJMonthOfYearField extends TestGJDateTimeField { public TestGJMonthOfYearField(TestGJChronology chrono) { super(DateTimeFieldType.monthOfYear(), chrono.millisPerMonth(), chrono); } public int get(long millis) { return iChronology.gjFromMillis(millis)[1]; } public long set(long millis, int value) { long timeOnlyMillis = iChronology.getTimeOnlyMillis(millis); int[] ymd = iChronology.gjFromMillis(millis); // First set to start of month... millis = iChronology.millisFromGJ(ymd[0], value, 1); // ...and use dayOfMonth field to check range. int maxDay = iChronology.dayOfMonth().getMaximumValue(millis); if (ymd[2] > maxDay) { ymd[2] = maxDay; } return timeOnlyMillis + iChronology.millisFromGJ(ymd[0], value, ymd[2]); } public long add(long millis, long value) { int newYear = iChronology.year().get(millis) + (int)TestGJChronology.div(value, 12); int newMonth = get(millis) + (int)TestGJChronology.mod(value, 12); if (newMonth > 12) { newYear++; newMonth -= 12; } int newDay = iChronology.dayOfMonth().get(millis); millis = iChronology.getTimeOnlyMillis(millis) + iChronology.millisFromGJ(newYear, newMonth, newDay); while (get(millis) != newMonth) { millis = iChronology.dayOfYear().add(millis, -1); } return millis; } public boolean isLeap(long millis) { int[] ymd = iChronology.gjFromMillis(millis); return ymd[1] == 2 && iChronology.isLeapYear(ymd[0]); } public int getLeapAmount(long millis) { return isLeap(millis) ? 1 : 0; } public DurationField getLeapDurationField() { return iChronology.days(); } public DurationField getRangeDurationField() { return iChronology.years(); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return 12; } public long roundFloor(long millis) { int[] ymd = iChronology.gjFromMillis(millis); return iChronology.millisFromGJ(ymd[0], ymd[1], 1); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJDateTimeField.java0000644000175000017500000000246211564251364026177 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.field.ImpreciseDateTimeField; /** * * @author Brian S O'Neill */ abstract class TestGJDateTimeField extends ImpreciseDateTimeField { protected final TestGJChronology iChronology; public TestGJDateTimeField(DateTimeFieldType type, long unitMillis, TestGJChronology chrono) { super(type, unitMillis); iChronology = chrono; } public boolean isLenient() { return false; } public long add(long instant, int value) { return add(instant, (long)value); } public abstract long add(long instant, long value); } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGregorianChronology.java0000644000175000017500000001044311564251364027275 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; /** * A reference Gregorian chronology implementation, intended for testing * purposes only. Correctness is favored over performance. The key functions * for date calculations are based on ones provided in "Calendrical * Calculations", ISBN 0-521-77752-6. * * @author Brian S O'Neill */ public final class TestGregorianChronology extends TestGJChronology { /** * Constructs with an epoch of 1970-01-01. */ public TestGregorianChronology() { super(1970, 1, 1); } public TestGregorianChronology(int epochYear, int epochMonth, int epochDay) { super(epochYear, epochMonth, epochDay); } public String toString() { return "TestGregorianChronology"; } long millisPerYear() { return (long)(365.2425 * MILLIS_PER_DAY); } long millisPerMonth() { return (long)(365.2425 * MILLIS_PER_DAY / 12); } boolean isLeapYear(int year) { if (mod(year, 4) == 0) { int t = (int)mod(year, 400); if (t != 100 && t != 200 && t != 300) { return true; } } return false; } /** * @return days from 0001-01-01 */ long fixedFromGJ(int year, int monthOfYear, int dayOfMonth) { long year_m1 = year - 1; long f = 365 * year_m1 + div(year_m1, 4) - div(year_m1, 100) + div(year_m1, 400) + div(367 * monthOfYear - 362, 12) + dayOfMonth; if (monthOfYear > 2) { f += isLeapYear(year) ? -1 : -2; } return f; } /** * @param date days from 0001-01-01 * @return gj year */ int gjYearFromFixed(long date) { long d0 = date - 1; long n400 = div(d0, 146097); long d1 = mod(d0, 146097); long n100 = div(d1, 36524); long d2 = mod(d1, 36524); long n4 = div(d2, 1461); long d3 = mod(d2, 1461); long n1 = div(d3, 365); long year = 400 * n400 + 100 * n100 + 4 * n4 + n1; if (!(n100 == 4 || n1 == 4)) { year += 1; } int year_i = (int)year; if (year_i == year) { return year_i; } else { throw new RuntimeException("year cannot be cast to an int: " + year); } } /** * @param date days from 0001-01-01 * @return gj year, monthOfYear, dayOfMonth */ int[] gjFromFixed(long date) { int year = gjYearFromFixed(date); long priorDays = date - fixedFromGJ(year, 1, 1); long correction; if (date < fixedFromGJ(year, 3, 1)) { correction = 0; } else if (isLeapYear(year)) { correction = 1; } else { correction = 2; } int monthOfYear = (int)div(12 * (priorDays + correction) + 373, 367); int day = (int)(date - fixedFromGJ(year, monthOfYear, 1) + 1); return new int[]{year, monthOfYear, day}; } long fixedFromISO(int weekyear, int weekOfWeekyear, int dayOfWeek) { return nthWeekday(weekOfWeekyear, 0, weekyear - 1, 12, 28) + dayOfWeek; } /** * @param date days from 0001-01-01 * @return iso weekyear, weekOfWeekyear, dayOfWeek (1=Monday to 7) */ int[] isoFromFixed(long date) { int weekyear = gjYearFromFixed(date - 3); if (date >= fixedFromISO(weekyear + 1, 1, 1)) { weekyear += 1; } int weekOfWeekyear = (int)(div(date - fixedFromISO(weekyear, 1, 1), 7) + 1); int dayOfWeek = (int)amod(date, 7); return new int[]{weekyear, weekOfWeekyear, dayOfWeek}; } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJDayOfMonthField.java0000644000175000017500000000404311564251364026510 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * * @author Brian S O'Neill */ class TestGJDayOfMonthField extends TestGJDateTimeField { public TestGJDayOfMonthField(TestGJChronology chrono) { super(DateTimeFieldType.dayOfMonth(), TestGJChronology.MILLIS_PER_DAY, chrono); } public int get(long millis) { return iChronology.gjFromMillis(millis)[2]; } public long set(long millis, int value) { int[] ymd = iChronology.gjFromMillis(millis); return iChronology.getTimeOnlyMillis(millis) + iChronology.millisFromGJ(ymd[0], ymd[1], value); } public long add(long millis, long value) { return millis + value * TestGJChronology.MILLIS_PER_DAY; } public DurationField getRangeDurationField() { return iChronology.months(); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return 31; } public int getMaximumValue(long millis) { int[] lengths = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (iChronology.year().isLeap(millis)) { lengths[2] = 29; } return lengths[iChronology.monthOfYear().get(millis)]; } public long roundFloor(long millis) { return iChronology.getDateOnlyMillis(millis); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestAll.java0000644000175000017500000000265412203425552024022 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all tests in this package. * * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new MainTest(1000, 0, 1345435247779935L)); suite.addTest(new MainTest(1000, 1, 1345435247779935L)); return suite; } public static void main(String args[]) { String[] testCaseName = { TestAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/MainTest.java0000644000175000017500000004457611564251364024216 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import java.util.Random; import junit.framework.TestCase; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeField; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.JulianChronology; /** * Tests either the Julian or Gregorian chronology from org.joda.time.chrono.gj * against the implementations in this package. It tests all the date fields * against their principal methods. *

* Randomly generated values are fed into the DateTimeField methods and the * results are compared between the two chronologies. If any result doesn't * match, an error report is generated and the program exits. Each time this * test program is run, the pseudo random number generator is seeded with the * same value. This ensures consistent results between test runs. *

* The main method accepts three optional arguments: iterations, mode, seed. By * default, iterations is set to 1,000,000. The test will take several minutes * to run, depending on the computer's performance. Every 5 seconds a progress * message is printed. *

* The mode can be either 'g' for proleptic gregorian (the default) or 'j' for * proleptic julian. To override the default random number generator seed, pass * in a third argument which accepts a long signed integer. * * @author Brian S O'Neill */ public class MainTest extends TestCase { public static final int GREGORIAN_MODE = 0; public static final int JULIAN_MODE = 1; private static final long MILLIS_PER_YEAR = (long)365.2425 * 24 * 60 * 60 * 1000; private static final long _1000_YEARS = 1000 * MILLIS_PER_YEAR; private static final long _500_YEARS = 500 * MILLIS_PER_YEAR; private static final long MAX_MILLIS = (10000 - 1970) * MILLIS_PER_YEAR; private static final long MIN_MILLIS = (-10000 - 1970) * MILLIS_PER_YEAR; // Show progess reports every 5 seconds. private static final long UPDATE_INTERVAL = 5000; /** * Arguments: iterations [mode [seed]] */ public static void main(String[] args) throws Exception { int iterations = 1000000; int mode = GREGORIAN_MODE; long seed = 1345435247779935L; if (args.length > 0) { iterations = Integer.parseInt(args[0]); if (args.length > 1) { if (args[1].startsWith("g")) { mode = GREGORIAN_MODE; } else if (args[1].startsWith("j")) { mode = JULIAN_MODE; } else { throw new IllegalArgumentException ("Unknown mode: " + args[1]); } if (args.length > 2) { seed = Long.parseLong(args[2]); } } } new MainTest(iterations, mode, seed).testChronology(); } //----------------------------------------------------------------------- private final int iIterations; private final int iMode; private final long iSeed; private final Chronology iTest; private final Chronology iActual; /** * @param iterations number of test iterations to perform * @param mode GREGORIAN_MODE or JULIAN_MODE,0=Gregorian, 1=Julian * @param seed seed for random number generator */ public MainTest(int iterations, int mode, long seed) { super("testChronology"); iIterations = iterations; iMode = mode; iSeed = seed; if (mode == GREGORIAN_MODE) { iTest = new TestGregorianChronology(); iActual = GregorianChronology.getInstanceUTC(); } else { iTest = new TestJulianChronology(); iActual = JulianChronology.getInstanceUTC(); } } //----------------------------------------------------------------------- /** * Main junit test */ public void testChronology() { int iterations = iIterations; long seed = iSeed; String modeStr; if (iMode == GREGORIAN_MODE) { modeStr = "Gregorian"; } else { modeStr = "Julian"; } System.out.println("\nTesting " + modeStr + " chronology over " + iterations + " iterations"); Random rnd = new Random(seed); long updateMillis = System.currentTimeMillis() + UPDATE_INTERVAL; for (int i=0; i= updateMillis) { updateMillis = now + UPDATE_INTERVAL; double complete = ((int)((double)i / iterations * 1000.0)) / 10d; if (complete < 100) { System.out.println("" + complete + "% complete (i=" + i + ")"); } } long millis = randomMillis(rnd); int value = rnd.nextInt(200) - 100; // millis2 is used for difference tests. long millis2 = millis + rnd.nextLong() % _1000_YEARS - _500_YEARS; try { testFields(millis, value, millis2); } catch (RuntimeException e) { System.out.println("Failure index: " + i); System.out.println("Test millis: " + millis); System.out.println("Test value: " + value); System.out.println("Test millis2: " + millis2); fail(e.getMessage()); } } System.out.println("100% complete (i=" + iterations + ")"); } //----------------------------------------------------------------------- private void testFields(long millis, int value, long millis2) { testField(iTest.year(), iActual.year(), millis, value, millis2); testField(iTest.monthOfYear(), iActual.monthOfYear(), millis, value, millis2); testField(iTest.dayOfMonth(), iActual.dayOfMonth(), millis, value, millis2); testField(iTest.weekyear(), iActual.weekyear(), millis, value, millis2); testField(iTest.weekOfWeekyear(), iActual.weekOfWeekyear(), millis, value, millis2); testField(iTest.dayOfWeek(), iActual.dayOfWeek(), millis, value, millis2); testField(iTest.dayOfYear(), iActual.dayOfYear(), millis, value, millis2); } private void testField(DateTimeField fieldA, DateTimeField fieldB, long millis, int value, long millis2) { int a, b; long x, y; boolean m, n; // get test a = fieldA.get(millis); b = fieldB.get(millis); testValue(fieldA, fieldB, "get", millis, a, b); // getMaximumValue test // Restrict this test to the fields that matter. Class fieldClass = fieldA.getClass(); if (fieldClass == TestGJDayOfYearField.class || fieldClass == TestGJDayOfMonthField.class || fieldClass == TestGJWeekOfWeekyearField.class) { a = fieldA.getMaximumValue(millis); b = fieldB.getMaximumValue(millis); testValue(fieldA, fieldB, "getMaximumValue", millis, a, b); } // set test a = getWrappedValue (value, fieldA.getMinimumValue(millis), fieldA.getMaximumValue(millis)); b = getWrappedValue (value, fieldB.getMinimumValue(millis), fieldB.getMaximumValue(millis)); if (iMode == JULIAN_MODE && a == 0 && (fieldA.getName().equals("year") || fieldA.getName().equals("weekyear"))) { // Exclude setting Julian year of zero. } else { x = fieldA.set(millis, a); y = fieldB.set(millis, b); testMillis(fieldA, fieldB, "set", millis, x, y, a, b); } // roundFloor test x = fieldA.roundFloor(millis); y = fieldB.roundFloor(millis); testMillis(fieldA, fieldB, "roundFloor", millis, x, y); // roundCeiling test x = fieldA.roundCeiling(millis); y = fieldB.roundCeiling(millis); testMillis(fieldA, fieldB, "roundCeiling", millis, x, y); // roundHalfFloor test x = fieldA.roundHalfFloor(millis); y = fieldB.roundHalfFloor(millis); testMillis(fieldA, fieldB, "roundHalfFloor", millis, x, y); // roundHalfEven test x = fieldA.roundHalfEven(millis); y = fieldB.roundHalfEven(millis); testMillis(fieldA, fieldB, "roundHalfEven", millis, x, y); // remainder test x = fieldA.remainder(millis); y = fieldB.remainder(millis); testMillis(fieldA, fieldB, "remainder", millis, x, y); // add test x = fieldA.add(millis, value); y = fieldB.add(millis, value); testMillis(fieldA, fieldB, "add", millis, x, y); // addWrapField test x = fieldA.addWrapField(millis, value); y = fieldB.addWrapField(millis, value); testMillis(fieldA, fieldB, "addWrapField", millis, x, y); // getDifference test x = fieldA.getDifference(millis, millis2); y = fieldB.getDifference(millis, millis2); try { testValue(fieldA, fieldB, "getDifference", millis, x, y); } catch (RuntimeException e) { System.out.println("Test datetime 2: " + makeDatetime(millis2)); throw e; } // isLeap test m = fieldA.isLeap(millis); n = fieldB.isLeap(millis); testBoolean(fieldA, fieldB, "isLeap", millis, m, n); // getLeapAmount test a = fieldA.getLeapAmount(millis); b = fieldB.getLeapAmount(millis); testValue(fieldA, fieldB, "getLeapAmount", millis, a, b); } private int getWrappedValue(int value, int minValue, int maxValue) { if (minValue >= maxValue) { throw new IllegalArgumentException("MIN > MAX"); } int wrapRange = maxValue - minValue + 1; value -= minValue; if (value >= 0) { return (value % wrapRange) + minValue; } int remByRange = (-value) % wrapRange; if (remByRange == 0) { return 0 + minValue; } return (wrapRange - remByRange) + minValue; } private void testValue(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, long valueA, long valueB) { if (valueA != valueB) { failValue(fieldA, fieldB, method, millis, valueA, valueB); } } private void testMillis(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, long millisA, long millisB) { if (millisA != millisB) { failMillis(fieldA, fieldB, method, millis, millisA, millisB); } } private void testMillis(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, long millisA, long millisB, int valueA, int valueB) { if (millisA != millisB) { failMillis(fieldA, fieldB, method, millis, millisA, millisB, valueA, valueB); } } private void testBoolean(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, boolean boolA, boolean boolB) { if (boolA != boolB) { failBoolean(fieldA, fieldB, method, millis, boolA, boolB); } } private void failValue(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, long valueA, long valueB) { System.out.println("Failure on " + makeName(fieldA, fieldB) + "." + method); System.out.println(fieldA.getClass().getName() + "\n\tvs. " + fieldB.getClass().getName()); System.out.println("Datetime: " + makeDatetime(millis)); System.out.println("Millis from 1970: " + millis); System.out.println(valueA + " != " + valueB); throw new RuntimeException(); } private void failMillis(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, long millisA, long millisB) { System.out.println("Failure on " + makeName(fieldA, fieldB) + "." + method); System.out.println(fieldA.getClass().getName() + "\n\tvs. " + fieldB.getClass().getName()); System.out.println("Datetime: " + makeDatetime(millis)); System.out.println("Millis from 1970: " + millis); System.out.println(makeDatetime(millisA) + " != " + makeDatetime(millisB)); System.out.println(millisA + " != " + millisB); System.out.println("Original value as reported by first field: " + fieldA.get(millis)); System.out.println("Original value as reported by second field: " + fieldB.get(millis)); System.out.println("First new value as reported by first field: " + fieldA.get(millisA)); System.out.println("First new value as reported by second field: " + fieldB.get(millisA)); System.out.println("Second new value as reported by first field: " + fieldA.get(millisB)); System.out.println("Second new value as reported by second field: " + fieldB.get(millisB)); throw new RuntimeException(); } private void failMillis(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, long millisA, long millisB, int valueA, int valueB) { System.out.println("Failure on " + makeName(fieldA, fieldB) + "." + method); System.out.println(fieldA.getClass().getName() + "\n\tvs. " + fieldB.getClass().getName()); System.out.println("Datetime: " + makeDatetime(millis)); System.out.println("Millis from 1970: " + millis); System.out.println(makeDatetime(millisA) + " != " + makeDatetime(millisB)); System.out.println(millisA + " != " + millisB); System.out.println("Original value as reported by first field: " + fieldA.get(millis)); System.out.println("Original value as reported by second field: " + fieldB.get(millis)); System.out.println("First new value as reported by first field: " + fieldA.get(millisA)); System.out.println("First new value as reported by second field: " + fieldB.get(millisA)); System.out.println("Second new value as reported by first field: " + fieldA.get(millisB)); System.out.println("Second new value as reported by second field: " + fieldB.get(millisB)); System.out.println("Value to set for first field: " + valueA); System.out.println("Value to set for second field: " + valueB); throw new RuntimeException(); } private void failBoolean(DateTimeField fieldA, DateTimeField fieldB, String method, long millis, boolean boolA, boolean boolB) { System.out.println("Failure on " + makeName(fieldA, fieldB) + "." + method); System.out.println(fieldA.getClass().getName() + "\n\tvs. " + fieldB.getClass().getName()); System.out.println("Datetime: " + makeDatetime(millis)); System.out.println("Millis from 1970: " + millis); System.out.println(boolA + " != " + boolB); throw new RuntimeException(); } private String makeName(DateTimeField fieldA, DateTimeField fieldB) { if (fieldA.getName().equals(fieldB.getName())) { return fieldA.getName(); } else { return fieldA.getName() + "/" + fieldB.getName(); } } private String makeDatetime(long millis) { return makeDatetime(millis, iActual); } private String makeDatetime(long millis, Chronology chrono) { return chrono.dayOfWeek().getAsShortText(millis) + " " + new DateTime(millis, chrono).toString() + " / " + chrono.weekyear().get(millis) + "-W" + chrono.weekOfWeekyear().get(millis) + "-" + chrono.dayOfWeek().get(millis); } private String makeDate(long millis) { return makeDate(millis, iActual); } private String makeDate(long millis, Chronology chrono) { return chrono.dayOfWeek().getAsShortText(millis) + " " + new DateTime(millis, chrono).toString("yyyy-MM-dd") + " / " + chrono.weekyear().get(millis) + "-W" + chrono.weekOfWeekyear().get(millis) + "-" + chrono.dayOfWeek().get(millis); } //----------------------------------------------------------------------- private static long randomMillis(Random rnd) { long millis = rnd.nextLong(); if (millis >= 0) { millis = millis % MAX_MILLIS; } else { millis = millis % -MIN_MILLIS; } return millis; } private static void dump(Chronology chrono, long millis) { System.out.println("year: " + chrono.year().get(millis)); System.out.println("monthOfYear: " + chrono.monthOfYear().get(millis)); System.out.println("dayOfMonth: " + chrono.dayOfMonth().get(millis)); System.out.println("weekyear: " + chrono.weekyear().get(millis)); System.out.println("weekOfWeekyear: " + chrono.weekOfWeekyear().get(millis)); System.out.println("dayOfWeek: " + chrono.dayOfWeek().get(millis)); System.out.println("dayOfYear: " + chrono.dayOfYear().get(millis)); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestJulianWeekyearField.java0000644000175000017500000000334711564251364027204 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.field.FieldUtils; /** * * @author Brian S O'Neill */ class TestJulianWeekyearField extends TestGJWeekyearField { public TestJulianWeekyearField(TestJulianChronology chrono) { super(chrono); } public long addWrapField(long millis, int value) { int weekyear = get(millis); int wrapped = FieldUtils.getWrappedValue (weekyear, value, getMinimumValue(), getMaximumValue()); return add(millis, (long) wrapped - weekyear); } public long add(long millis, long value) { int weekyear = get(millis); int newWeekyear = weekyear + FieldUtils.safeToInt(value); if (weekyear < 0) { if (newWeekyear >= 0) { newWeekyear++; } } else { if (newWeekyear <= 0) { newWeekyear--; } } return set(millis, newWeekyear); } public int getMinimumValue() { return -100000000; } public int getMaximumValue() { return 100000000; } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestJulianMonthOfYearField.java0000644000175000017500000000365311564251364027623 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; /** * * @author Brian S O'Neill */ class TestJulianMonthOfYearField extends TestGJMonthOfYearField { public TestJulianMonthOfYearField(TestJulianChronology chrono) { super(chrono); } public int get(long millis) { return iChronology.gjFromMillis(millis)[1]; } public long add(long millis, long value) { int year = iChronology.year().get(millis); int newYear = year + (int)TestGJChronology.div(value, 12); if (year < 0) { if (newYear >= 0) { newYear++; } } else { if (newYear <= 0) { newYear--; } } int newMonth = get(millis) + (int)TestGJChronology.mod(value, 12); if (newMonth > 12) { if (newYear == -1) { newYear = 1; } else { newYear++; } newMonth -= 12; } int newDay = iChronology.dayOfMonth().get(millis); millis = iChronology.getTimeOnlyMillis(millis) + iChronology.millisFromGJ(newYear, newMonth, newDay); while (get(millis) != newMonth) { millis = iChronology.dayOfYear().add(millis, -1); } return millis; } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJDayOfWeekField.java0000644000175000017500000000342211564251364026316 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * * @author Brian S O'Neill */ class TestGJDayOfWeekField extends TestGJDateTimeField { public TestGJDayOfWeekField(TestGJChronology chrono) { super(DateTimeFieldType.dayOfWeek(), TestGJChronology.MILLIS_PER_DAY, chrono); } public int get(long millis) { int dayOfWeek = (int) TestGJChronology.mod(iChronology.fixedFromMillis(millis), 7); if (dayOfWeek == 0) { dayOfWeek = 7; } return dayOfWeek; } public long set(long millis, int value) { return add(millis, (long) value - get(millis)); } public long add(long millis, long value) { return millis + value * TestGJChronology.MILLIS_PER_DAY; } public DurationField getRangeDurationField() { return iChronology.weeks(); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return 7; } public long roundFloor(long millis) { return iChronology.getDateOnlyMillis(millis); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJWeekyearField.java0000644000175000017500000000462311564251364026260 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * * @author Brian S O'Neill */ class TestGJWeekyearField extends TestGJDateTimeField { public TestGJWeekyearField(TestGJChronology chrono) { super(DateTimeFieldType.weekyear(), chrono.millisPerYear(), chrono); } public int get(long millis) { return iChronology.isoFromMillis(millis)[0]; } public long set(long millis, int value) { int[] wwd = iChronology.isoFromMillis(millis); millis = iChronology.getTimeOnlyMillis(millis) + iChronology.millisFromISO(value, wwd[1], wwd[2]); if (wwd[1] == 53) { int[] wwd2 = iChronology.isoFromMillis(millis); if (wwd2[0] != value) { // Set year doesn't have 53 weeks, so back off a week. millis = iChronology.dayOfYear().add(millis, -7); } } return millis; } public long add(long millis, long value) { return set(millis, (int)(get(millis) + value)); } public boolean isLeap(long millis) { return iChronology.weekOfWeekyear().getMaximumValue(millis) > 52; } public int getLeapAmount(long millis) { return iChronology.weekOfWeekyear().getMaximumValue(millis) - 52; } public DurationField getLeapDurationField() { return iChronology.weeks(); } public DurationField getRangeDurationField() { return null; } public int getMinimumValue() { return -100000000; } public int getMaximumValue() { return 100000000; } public long roundFloor(long millis) { return iChronology.millisFromISO(get(millis), 1, 1); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJChronology.java0000644000175000017500000002052111564251364025656 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.chrono.BaseChronology; /** * A reference Gregorian/Julian chronology implementation, intended for testing * purposes only. Correctness is favored over performance. The key functions * for date calculations are based on ones provided in "Calendrical * Calculations", ISBN 0-521-77752-6. * *

In theory, this class can be used to test any other Gregorian/Julian * chronology as long as almost all datetime fields are implemented differently * between the two. Fields that would most likely be implemented the same are * not supported by this class. * *

Unsupported features *

    *
  • time zones *
  • time of day *
  • year of era *
  • year of century *
  • century of era *
  • era *
* * @author Brian S O'Neill */ abstract class TestGJChronology extends BaseChronology { static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; /** * Divide with round-negative behavior. * * @param divisor must be positive */ static long div(long dividend, long divisor) { if (divisor < 0) { throw new IllegalArgumentException("divisor must be positive: " + divisor); } if (dividend >= 0) { return dividend / divisor; } else { return (dividend + 1) / divisor - 1; } } /** * Modulus with round-negative behavior, result is always positive. * * @param divisor must be positive */ static long mod(long dividend, long divisor) { if (divisor < 0) { throw new IllegalArgumentException("divisor must be positive: " + divisor); } if (dividend >= 0) { return dividend % divisor; } else { return (dividend + 1) % divisor - 1 + divisor; } } static long amod(long dividend, long divisor) { long mod = mod(dividend, divisor); return (mod == 0) ? divisor : mod; } /** Milliseconds from 0001-01-01 to the epoch. */ private final long iEpochMillis; public TestGJChronology(int epochYear, int epochMonth, int epochDay) { iEpochMillis = fixedFromGJ(epochYear, epochMonth, epochDay) * MILLIS_PER_DAY; } public DateTimeZone getZone() { return null; } public Chronology withUTC() { return this; } /** * Unsupported. */ public Chronology withZone(DateTimeZone zone) { throw new UnsupportedOperationException(); } long getTimeOnlyMillis(long millis) { return mod(millis, MILLIS_PER_DAY); } long getDateOnlyMillis(long millis) { return millis - mod(millis, MILLIS_PER_DAY); } public DurationField days() { return dayOfWeek().getDurationField(); } public DateTimeField dayOfWeek() { return new TestGJDayOfWeekField(this); } public DateTimeField dayOfMonth() { return new TestGJDayOfMonthField(this); } public DateTimeField dayOfYear() { return new TestGJDayOfYearField(this); } public DurationField weeks() { return weekOfWeekyear().getDurationField(); } public DateTimeField weekOfWeekyear() { return new TestGJWeekOfWeekyearField(this); } public DurationField weekyears() { return weekyear().getDurationField(); } public DateTimeField weekyear() { return new TestGJWeekyearField(this); } public DurationField months() { return monthOfYear().getDurationField(); } public DateTimeField monthOfYear() { return new TestGJMonthOfYearField(this); } public DurationField years() { return year().getDurationField(); } public DateTimeField year() { return new TestGJYearField(this); } abstract long millisPerYear(); abstract long millisPerMonth(); abstract boolean isLeapYear(int year); /** * @return days from 0001-01-01 */ abstract long fixedFromGJ(int year, int monthOfYear, int dayOfMonth); /** * @param date days from 0001-01-01 * @return gj year */ abstract int gjYearFromFixed(long date); /** * @param date days from 0001-01-01 * @return gj year, monthOfYear, dayOfMonth */ abstract int[] gjFromFixed(long date); abstract long fixedFromISO(int weekyear, int weekOfWeekyear, int dayOfWeek); /** * @param date days from 0001-01-01 * @return iso weekyear, weekOfWeekyear, dayOfWeek (1=Monday to 7) */ abstract int[] isoFromFixed(long date); /** * @param millis milliseconds from epoch * @return days from 0001-01-01 */ long fixedFromMillis(long millis) { return div(millis + iEpochMillis, MILLIS_PER_DAY); } /** * @param fixed days from 0001-01-01 * @return milliseconds from epoch */ long millisFromFixed(long fixed) { return fixed * MILLIS_PER_DAY - iEpochMillis; } /** * @return milliseconds from epoch */ long millisFromGJ(int year, int monthOfYear, int dayOfMonth) { return millisFromFixed(fixedFromGJ(year, monthOfYear, dayOfMonth)); } /** * @param millis milliseconds from epoch * @return gj year */ int gjYearFromMillis(long millis) { return gjYearFromFixed(fixedFromMillis(millis)); } /** * @param millis milliseconds from epoch * @return gj year, monthOfYear, dayOfMonth */ int[] gjFromMillis(long millis) { return gjFromFixed(fixedFromMillis(millis)); } /** * @return milliseconds from epoch */ long millisFromISO(int weekyear, int weekOfWeekyear, int dayOfWeek) { return millisFromFixed(fixedFromISO(weekyear, weekOfWeekyear, dayOfWeek)); } /** * @param millis milliseconds from epoch * @return iso weekyear, weekOfWeekyear, dayOfWeek (1=Monday to 7) */ int[] isoFromMillis(long millis) { return isoFromFixed(fixedFromMillis(millis)); } /** * @param date days from 0001-01-01 * @param weekday 0=Sunday, 1=Monday, 2=Tuesday ... 6=Saturday, 7=Sunday * @param date days from 0001-01-01, on or before weekday */ long weekdayOnOrBefore(long date, int weekday) { return date - mod(date - mod(weekday, 7), 7); } long weekdayOnOrAfter(long date, int weekday) { return weekdayOnOrBefore(date + 6, weekday); } long weekdayNearest(long date, int weekday) { return weekdayOnOrBefore(date + 3, weekday); } long weekdayBefore(long date, int weekday) { return weekdayOnOrBefore(date - 1, weekday); } long weekdayAfter(long date, int weekday) { return weekdayOnOrBefore(date + 7, weekday); } long nthWeekday(int n, int weekday, int year, int monthOfYear, int dayOfMonth) { if (n > 0) { return 7 * n + weekdayBefore (fixedFromGJ(year, monthOfYear, dayOfMonth), weekday); } else { return 7 * n + weekdayAfter (fixedFromGJ(year, monthOfYear, dayOfMonth), weekday); } } long firstWeekday(int weekday, int year, int monthOfYear, int dayOfMonth) { return nthWeekday(1, weekday, year, monthOfYear, dayOfMonth); } long lastWeekday(int weekday, int year, int monthOfYear, int dayOfMonth) { return nthWeekday(-1, weekday, year, monthOfYear, dayOfMonth); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestJulianYearField.java0000644000175000017500000000325311564251364026324 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.field.FieldUtils; /** * * @author Brian S O'Neill */ class TestJulianYearField extends TestGJYearField { public TestJulianYearField(TestJulianChronology chrono) { super(chrono); } public long addWrapField(long millis, int value) { int year = get(millis); int wrapped = FieldUtils.getWrappedValue (year, value, getMinimumValue(), getMaximumValue()); return add(millis, (long) wrapped - year); } public long add(long millis, long value) { int year = get(millis); int newYear = year + FieldUtils.safeToInt(value); if (year < 0) { if (newYear >= 0) { newYear++; } } else { if (newYear <= 0) { newYear--; } } return set(millis, newYear); } public int getMinimumValue() { return -100000000; } public int getMaximumValue() { return 100000000; } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJWeekOfWeekyearField.java0000644000175000017500000000423211564251364027355 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * * @author Brian S O'Neill */ class TestGJWeekOfWeekyearField extends TestGJDateTimeField { public TestGJWeekOfWeekyearField(TestGJChronology chrono) { super(DateTimeFieldType.weekOfWeekyear(), (long)(TestGJChronology.MILLIS_PER_DAY * 7), chrono); } public int get(long millis) { return iChronology.isoFromMillis(millis)[1]; } public long set(long millis, int value) { int[] wwd = iChronology.isoFromMillis(millis); return iChronology.getTimeOnlyMillis(millis) + iChronology.millisFromISO(wwd[0], value, wwd[2]); } public long add(long millis, long value) { return iChronology.dayOfYear().add(millis, value * 7); } public DurationField getRangeDurationField() { return iChronology.weeks(); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return 53; } public int getMaximumValue(long millis) { // Move millis to end of weekyear. millis = iChronology.weekyear().roundFloor(millis); millis = iChronology.weekyear().add(millis, 1); millis = iChronology.dayOfYear().add(millis, -1); return get(millis); } public long roundFloor(long millis) { int[] wwd = iChronology.isoFromMillis(millis); return iChronology.millisFromISO(wwd[0], wwd[1], 1); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestJulianDayOfMonthField.java0000644000175000017500000000171211564251364027432 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; /** * * @author Brian S O'Neill */ class TestJulianDayOfMonthField extends TestGJDayOfMonthField { public TestJulianDayOfMonthField(TestJulianChronology chrono) { super(chrono); } public long getRangeMillis() { return iChronology.millisPerMonth(); } } joda-time-2.3/src/test/java/org/joda/time/chrono/gj/TestGJYearField.java0000644000175000017500000000427511564251364025407 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono.gj; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * * @author Brian S O'Neill */ class TestGJYearField extends TestGJDateTimeField { public TestGJYearField(TestGJChronology chrono) { super(DateTimeFieldType.year(), chrono.millisPerYear(), chrono); } public int get(long millis) { return iChronology.gjYearFromMillis(millis); } public long set(long millis, int value) { int[] ymd = iChronology.gjFromMillis(millis); millis = iChronology.getTimeOnlyMillis(millis) + iChronology.millisFromGJ(value, ymd[1], ymd[2]); if (ymd[1] == 2 && ymd[2] == 29 && !iChronology.isLeapYear(value)) { millis = iChronology.dayOfYear().add(millis, -1); } return millis; } public long add(long millis, long value) { return set(millis, (int)(get(millis) + value)); } public boolean isLeap(long millis) { return iChronology.isLeapYear(get(millis)); } public int getLeapAmount(long millis) { return isLeap(millis) ? 1 : 0; } public DurationField getLeapDurationField() { return iChronology.days(); } public DurationField getRangeDurationField() { return null; } public int getMinimumValue() { return -100000000; } public int getMaximumValue() { return 100000000; } public long roundFloor(long millis) { return iChronology.millisFromGJ(get(millis), 1, 1); } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestGJChronology.java0000644000175000017500000006623611667401136025271 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.IllegalFieldValueException; import org.joda.time.Instant; import org.joda.time.Period; import org.joda.time.TimeOfDay; import org.joda.time.YearMonthDay; /** * This class is a Junit unit test for GJChronology. * * @author Stephen Colebourne */ public class TestGJChronology extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestGJChronology.class); } public TestGJChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, GJChronology.getInstanceUTC().getZone()); assertSame(GJChronology.class, GJChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, GJChronology.getInstance().getZone()); assertSame(GJChronology.class, GJChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, GJChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, GJChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, GJChronology.getInstance(null).getZone()); assertSame(GJChronology.class, GJChronology.getInstance(TOKYO).getClass()); } public void testFactory_Zone_long_int() { GJChronology chrono = GJChronology.getInstance(TOKYO, 0L, 2); assertEquals(TOKYO, chrono.getZone()); assertEquals(new Instant(0L), chrono.getGregorianCutover()); assertEquals(2, chrono.getMinimumDaysInFirstWeek()); assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, 0L, 2).getClass()); try { GJChronology.getInstance(TOKYO, 0L, 0); fail(); } catch (IllegalArgumentException ex) {} try { GJChronology.getInstance(TOKYO, 0L, 8); fail(); } catch (IllegalArgumentException ex) {} } public void testFactory_Zone_RI() { GJChronology chrono = GJChronology.getInstance(TOKYO, new Instant(0L)); assertEquals(TOKYO, chrono.getZone()); assertEquals(new Instant(0L), chrono.getGregorianCutover()); assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, new Instant(0L)).getClass()); DateTime cutover = new DateTime(1582, 10, 15, 0, 0, 0, 0, DateTimeZone.UTC); chrono = GJChronology.getInstance(TOKYO, null); assertEquals(TOKYO, chrono.getZone()); assertEquals(cutover.toInstant(), chrono.getGregorianCutover()); } public void testFactory_Zone_RI_int() { GJChronology chrono = GJChronology.getInstance(TOKYO, new Instant(0L), 2); assertEquals(TOKYO, chrono.getZone()); assertEquals(new Instant(0L), chrono.getGregorianCutover()); assertEquals(2, chrono.getMinimumDaysInFirstWeek()); assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, new Instant(0L), 2).getClass()); DateTime cutover = new DateTime(1582, 10, 15, 0, 0, 0, 0, DateTimeZone.UTC); chrono = GJChronology.getInstance(TOKYO, null, 2); assertEquals(TOKYO, chrono.getZone()); assertEquals(cutover.toInstant(), chrono.getGregorianCutover()); assertEquals(2, chrono.getMinimumDaysInFirstWeek()); try { GJChronology.getInstance(TOKYO, new Instant(0L), 0); fail(); } catch (IllegalArgumentException ex) {} try { GJChronology.getInstance(TOKYO, new Instant(0L), 8); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testEquality() { assertSame(GJChronology.getInstance(TOKYO), GJChronology.getInstance(TOKYO)); assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(LONDON)); assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance(PARIS)); assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstanceUTC()); assertSame(GJChronology.getInstance(), GJChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance(LONDON).withUTC()); assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance(TOKYO).withUTC()); assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstanceUTC().withUTC()); assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(GJChronology.getInstance(TOKYO), GJChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(TOKYO).withZone(null)); assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance().withZone(PARIS)); assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("GJChronology[Europe/London]", GJChronology.getInstance(LONDON).toString()); assertEquals("GJChronology[Asia/Tokyo]", GJChronology.getInstance(TOKYO).toString()); assertEquals("GJChronology[Europe/London]", GJChronology.getInstance().toString()); assertEquals("GJChronology[UTC]", GJChronology.getInstanceUTC().toString()); assertEquals("GJChronology[UTC,cutover=1970-01-01]", GJChronology.getInstance(DateTimeZone.UTC, 0L, 4).toString()); assertEquals("GJChronology[UTC,cutover=1970-01-01T00:00:00.001Z,mdfw=2]", GJChronology.getInstance(DateTimeZone.UTC, 1L, 2).toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", GJChronology.getInstance().eras().getName()); assertEquals("centuries", GJChronology.getInstance().centuries().getName()); assertEquals("years", GJChronology.getInstance().years().getName()); assertEquals("weekyears", GJChronology.getInstance().weekyears().getName()); assertEquals("months", GJChronology.getInstance().months().getName()); assertEquals("weeks", GJChronology.getInstance().weeks().getName()); assertEquals("halfdays", GJChronology.getInstance().halfdays().getName()); assertEquals("days", GJChronology.getInstance().days().getName()); assertEquals("hours", GJChronology.getInstance().hours().getName()); assertEquals("minutes", GJChronology.getInstance().minutes().getName()); assertEquals("seconds", GJChronology.getInstance().seconds().getName()); assertEquals("millis", GJChronology.getInstance().millis().getName()); assertEquals(false, GJChronology.getInstance().eras().isSupported()); assertEquals(true, GJChronology.getInstance().centuries().isSupported()); assertEquals(true, GJChronology.getInstance().years().isSupported()); assertEquals(true, GJChronology.getInstance().weekyears().isSupported()); assertEquals(true, GJChronology.getInstance().months().isSupported()); assertEquals(true, GJChronology.getInstance().weeks().isSupported()); assertEquals(true, GJChronology.getInstance().days().isSupported()); assertEquals(true, GJChronology.getInstance().halfdays().isSupported()); assertEquals(true, GJChronology.getInstance().hours().isSupported()); assertEquals(true, GJChronology.getInstance().minutes().isSupported()); assertEquals(true, GJChronology.getInstance().seconds().isSupported()); assertEquals(true, GJChronology.getInstance().millis().isSupported()); assertEquals(false, GJChronology.getInstance().centuries().isPrecise()); assertEquals(false, GJChronology.getInstance().years().isPrecise()); assertEquals(false, GJChronology.getInstance().weekyears().isPrecise()); assertEquals(false, GJChronology.getInstance().months().isPrecise()); assertEquals(false, GJChronology.getInstance().weeks().isPrecise()); assertEquals(false, GJChronology.getInstance().days().isPrecise()); assertEquals(false, GJChronology.getInstance().halfdays().isPrecise()); assertEquals(true, GJChronology.getInstance().hours().isPrecise()); assertEquals(true, GJChronology.getInstance().minutes().isPrecise()); assertEquals(true, GJChronology.getInstance().seconds().isPrecise()); assertEquals(true, GJChronology.getInstance().millis().isPrecise()); assertEquals(false, GJChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, GJChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, GJChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, GJChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, GJChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, GJChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, GJChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, GJChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, GJChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, GJChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, GJChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, GJChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, GJChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, GJChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, GJChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, GJChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, GJChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, GJChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, GJChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, GJChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, GJChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, GJChronology.getInstance(gmt).millis().isPrecise()); } public void testDateFields() { assertEquals("era", GJChronology.getInstance().era().getName()); assertEquals("centuryOfEra", GJChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", GJChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", GJChronology.getInstance().yearOfEra().getName()); assertEquals("year", GJChronology.getInstance().year().getName()); assertEquals("monthOfYear", GJChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", GJChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", GJChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", GJChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", GJChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", GJChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", GJChronology.getInstance().dayOfWeek().getName()); assertEquals(true, GJChronology.getInstance().era().isSupported()); assertEquals(true, GJChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, GJChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, GJChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, GJChronology.getInstance().year().isSupported()); assertEquals(true, GJChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, GJChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, GJChronology.getInstance().weekyear().isSupported()); assertEquals(true, GJChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, GJChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, GJChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, GJChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", GJChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", GJChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", GJChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", GJChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", GJChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", GJChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", GJChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", GJChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", GJChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", GJChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", GJChronology.getInstance().millisOfSecond().getName()); assertEquals(true, GJChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, GJChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, GJChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, GJChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, GJChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, GJChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, GJChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, GJChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, GJChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, GJChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, GJChronology.getInstance().millisOfSecond().isSupported()); } public void testIllegalDates() { try { new DateTime(1582, 10, 5, 0, 0, 0, 0, GJChronology.getInstance(DateTimeZone.UTC)); fail("Constructed illegal date"); } catch (IllegalArgumentException e) { /* good */ } try { new DateTime(1582, 10, 14, 0, 0, 0, 0, GJChronology.getInstance(DateTimeZone.UTC)); fail("Constructed illegal date"); } catch (IllegalArgumentException e) { /* good */ } } public void testParseEquivalence() { testParse("1581-01-01T01:23:45.678", 1581, 1, 1, 1, 23, 45, 678); testParse("1581-06-30", 1581, 6, 30, 0, 0, 0, 0); testParse("1582-01-01T01:23:45.678", 1582, 1, 1, 1, 23, 45, 678); testParse("1582-06-30T01:23:45.678", 1582, 6, 30, 1, 23, 45, 678); testParse("1582-10-04", 1582, 10, 4, 0, 0, 0, 0); testParse("1582-10-15", 1582, 10, 15, 0, 0, 0, 0); testParse("1582-12-31", 1582, 12, 31, 0, 0, 0, 0); testParse("1583-12-31", 1583, 12, 31, 0, 0, 0, 0); } private void testParse(String str, int year, int month, int day, int hour, int minute, int second, int millis) { assertEquals(new DateTime(str, GJChronology.getInstance(DateTimeZone.UTC)), new DateTime(year, month, day, hour, minute, second, millis, GJChronology.getInstance(DateTimeZone.UTC))); } public void testCutoverAddYears() { testAdd("1582-01-01", DurationFieldType.years(), 1, "1583-01-01"); testAdd("1582-02-15", DurationFieldType.years(), 1, "1583-02-15"); testAdd("1582-02-28", DurationFieldType.years(), 1, "1583-02-28"); testAdd("1582-03-01", DurationFieldType.years(), 1, "1583-03-01"); testAdd("1582-09-30", DurationFieldType.years(), 1, "1583-09-30"); testAdd("1582-10-01", DurationFieldType.years(), 1, "1583-10-01"); testAdd("1582-10-04", DurationFieldType.years(), 1, "1583-10-04"); testAdd("1582-10-15", DurationFieldType.years(), 1, "1583-10-15"); testAdd("1582-10-16", DurationFieldType.years(), 1, "1583-10-16"); // Leap years... testAdd("1580-01-01", DurationFieldType.years(), 4, "1584-01-01"); testAdd("1580-02-29", DurationFieldType.years(), 4, "1584-02-29"); testAdd("1580-10-01", DurationFieldType.years(), 4, "1584-10-01"); testAdd("1580-10-10", DurationFieldType.years(), 4, "1584-10-10"); testAdd("1580-10-15", DurationFieldType.years(), 4, "1584-10-15"); testAdd("1580-12-31", DurationFieldType.years(), 4, "1584-12-31"); } public void testCutoverAddWeekyears() { testAdd("1582-W01-1", DurationFieldType.weekyears(), 1, "1583-W01-1"); testAdd("1582-W39-1", DurationFieldType.weekyears(), 1, "1583-W39-1"); testAdd("1583-W45-1", DurationFieldType.weekyears(), 1, "1584-W45-1"); // This test fails, but I'm not sure if its worth fixing. The date // falls after the cutover, but in the cutover year. The add operation // is performed completely within the gregorian calendar, with no // crossing of the cutover. As a result, no special correction is // applied. Since the full gregorian year of 1582 has a different week // numbers than the full julian year of 1582, the week number is off by // one after the addition. // //testAdd("1582-W42-1", DurationFieldType.weekyears(), 1, "1583-W42-1"); // Leap years... testAdd("1580-W01-1", DurationFieldType.weekyears(), 4, "1584-W01-1"); testAdd("1580-W30-7", DurationFieldType.weekyears(), 4, "1584-W30-7"); testAdd("1580-W50-7", DurationFieldType.weekyears(), 4, "1584-W50-7"); } public void testCutoverAddMonths() { testAdd("1582-01-01", DurationFieldType.months(), 1, "1582-02-01"); testAdd("1582-01-01", DurationFieldType.months(), 6, "1582-07-01"); testAdd("1582-01-01", DurationFieldType.months(), 12, "1583-01-01"); testAdd("1582-11-15", DurationFieldType.months(), 1, "1582-12-15"); testAdd("1582-09-04", DurationFieldType.months(), 2, "1582-11-04"); testAdd("1582-09-05", DurationFieldType.months(), 2, "1582-11-05"); testAdd("1582-09-10", DurationFieldType.months(), 2, "1582-11-10"); testAdd("1582-09-15", DurationFieldType.months(), 2, "1582-11-15"); // Leap years... testAdd("1580-01-01", DurationFieldType.months(), 48, "1584-01-01"); testAdd("1580-02-29", DurationFieldType.months(), 48, "1584-02-29"); testAdd("1580-10-01", DurationFieldType.months(), 48, "1584-10-01"); testAdd("1580-10-10", DurationFieldType.months(), 48, "1584-10-10"); testAdd("1580-10-15", DurationFieldType.months(), 48, "1584-10-15"); testAdd("1580-12-31", DurationFieldType.months(), 48, "1584-12-31"); } public void testCutoverAddWeeks() { testAdd("1582-01-01", DurationFieldType.weeks(), 1, "1582-01-08"); testAdd("1583-01-01", DurationFieldType.weeks(), 1, "1583-01-08"); // Weeks are precise, and so cutover is not ignored. testAdd("1582-10-01", DurationFieldType.weeks(), 2, "1582-10-25"); testAdd("1582-W01-1", DurationFieldType.weeks(), 51, "1583-W01-1"); } public void testCutoverAddDays() { testAdd("1582-10-03", DurationFieldType.days(), 1, "1582-10-04"); testAdd("1582-10-04", DurationFieldType.days(), 1, "1582-10-15"); testAdd("1582-10-15", DurationFieldType.days(), 1, "1582-10-16"); testAdd("1582-09-30", DurationFieldType.days(), 10, "1582-10-20"); testAdd("1582-10-04", DurationFieldType.days(), 10, "1582-10-24"); testAdd("1582-10-15", DurationFieldType.days(), 10, "1582-10-25"); } public void testYearEndAddDays() { testAdd("1582-11-05", DurationFieldType.days(), 28, "1582-12-03"); testAdd("1582-12-05", DurationFieldType.days(), 28, "1583-01-02"); testAdd("2005-11-05", DurationFieldType.days(), 28, "2005-12-03"); testAdd("2005-12-05", DurationFieldType.days(), 28, "2006-01-02"); } public void testSubtractDays() { // This is a test for a bug in version 1.0. The dayOfMonth range // duration field did not match the monthOfYear duration field. This // caused an exception to be thrown when subtracting days. DateTime dt = new DateTime (1112306400000L, GJChronology.getInstance(DateTimeZone.forID("Europe/Berlin"))); YearMonthDay ymd = dt.toYearMonthDay(); while (ymd.toDateTimeAtMidnight().getDayOfWeek() != DateTimeConstants.MONDAY) { ymd = ymd.minus(Period.days(1)); } } private void testAdd(String start, DurationFieldType type, int amt, String end) { DateTime dtStart = new DateTime(start, GJChronology.getInstance(DateTimeZone.UTC)); DateTime dtEnd = new DateTime(end, GJChronology.getInstance(DateTimeZone.UTC)); assertEquals(dtEnd, dtStart.withFieldAdded(type, amt)); assertEquals(dtStart, dtEnd.withFieldAdded(type, -amt)); DurationField field = type.getField(GJChronology.getInstance(DateTimeZone.UTC)); int diff = field.getDifference(dtEnd.getMillis(), dtStart.getMillis()); assertEquals(amt, diff); if (type == DurationFieldType.years() || type == DurationFieldType.months() || type == DurationFieldType.days()) { YearMonthDay ymdStart = new YearMonthDay(start, GJChronology.getInstance(DateTimeZone.UTC)); YearMonthDay ymdEnd = new YearMonthDay(end, GJChronology.getInstance(DateTimeZone.UTC)); assertEquals(ymdEnd, ymdStart.withFieldAdded(type, amt)); assertEquals(ymdStart, ymdEnd.withFieldAdded(type, -amt)); } } public void testTimeOfDayAdd() { TimeOfDay start = new TimeOfDay(12, 30, GJChronology.getInstance()); TimeOfDay end = new TimeOfDay(10, 30, GJChronology.getInstance()); assertEquals(end, start.plusHours(22)); assertEquals(start, end.minusHours(22)); assertEquals(end, start.plusMinutes(22 * 60)); assertEquals(start, end.minusMinutes(22 * 60)); } public void testMaximumValue() { DateMidnight dt = new DateMidnight(1570, 1, 1, GJChronology.getInstance()); while (dt.getYear() < 1590) { dt = dt.plusDays(1); YearMonthDay ymd = dt.toYearMonthDay(); assertEquals(dt.year().getMaximumValue(), ymd.year().getMaximumValue()); assertEquals(dt.monthOfYear().getMaximumValue(), ymd.monthOfYear().getMaximumValue()); assertEquals(dt.dayOfMonth().getMaximumValue(), ymd.dayOfMonth().getMaximumValue()); } } public void testPartialGetAsText() { GJChronology chrono = GJChronology.getInstance(TOKYO); assertEquals("January", new YearMonthDay("2005-01-01", chrono).monthOfYear().getAsText()); assertEquals("Jan", new YearMonthDay("2005-01-01", chrono).monthOfYear().getAsShortText()); } public void testLeapYearRulesConstruction() { // 1500 not leap in Gregorian, but is leap in Julian DateMidnight dt = new DateMidnight(1500, 2, 29, GJChronology.getInstanceUTC()); assertEquals(dt.getYear(), 1500); assertEquals(dt.getMonthOfYear(), 2); assertEquals(dt.getDayOfMonth(), 29); } public void testLeapYearRulesConstructionInvalid() { // 1500 not leap in Gregorian, but is leap in Julian try { new DateMidnight(1500, 2, 30, GJChronology.getInstanceUTC()); fail(); } catch (IllegalFieldValueException ex) { // good } } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestEthiopicChronology.java0000644000175000017500000007466611564251364026545 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.DateTime.Property; /** * This class is a Junit unit test for EthiopicChronology. * * @author Stephen Colebourne */ public class TestEthiopicChronology extends TestCase { private static final int MILLIS_PER_DAY = DateTimeConstants.MILLIS_PER_DAY; private static long SKIP = 1 * MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology ETHIOPIC_UTC = EthiopicChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { SKIP = 1 * MILLIS_PER_DAY; return new TestSuite(TestEthiopicChronology.class); } public TestEthiopicChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, EthiopicChronology.getInstanceUTC().getZone()); assertSame(EthiopicChronology.class, EthiopicChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, EthiopicChronology.getInstance().getZone()); assertSame(EthiopicChronology.class, EthiopicChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, EthiopicChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, EthiopicChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, EthiopicChronology.getInstance(null).getZone()); assertSame(EthiopicChronology.class, EthiopicChronology.getInstance(TOKYO).getClass()); } //----------------------------------------------------------------------- public void testEquality() { assertSame(EthiopicChronology.getInstance(TOKYO), EthiopicChronology.getInstance(TOKYO)); assertSame(EthiopicChronology.getInstance(LONDON), EthiopicChronology.getInstance(LONDON)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstance(PARIS)); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstanceUTC()); assertSame(EthiopicChronology.getInstance(), EthiopicChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstance(LONDON).withUTC()); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstance(TOKYO).withUTC()); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstanceUTC().withUTC()); assertSame(EthiopicChronology.getInstanceUTC(), EthiopicChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(EthiopicChronology.getInstance(TOKYO), EthiopicChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(EthiopicChronology.getInstance(LONDON), EthiopicChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(EthiopicChronology.getInstance(LONDON), EthiopicChronology.getInstance(TOKYO).withZone(null)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstance().withZone(PARIS)); assertSame(EthiopicChronology.getInstance(PARIS), EthiopicChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("EthiopicChronology[Europe/London]", EthiopicChronology.getInstance(LONDON).toString()); assertEquals("EthiopicChronology[Asia/Tokyo]", EthiopicChronology.getInstance(TOKYO).toString()); assertEquals("EthiopicChronology[Europe/London]", EthiopicChronology.getInstance().toString()); assertEquals("EthiopicChronology[UTC]", EthiopicChronology.getInstanceUTC().toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", EthiopicChronology.getInstance().eras().getName()); assertEquals("centuries", EthiopicChronology.getInstance().centuries().getName()); assertEquals("years", EthiopicChronology.getInstance().years().getName()); assertEquals("weekyears", EthiopicChronology.getInstance().weekyears().getName()); assertEquals("months", EthiopicChronology.getInstance().months().getName()); assertEquals("weeks", EthiopicChronology.getInstance().weeks().getName()); assertEquals("days", EthiopicChronology.getInstance().days().getName()); assertEquals("halfdays", EthiopicChronology.getInstance().halfdays().getName()); assertEquals("hours", EthiopicChronology.getInstance().hours().getName()); assertEquals("minutes", EthiopicChronology.getInstance().minutes().getName()); assertEquals("seconds", EthiopicChronology.getInstance().seconds().getName()); assertEquals("millis", EthiopicChronology.getInstance().millis().getName()); assertEquals(false, EthiopicChronology.getInstance().eras().isSupported()); assertEquals(true, EthiopicChronology.getInstance().centuries().isSupported()); assertEquals(true, EthiopicChronology.getInstance().years().isSupported()); assertEquals(true, EthiopicChronology.getInstance().weekyears().isSupported()); assertEquals(true, EthiopicChronology.getInstance().months().isSupported()); assertEquals(true, EthiopicChronology.getInstance().weeks().isSupported()); assertEquals(true, EthiopicChronology.getInstance().days().isSupported()); assertEquals(true, EthiopicChronology.getInstance().halfdays().isSupported()); assertEquals(true, EthiopicChronology.getInstance().hours().isSupported()); assertEquals(true, EthiopicChronology.getInstance().minutes().isSupported()); assertEquals(true, EthiopicChronology.getInstance().seconds().isSupported()); assertEquals(true, EthiopicChronology.getInstance().millis().isSupported()); assertEquals(false, EthiopicChronology.getInstance().centuries().isPrecise()); assertEquals(false, EthiopicChronology.getInstance().years().isPrecise()); assertEquals(false, EthiopicChronology.getInstance().weekyears().isPrecise()); assertEquals(false, EthiopicChronology.getInstance().months().isPrecise()); assertEquals(false, EthiopicChronology.getInstance().weeks().isPrecise()); assertEquals(false, EthiopicChronology.getInstance().days().isPrecise()); assertEquals(false, EthiopicChronology.getInstance().halfdays().isPrecise()); assertEquals(true, EthiopicChronology.getInstance().hours().isPrecise()); assertEquals(true, EthiopicChronology.getInstance().minutes().isPrecise()); assertEquals(true, EthiopicChronology.getInstance().seconds().isPrecise()); assertEquals(true, EthiopicChronology.getInstance().millis().isPrecise()); assertEquals(false, EthiopicChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, EthiopicChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, EthiopicChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, EthiopicChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, EthiopicChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, EthiopicChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, EthiopicChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, EthiopicChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, EthiopicChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, EthiopicChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, EthiopicChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, EthiopicChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, EthiopicChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, EthiopicChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, EthiopicChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, EthiopicChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, EthiopicChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, EthiopicChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, EthiopicChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, EthiopicChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, EthiopicChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, EthiopicChronology.getInstance(gmt).millis().isPrecise()); } public void testDateFields() { assertEquals("era", EthiopicChronology.getInstance().era().getName()); assertEquals("centuryOfEra", EthiopicChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", EthiopicChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", EthiopicChronology.getInstance().yearOfEra().getName()); assertEquals("year", EthiopicChronology.getInstance().year().getName()); assertEquals("monthOfYear", EthiopicChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", EthiopicChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", EthiopicChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", EthiopicChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", EthiopicChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", EthiopicChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", EthiopicChronology.getInstance().dayOfWeek().getName()); assertEquals(true, EthiopicChronology.getInstance().era().isSupported()); assertEquals(true, EthiopicChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, EthiopicChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, EthiopicChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, EthiopicChronology.getInstance().year().isSupported()); assertEquals(true, EthiopicChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, EthiopicChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, EthiopicChronology.getInstance().weekyear().isSupported()); assertEquals(true, EthiopicChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, EthiopicChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, EthiopicChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, EthiopicChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", EthiopicChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", EthiopicChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", EthiopicChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", EthiopicChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", EthiopicChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", EthiopicChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", EthiopicChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", EthiopicChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", EthiopicChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", EthiopicChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", EthiopicChronology.getInstance().millisOfSecond().getName()); assertEquals(true, EthiopicChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, EthiopicChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, EthiopicChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, EthiopicChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, EthiopicChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, EthiopicChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, EthiopicChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, EthiopicChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, EthiopicChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, EthiopicChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, EthiopicChronology.getInstance().millisOfSecond().isSupported()); } //----------------------------------------------------------------------- public void testEpoch() { DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, ETHIOPIC_UTC); assertEquals(new DateTime(8, 8, 29, 0, 0, 0, 0, JULIAN_UTC), epoch.withChronology(JULIAN_UTC)); } public void testEra() { assertEquals(1, EthiopicChronology.EE); try { new DateTime(-1, 13, 5, 0, 0, 0, 0, ETHIOPIC_UTC); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */ public void testCalendar() { if (TestAll.FAST) { return; } System.out.println("\nTestEthiopicChronology.testCalendar"); DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, ETHIOPIC_UTC); long millis = epoch.getMillis(); long end = new DateTime(3000, 1, 1, 0, 0, 0, 0, ISO_UTC).getMillis(); DateTimeField dayOfWeek = ETHIOPIC_UTC.dayOfWeek(); DateTimeField dayOfYear = ETHIOPIC_UTC.dayOfYear(); DateTimeField dayOfMonth = ETHIOPIC_UTC.dayOfMonth(); DateTimeField monthOfYear = ETHIOPIC_UTC.monthOfYear(); DateTimeField year = ETHIOPIC_UTC.year(); DateTimeField yearOfEra = ETHIOPIC_UTC.yearOfEra(); DateTimeField era = ETHIOPIC_UTC.era(); int expectedDOW = new DateTime(8, 8, 29, 0, 0, 0, 0, JULIAN_UTC).getDayOfWeek(); int expectedDOY = 1; int expectedDay = 1; int expectedMonth = 1; int expectedYear = 1; while (millis < end) { int dowValue = dayOfWeek.get(millis); int doyValue = dayOfYear.get(millis); int dayValue = dayOfMonth.get(millis); int monthValue = monthOfYear.get(millis); int yearValue = year.get(millis); int yearOfEraValue = yearOfEra.get(millis); int monthLen = dayOfMonth.getMaximumValue(millis); if (monthValue < 1 || monthValue > 13) { fail("Bad month: " + millis); } // test era assertEquals(1, era.get(millis)); assertEquals("EE", era.getAsText(millis)); assertEquals("EE", era.getAsShortText(millis)); // test date assertEquals(expectedYear, yearValue); assertEquals(expectedYear, yearOfEraValue); assertEquals(expectedMonth, monthValue); assertEquals(expectedDay, dayValue); assertEquals(expectedDOW, dowValue); assertEquals(expectedDOY, doyValue); // test leap year assertEquals(yearValue % 4 == 3, year.isLeap(millis)); // test month length if (monthValue == 13) { assertEquals(yearValue % 4 == 3, monthOfYear.isLeap(millis)); if (yearValue % 4 == 3) { assertEquals(6, monthLen); } else { assertEquals(5, monthLen); } } else { assertEquals(30, monthLen); } // recalculate date expectedDOW = (((expectedDOW + 1) - 1) % 7) + 1; expectedDay++; expectedDOY++; if (expectedDay == 31 && expectedMonth < 13) { expectedDay = 1; expectedMonth++; } else if (expectedMonth == 13) { if (expectedYear % 4 == 3 && expectedDay == 7) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } else if (expectedYear % 4 != 3 && expectedDay == 6) { expectedDay = 1; expectedMonth = 1; expectedYear++; expectedDOY = 1; } } millis += SKIP; } } public void testSampleDate() { DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, ISO_UTC).withChronology(ETHIOPIC_UTC); assertEquals(EthiopicChronology.EE, dt.getEra()); assertEquals(20, dt.getCenturyOfEra()); // TODO confirm assertEquals(96, dt.getYearOfCentury()); assertEquals(1996, dt.getYearOfEra()); assertEquals(1996, dt.getYear()); Property fld = dt.year(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(new DateTime(1997, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(10, dt.getMonthOfYear()); fld = dt.monthOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(13, fld.getMaximumValue()); assertEquals(13, fld.getMaximumValueOverall()); assertEquals(new DateTime(1997, 1, 2, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(4)); assertEquals(new DateTime(1996, 1, 2, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addWrapFieldToCopy(4)); assertEquals(2, dt.getDayOfMonth()); fld = dt.dayOfMonth(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(30, fld.getMaximumValue()); assertEquals(30, fld.getMaximumValueOverall()); assertEquals(new DateTime(1996, 10, 3, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(DateTimeConstants.WEDNESDAY, dt.getDayOfWeek()); fld = dt.dayOfWeek(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(7, fld.getMaximumValue()); assertEquals(7, fld.getMaximumValueOverall()); assertEquals(new DateTime(1996, 10, 3, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(9 * 30 + 2, dt.getDayOfYear()); fld = dt.dayOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(365, fld.getMaximumValue()); assertEquals(366, fld.getMaximumValueOverall()); assertEquals(new DateTime(1996, 10, 3, 0, 0, 0, 0, ETHIOPIC_UTC), fld.addToCopy(1)); assertEquals(0, dt.getHourOfDay()); assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testSampleDateWithZone() { DateTime dt = new DateTime(2004, 6, 9, 12, 0, 0, 0, PARIS).withChronology(ETHIOPIC_UTC); assertEquals(EthiopicChronology.EE, dt.getEra()); assertEquals(1996, dt.getYear()); assertEquals(1996, dt.getYearOfEra()); assertEquals(10, dt.getMonthOfYear()); assertEquals(2, dt.getDayOfMonth()); assertEquals(10, dt.getHourOfDay()); // PARIS is UTC+2 in summer (12-2=10) assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testDurationYear() { // Leap 1999, NotLeap 1996,97,98 DateTime dt96 = new DateTime(1996, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt97 = new DateTime(1997, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt98 = new DateTime(1998, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt99 = new DateTime(1999, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt00 = new DateTime(2000, 10, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DurationField fld = dt96.year().getDurationField(); assertEquals(ETHIOPIC_UTC.years(), fld); assertEquals(1L * 365L * MILLIS_PER_DAY, fld.getMillis(1, dt96.getMillis())); assertEquals(2L * 365L * MILLIS_PER_DAY, fld.getMillis(2, dt96.getMillis())); assertEquals(3L * 365L * MILLIS_PER_DAY, fld.getMillis(3, dt96.getMillis())); assertEquals((4L * 365L + 1L) * MILLIS_PER_DAY, fld.getMillis(4, dt96.getMillis())); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getMillis(1)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 2, fld.getMillis(2)); assertEquals(1L * 365L * MILLIS_PER_DAY, fld.getMillis(1L, dt96.getMillis())); assertEquals(2L * 365L * MILLIS_PER_DAY, fld.getMillis(2L, dt96.getMillis())); assertEquals(3L * 365L * MILLIS_PER_DAY, fld.getMillis(3L, dt96.getMillis())); assertEquals((4L * 365L + 1L) * MILLIS_PER_DAY, fld.getMillis(4L, dt96.getMillis())); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getMillis(1L)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 2, fld.getMillis(2L)); assertEquals(((4L * 365L + 1L) * MILLIS_PER_DAY) / 4, fld.getUnitMillis()); assertEquals(0, fld.getValue(1L * 365L * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(1, fld.getValue(1L * 365L * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(1, fld.getValue(1L * 365L * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(1, fld.getValue(2L * 365L * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(2, fld.getValue(2L * 365L * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(2, fld.getValue(2L * 365L * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(2, fld.getValue(3L * 365L * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(3, fld.getValue(3L * 365L * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(3, fld.getValue(3L * 365L * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(3, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY - 1L, dt96.getMillis())); assertEquals(4, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY, dt96.getMillis())); assertEquals(4, fld.getValue((4L * 365L + 1L) * MILLIS_PER_DAY + 1L, dt96.getMillis())); assertEquals(dt97.getMillis(), fld.add(dt96.getMillis(), 1)); assertEquals(dt98.getMillis(), fld.add(dt96.getMillis(), 2)); assertEquals(dt99.getMillis(), fld.add(dt96.getMillis(), 3)); assertEquals(dt00.getMillis(), fld.add(dt96.getMillis(), 4)); assertEquals(dt97.getMillis(), fld.add(dt96.getMillis(), 1L)); assertEquals(dt98.getMillis(), fld.add(dt96.getMillis(), 2L)); assertEquals(dt99.getMillis(), fld.add(dt96.getMillis(), 3L)); assertEquals(dt00.getMillis(), fld.add(dt96.getMillis(), 4L)); } public void testDurationMonth() { // Leap 1999, NotLeap 1996,97,98 DateTime dt11 = new DateTime(1999, 11, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt12 = new DateTime(1999, 12, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt13 = new DateTime(1999, 13, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DateTime dt01 = new DateTime(2000, 1, 2, 0, 0, 0, 0, ETHIOPIC_UTC); DurationField fld = dt11.monthOfYear().getDurationField(); assertEquals(ETHIOPIC_UTC.months(), fld); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1, dt11.getMillis())); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2, dt11.getMillis())); assertEquals((2L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(3, dt11.getMillis())); assertEquals((3L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(4, dt11.getMillis())); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1)); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2)); assertEquals(13L * 30L * MILLIS_PER_DAY, fld.getMillis(13)); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1L, dt11.getMillis())); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2L, dt11.getMillis())); assertEquals((2L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(3L, dt11.getMillis())); assertEquals((3L * 30L + 6L) * MILLIS_PER_DAY, fld.getMillis(4L, dt11.getMillis())); assertEquals(1L * 30L * MILLIS_PER_DAY, fld.getMillis(1L)); assertEquals(2L * 30L * MILLIS_PER_DAY, fld.getMillis(2L)); assertEquals(13L * 30L * MILLIS_PER_DAY, fld.getMillis(13L)); assertEquals(0, fld.getValue(1L * 30L * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(1, fld.getValue(1L * 30L * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(1, fld.getValue(1L * 30L * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(1, fld.getValue(2L * 30L * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(2, fld.getValue(2L * 30L * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(2, fld.getValue(2L * 30L * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(2, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(3, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(3, fld.getValue((2L * 30L + 6L) * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(3, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY - 1L, dt11.getMillis())); assertEquals(4, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY, dt11.getMillis())); assertEquals(4, fld.getValue((3L * 30L + 6L) * MILLIS_PER_DAY + 1L, dt11.getMillis())); assertEquals(dt12.getMillis(), fld.add(dt11.getMillis(), 1)); assertEquals(dt13.getMillis(), fld.add(dt11.getMillis(), 2)); assertEquals(dt01.getMillis(), fld.add(dt11.getMillis(), 3)); assertEquals(dt12.getMillis(), fld.add(dt11.getMillis(), 1L)); assertEquals(dt13.getMillis(), fld.add(dt11.getMillis(), 2L)); assertEquals(dt01.getMillis(), fld.add(dt11.getMillis(), 3L)); } } joda-time-2.3/src/test/java/org/joda/time/chrono/TestIslamicChronology.java0000644000175000017500000011632311564251364026345 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationFieldType; import org.joda.time.DateTime.Property; /** * This class is a Junit unit test for IslamicChronology. * * @author Stephen Colebourne */ public class TestIslamicChronology extends TestCase { private static long SKIP = 1 * DateTimeConstants.MILLIS_PER_DAY; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology ISLAMIC_UTC = IslamicChronology.getInstanceUTC(); private static final Chronology JULIAN_UTC = JulianChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { SKIP = 1 * DateTimeConstants.MILLIS_PER_DAY; return new TestSuite(TestIslamicChronology.class); } public TestIslamicChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testFactoryUTC() { assertEquals(DateTimeZone.UTC, IslamicChronology.getInstanceUTC().getZone()); assertSame(IslamicChronology.class, IslamicChronology.getInstanceUTC().getClass()); } public void testFactory() { assertEquals(LONDON, IslamicChronology.getInstance().getZone()); assertSame(IslamicChronology.class, IslamicChronology.getInstance().getClass()); } public void testFactory_Zone() { assertEquals(TOKYO, IslamicChronology.getInstance(TOKYO).getZone()); assertEquals(PARIS, IslamicChronology.getInstance(PARIS).getZone()); assertEquals(LONDON, IslamicChronology.getInstance(null).getZone()); assertSame(IslamicChronology.class, IslamicChronology.getInstance(TOKYO).getClass()); } //----------------------------------------------------------------------- public void testEquality() { assertSame(IslamicChronology.getInstance(TOKYO), IslamicChronology.getInstance(TOKYO)); assertSame(IslamicChronology.getInstance(LONDON), IslamicChronology.getInstance(LONDON)); assertSame(IslamicChronology.getInstance(PARIS), IslamicChronology.getInstance(PARIS)); assertSame(IslamicChronology.getInstanceUTC(), IslamicChronology.getInstanceUTC()); assertSame(IslamicChronology.getInstance(), IslamicChronology.getInstance(LONDON)); } public void testWithUTC() { assertSame(IslamicChronology.getInstanceUTC(), IslamicChronology.getInstance(LONDON).withUTC()); assertSame(IslamicChronology.getInstanceUTC(), IslamicChronology.getInstance(TOKYO).withUTC()); assertSame(IslamicChronology.getInstanceUTC(), IslamicChronology.getInstanceUTC().withUTC()); assertSame(IslamicChronology.getInstanceUTC(), IslamicChronology.getInstance().withUTC()); } public void testWithZone() { assertSame(IslamicChronology.getInstance(TOKYO), IslamicChronology.getInstance(TOKYO).withZone(TOKYO)); assertSame(IslamicChronology.getInstance(LONDON), IslamicChronology.getInstance(TOKYO).withZone(LONDON)); assertSame(IslamicChronology.getInstance(PARIS), IslamicChronology.getInstance(TOKYO).withZone(PARIS)); assertSame(IslamicChronology.getInstance(LONDON), IslamicChronology.getInstance(TOKYO).withZone(null)); assertSame(IslamicChronology.getInstance(PARIS), IslamicChronology.getInstance().withZone(PARIS)); assertSame(IslamicChronology.getInstance(PARIS), IslamicChronology.getInstanceUTC().withZone(PARIS)); } public void testToString() { assertEquals("IslamicChronology[Europe/London]", IslamicChronology.getInstance(LONDON).toString()); assertEquals("IslamicChronology[Asia/Tokyo]", IslamicChronology.getInstance(TOKYO).toString()); assertEquals("IslamicChronology[Europe/London]", IslamicChronology.getInstance().toString()); assertEquals("IslamicChronology[UTC]", IslamicChronology.getInstanceUTC().toString()); } //----------------------------------------------------------------------- public void testDurationFields() { assertEquals("eras", IslamicChronology.getInstance().eras().getName()); assertEquals("centuries", IslamicChronology.getInstance().centuries().getName()); assertEquals("years", IslamicChronology.getInstance().years().getName()); assertEquals("weekyears", IslamicChronology.getInstance().weekyears().getName()); assertEquals("months", IslamicChronology.getInstance().months().getName()); assertEquals("weeks", IslamicChronology.getInstance().weeks().getName()); assertEquals("days", IslamicChronology.getInstance().days().getName()); assertEquals("halfdays", IslamicChronology.getInstance().halfdays().getName()); assertEquals("hours", IslamicChronology.getInstance().hours().getName()); assertEquals("minutes", IslamicChronology.getInstance().minutes().getName()); assertEquals("seconds", IslamicChronology.getInstance().seconds().getName()); assertEquals("millis", IslamicChronology.getInstance().millis().getName()); assertEquals(false, IslamicChronology.getInstance().eras().isSupported()); assertEquals(true, IslamicChronology.getInstance().centuries().isSupported()); assertEquals(true, IslamicChronology.getInstance().years().isSupported()); assertEquals(true, IslamicChronology.getInstance().weekyears().isSupported()); assertEquals(true, IslamicChronology.getInstance().months().isSupported()); assertEquals(true, IslamicChronology.getInstance().weeks().isSupported()); assertEquals(true, IslamicChronology.getInstance().days().isSupported()); assertEquals(true, IslamicChronology.getInstance().halfdays().isSupported()); assertEquals(true, IslamicChronology.getInstance().hours().isSupported()); assertEquals(true, IslamicChronology.getInstance().minutes().isSupported()); assertEquals(true, IslamicChronology.getInstance().seconds().isSupported()); assertEquals(true, IslamicChronology.getInstance().millis().isSupported()); assertEquals(false, IslamicChronology.getInstance().centuries().isPrecise()); assertEquals(false, IslamicChronology.getInstance().years().isPrecise()); assertEquals(false, IslamicChronology.getInstance().weekyears().isPrecise()); assertEquals(false, IslamicChronology.getInstance().months().isPrecise()); assertEquals(false, IslamicChronology.getInstance().weeks().isPrecise()); assertEquals(false, IslamicChronology.getInstance().days().isPrecise()); assertEquals(false, IslamicChronology.getInstance().halfdays().isPrecise()); assertEquals(true, IslamicChronology.getInstance().hours().isPrecise()); assertEquals(true, IslamicChronology.getInstance().minutes().isPrecise()); assertEquals(true, IslamicChronology.getInstance().seconds().isPrecise()); assertEquals(true, IslamicChronology.getInstance().millis().isPrecise()); assertEquals(false, IslamicChronology.getInstanceUTC().centuries().isPrecise()); assertEquals(false, IslamicChronology.getInstanceUTC().years().isPrecise()); assertEquals(false, IslamicChronology.getInstanceUTC().weekyears().isPrecise()); assertEquals(false, IslamicChronology.getInstanceUTC().months().isPrecise()); assertEquals(true, IslamicChronology.getInstanceUTC().weeks().isPrecise()); assertEquals(true, IslamicChronology.getInstanceUTC().days().isPrecise()); assertEquals(true, IslamicChronology.getInstanceUTC().halfdays().isPrecise()); assertEquals(true, IslamicChronology.getInstanceUTC().hours().isPrecise()); assertEquals(true, IslamicChronology.getInstanceUTC().minutes().isPrecise()); assertEquals(true, IslamicChronology.getInstanceUTC().seconds().isPrecise()); assertEquals(true, IslamicChronology.getInstanceUTC().millis().isPrecise()); DateTimeZone gmt = DateTimeZone.forID("Etc/GMT"); assertEquals(false, IslamicChronology.getInstance(gmt).centuries().isPrecise()); assertEquals(false, IslamicChronology.getInstance(gmt).years().isPrecise()); assertEquals(false, IslamicChronology.getInstance(gmt).weekyears().isPrecise()); assertEquals(false, IslamicChronology.getInstance(gmt).months().isPrecise()); assertEquals(true, IslamicChronology.getInstance(gmt).weeks().isPrecise()); assertEquals(true, IslamicChronology.getInstance(gmt).days().isPrecise()); assertEquals(true, IslamicChronology.getInstance(gmt).halfdays().isPrecise()); assertEquals(true, IslamicChronology.getInstance(gmt).hours().isPrecise()); assertEquals(true, IslamicChronology.getInstance(gmt).minutes().isPrecise()); assertEquals(true, IslamicChronology.getInstance(gmt).seconds().isPrecise()); assertEquals(true, IslamicChronology.getInstance(gmt).millis().isPrecise()); } public void testDateFields() { assertEquals("era", IslamicChronology.getInstance().era().getName()); assertEquals("centuryOfEra", IslamicChronology.getInstance().centuryOfEra().getName()); assertEquals("yearOfCentury", IslamicChronology.getInstance().yearOfCentury().getName()); assertEquals("yearOfEra", IslamicChronology.getInstance().yearOfEra().getName()); assertEquals("year", IslamicChronology.getInstance().year().getName()); assertEquals("monthOfYear", IslamicChronology.getInstance().monthOfYear().getName()); assertEquals("weekyearOfCentury", IslamicChronology.getInstance().weekyearOfCentury().getName()); assertEquals("weekyear", IslamicChronology.getInstance().weekyear().getName()); assertEquals("weekOfWeekyear", IslamicChronology.getInstance().weekOfWeekyear().getName()); assertEquals("dayOfYear", IslamicChronology.getInstance().dayOfYear().getName()); assertEquals("dayOfMonth", IslamicChronology.getInstance().dayOfMonth().getName()); assertEquals("dayOfWeek", IslamicChronology.getInstance().dayOfWeek().getName()); assertEquals(true, IslamicChronology.getInstance().era().isSupported()); assertEquals(true, IslamicChronology.getInstance().centuryOfEra().isSupported()); assertEquals(true, IslamicChronology.getInstance().yearOfCentury().isSupported()); assertEquals(true, IslamicChronology.getInstance().yearOfEra().isSupported()); assertEquals(true, IslamicChronology.getInstance().year().isSupported()); assertEquals(true, IslamicChronology.getInstance().monthOfYear().isSupported()); assertEquals(true, IslamicChronology.getInstance().weekyearOfCentury().isSupported()); assertEquals(true, IslamicChronology.getInstance().weekyear().isSupported()); assertEquals(true, IslamicChronology.getInstance().weekOfWeekyear().isSupported()); assertEquals(true, IslamicChronology.getInstance().dayOfYear().isSupported()); assertEquals(true, IslamicChronology.getInstance().dayOfMonth().isSupported()); assertEquals(true, IslamicChronology.getInstance().dayOfWeek().isSupported()); } public void testTimeFields() { assertEquals("halfdayOfDay", IslamicChronology.getInstance().halfdayOfDay().getName()); assertEquals("clockhourOfHalfday", IslamicChronology.getInstance().clockhourOfHalfday().getName()); assertEquals("hourOfHalfday", IslamicChronology.getInstance().hourOfHalfday().getName()); assertEquals("clockhourOfDay", IslamicChronology.getInstance().clockhourOfDay().getName()); assertEquals("hourOfDay", IslamicChronology.getInstance().hourOfDay().getName()); assertEquals("minuteOfDay", IslamicChronology.getInstance().minuteOfDay().getName()); assertEquals("minuteOfHour", IslamicChronology.getInstance().minuteOfHour().getName()); assertEquals("secondOfDay", IslamicChronology.getInstance().secondOfDay().getName()); assertEquals("secondOfMinute", IslamicChronology.getInstance().secondOfMinute().getName()); assertEquals("millisOfDay", IslamicChronology.getInstance().millisOfDay().getName()); assertEquals("millisOfSecond", IslamicChronology.getInstance().millisOfSecond().getName()); assertEquals(true, IslamicChronology.getInstance().halfdayOfDay().isSupported()); assertEquals(true, IslamicChronology.getInstance().clockhourOfHalfday().isSupported()); assertEquals(true, IslamicChronology.getInstance().hourOfHalfday().isSupported()); assertEquals(true, IslamicChronology.getInstance().clockhourOfDay().isSupported()); assertEquals(true, IslamicChronology.getInstance().hourOfDay().isSupported()); assertEquals(true, IslamicChronology.getInstance().minuteOfDay().isSupported()); assertEquals(true, IslamicChronology.getInstance().minuteOfHour().isSupported()); assertEquals(true, IslamicChronology.getInstance().secondOfDay().isSupported()); assertEquals(true, IslamicChronology.getInstance().secondOfMinute().isSupported()); assertEquals(true, IslamicChronology.getInstance().millisOfDay().isSupported()); assertEquals(true, IslamicChronology.getInstance().millisOfSecond().isSupported()); } //----------------------------------------------------------------------- public void testEpoch() { DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, ISLAMIC_UTC); DateTime expectedEpoch = new DateTime(622, 7, 16, 0, 0, 0, 0, JULIAN_UTC); assertEquals(expectedEpoch.getMillis(), epoch.getMillis()); } public void testEra() { assertEquals(1, IslamicChronology.AH); try { new DateTime(-1, 13, 5, 0, 0, 0, 0, ISLAMIC_UTC); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFieldConstructor() { DateTime date = new DateTime(1364, 12, 6, 0, 0, 0, 0, ISLAMIC_UTC); DateTime expectedDate = new DateTime(1945, 11, 12, 0, 0, 0, 0, ISO_UTC); assertEquals(expectedDate.getMillis(), date.getMillis()); } //----------------------------------------------------------------------- /** * Tests era, year, monthOfYear, dayOfMonth and dayOfWeek. */ public void testCalendar() { if (TestAll.FAST) { return; } System.out.println("\nTestIslamicChronology.testCalendar"); DateTime epoch = new DateTime(1, 1, 1, 0, 0, 0, 0, ISLAMIC_UTC); long millis = epoch.getMillis(); long end = new DateTime(3000, 1, 1, 0, 0, 0, 0, ISO_UTC).getMillis(); DateTimeField dayOfWeek = ISLAMIC_UTC.dayOfWeek(); DateTimeField dayOfYear = ISLAMIC_UTC.dayOfYear(); DateTimeField dayOfMonth = ISLAMIC_UTC.dayOfMonth(); DateTimeField monthOfYear = ISLAMIC_UTC.monthOfYear(); DateTimeField year = ISLAMIC_UTC.year(); DateTimeField yearOfEra = ISLAMIC_UTC.yearOfEra(); DateTimeField era = ISLAMIC_UTC.era(); int expectedDOW = new DateTime(622, 7, 16, 0, 0, 0, 0, JULIAN_UTC).getDayOfWeek(); int expectedDOY = 1; int expectedDay = 1; int expectedMonth = 1; int expectedYear = 1; while (millis < end) { int dowValue = dayOfWeek.get(millis); int doyValue = dayOfYear.get(millis); int dayValue = dayOfMonth.get(millis); int monthValue = monthOfYear.get(millis); int yearValue = year.get(millis); int yearOfEraValue = yearOfEra.get(millis); int dayOfYearLen = dayOfYear.getMaximumValue(millis); int monthLen = dayOfMonth.getMaximumValue(millis); if (monthValue < 1 || monthValue > 12) { fail("Bad month: " + millis); } // test era assertEquals(1, era.get(millis)); assertEquals("AH", era.getAsText(millis)); assertEquals("AH", era.getAsShortText(millis)); // test date assertEquals(expectedDOY, doyValue); assertEquals(expectedMonth, monthValue); assertEquals(expectedDay, dayValue); assertEquals(expectedDOW, dowValue); assertEquals(expectedYear, yearValue); assertEquals(expectedYear, yearOfEraValue); // test leap year boolean leap = ((11 * yearValue + 14) % 30) < 11; assertEquals(leap, year.isLeap(millis)); // test month length switch (monthValue) { case 1: case 3: case 5: case 7: case 9: case 11: assertEquals(30, monthLen); break; case 2: case 4: case 6: case 8: case 10: assertEquals(29, monthLen); break; case 12: assertEquals((leap ? 30 : 29), monthLen); break; } // test year length assertEquals((leap ? 355 : 354), dayOfYearLen); // recalculate date expectedDOW = (((expectedDOW + 1) - 1) % 7) + 1; expectedDay++; expectedDOY++; if (expectedDay > monthLen) { expectedDay = 1; expectedMonth++; if (expectedMonth == 13) { expectedMonth = 1; expectedDOY = 1; expectedYear++; } } millis += SKIP; } } public void testSampleDate1() { DateTime dt = new DateTime(1945, 11, 12, 0, 0, 0, 0, ISO_UTC); dt = dt.withChronology(ISLAMIC_UTC); assertEquals(IslamicChronology.AH, dt.getEra()); assertEquals(14, dt.getCenturyOfEra()); // TODO confirm assertEquals(64, dt.getYearOfCentury()); assertEquals(1364, dt.getYearOfEra()); assertEquals(1364, dt.getYear()); Property fld = dt.year(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(new DateTime(1365, 12, 6, 0, 0, 0, 0, ISLAMIC_UTC), fld.addToCopy(1)); assertEquals(12, dt.getMonthOfYear()); fld = dt.monthOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(12, fld.getMaximumValue()); assertEquals(12, fld.getMaximumValueOverall()); assertEquals(new DateTime(1365, 1, 6, 0, 0, 0, 0, ISLAMIC_UTC), fld.addToCopy(1)); assertEquals(new DateTime(1364, 1, 6, 0, 0, 0, 0, ISLAMIC_UTC), fld.addWrapFieldToCopy(1)); assertEquals(6, dt.getDayOfMonth()); fld = dt.dayOfMonth(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(29, fld.getMaximumValue()); assertEquals(30, fld.getMaximumValueOverall()); assertEquals(new DateTime(1364, 12, 7, 0, 0, 0, 0, ISLAMIC_UTC), fld.addToCopy(1)); assertEquals(DateTimeConstants.MONDAY, dt.getDayOfWeek()); fld = dt.dayOfWeek(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(7, fld.getMaximumValue()); assertEquals(7, fld.getMaximumValueOverall()); assertEquals(new DateTime(1364, 12, 7, 0, 0, 0, 0, ISLAMIC_UTC), fld.addToCopy(1)); assertEquals(6 * 30 + 5 * 29 + 6, dt.getDayOfYear()); fld = dt.dayOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(354, fld.getMaximumValue()); assertEquals(355, fld.getMaximumValueOverall()); assertEquals(new DateTime(1364, 12, 7, 0, 0, 0, 0, ISLAMIC_UTC), fld.addToCopy(1)); assertEquals(0, dt.getHourOfDay()); assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testSampleDate2() { DateTime dt = new DateTime(2005, 11, 26, 0, 0, 0, 0, ISO_UTC); dt = dt.withChronology(ISLAMIC_UTC); assertEquals(IslamicChronology.AH, dt.getEra()); assertEquals(15, dt.getCenturyOfEra()); // TODO confirm assertEquals(26, dt.getYearOfCentury()); assertEquals(1426, dt.getYearOfEra()); assertEquals(1426, dt.getYear()); Property fld = dt.year(); assertEquals(true, fld.isLeap()); assertEquals(1, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(10, dt.getMonthOfYear()); fld = dt.monthOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(12, fld.getMaximumValue()); assertEquals(12, fld.getMaximumValueOverall()); assertEquals(24, dt.getDayOfMonth()); fld = dt.dayOfMonth(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(29, fld.getMaximumValue()); assertEquals(30, fld.getMaximumValueOverall()); assertEquals(DateTimeConstants.SATURDAY, dt.getDayOfWeek()); fld = dt.dayOfWeek(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(7, fld.getMaximumValue()); assertEquals(7, fld.getMaximumValueOverall()); assertEquals(5 * 30 + 4 * 29 + 24, dt.getDayOfYear()); fld = dt.dayOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(355, fld.getMaximumValue()); assertEquals(355, fld.getMaximumValueOverall()); assertEquals(0, dt.getHourOfDay()); assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testSampleDate3() { DateTime dt = new DateTime(1426, 12, 24, 0, 0, 0, 0, ISLAMIC_UTC); assertEquals(IslamicChronology.AH, dt.getEra()); assertEquals(1426, dt.getYear()); Property fld = dt.year(); assertEquals(true, fld.isLeap()); assertEquals(1, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(12, dt.getMonthOfYear()); fld = dt.monthOfYear(); assertEquals(true, fld.isLeap()); assertEquals(1, fld.getLeapAmount()); assertEquals(DurationFieldType.days(), fld.getLeapDurationField().getType()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(12, fld.getMaximumValue()); assertEquals(12, fld.getMaximumValueOverall()); assertEquals(24, dt.getDayOfMonth()); fld = dt.dayOfMonth(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(30, fld.getMaximumValue()); assertEquals(30, fld.getMaximumValueOverall()); assertEquals(DateTimeConstants.TUESDAY, dt.getDayOfWeek()); fld = dt.dayOfWeek(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(7, fld.getMaximumValue()); assertEquals(7, fld.getMaximumValueOverall()); assertEquals(6 * 30 + 5 * 29 + 24, dt.getDayOfYear()); fld = dt.dayOfYear(); assertEquals(false, fld.isLeap()); assertEquals(0, fld.getLeapAmount()); assertEquals(null, fld.getLeapDurationField()); assertEquals(1, fld.getMinimumValue()); assertEquals(1, fld.getMinimumValueOverall()); assertEquals(355, fld.getMaximumValue()); assertEquals(355, fld.getMaximumValueOverall()); assertEquals(0, dt.getHourOfDay()); assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void testSampleDateWithZone() { DateTime dt = new DateTime(2005, 11, 26, 12, 0, 0, 0, PARIS).withChronology(ISLAMIC_UTC); assertEquals(IslamicChronology.AH, dt.getEra()); assertEquals(1426, dt.getYear()); assertEquals(10, dt.getMonthOfYear()); assertEquals(24, dt.getDayOfMonth()); assertEquals(11, dt.getHourOfDay()); // PARIS is UTC+1 in summer (12-1=11) assertEquals(0, dt.getMinuteOfHour()); assertEquals(0, dt.getSecondOfMinute()); assertEquals(0, dt.getMillisOfSecond()); } public void test15BasedLeapYear() { assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(1)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(2)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(3)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(4)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(5)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(6)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(7)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(8)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(9)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(10)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(11)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(12)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(13)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(14)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(15)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(16)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(17)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(18)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(19)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(20)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(21)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(22)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(23)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(24)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(25)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(26)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(27)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(28)); assertEquals(true, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(29)); assertEquals(false, IslamicChronology.LEAP_YEAR_15_BASED.isLeapYear(30)); } public void test16BasedLeapYear() { assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(1)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(2)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(3)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(4)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(5)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(6)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(7)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(8)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(9)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(10)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(11)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(12)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(13)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(14)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(15)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(16)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(17)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(18)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(19)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(20)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(21)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(22)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(23)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(24)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(25)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(26)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(27)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(28)); assertEquals(true, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(29)); assertEquals(false, IslamicChronology.LEAP_YEAR_16_BASED.isLeapYear(30)); } public void testIndianBasedLeapYear() { assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(1)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(2)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(3)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(4)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(5)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(6)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(7)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(8)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(9)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(10)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(11)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(12)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(13)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(14)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(15)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(16)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(17)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(18)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(19)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(20)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(21)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(22)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(23)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(24)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(25)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(26)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(27)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(28)); assertEquals(true, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(29)); assertEquals(false, IslamicChronology.LEAP_YEAR_INDIAN.isLeapYear(30)); } public void testHabashAlHasibBasedLeapYear() { assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(1)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(2)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(3)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(4)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(5)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(6)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(7)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(8)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(9)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(10)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(11)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(12)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(13)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(14)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(15)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(16)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(17)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(18)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(19)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(20)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(21)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(22)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(23)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(24)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(25)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(26)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(27)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(28)); assertEquals(false, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(29)); assertEquals(true, IslamicChronology.LEAP_YEAR_HABASH_AL_HASIB.isLeapYear(30)); } } joda-time-2.3/src/test/java/org/joda/time/TestInterval_Constructors.java0000644000175000017500000007454311564251363026012 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.IntervalConverter; /** * This class is a JUnit test for Interval. * * @author Stephen Colebourne */ public class TestInterval_Constructors extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // // 2002-04-05 // private long TEST_TIME1 = // (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 12L * DateTimeConstants.MILLIS_PER_HOUR // + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // // // 2003-05-06 // private long TEST_TIME2 = // (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 14L * DateTimeConstants.MILLIS_PER_HOUR // + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestInterval_Constructors.class); } public TestInterval_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(PARIS); TimeZone.setDefault(PARIS.toTimeZone()); Locale.setDefault(Locale.FRANCE); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { DateTime start = new DateTime(2010, 6, 30, 12, 30, ISOChronology.getInstance(PARIS)); DateTime end = new DateTime(2010, 7, 1, 14, 30, ISOChronology.getInstance(PARIS)); assertEquals(new Interval(start, end), Interval.parse("2010-06-30T12:30/2010-07-01T14:30")); assertEquals(new Interval(start, end), Interval.parse("2010-06-30T12:30/P1DT2H")); assertEquals(new Interval(start, end), Interval.parse("P1DT2H/2010-07-01T14:30")); } //----------------------------------------------------------------------- public void testConstructor_long_long1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1.getMillis(), dt2.getMillis()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } public void testConstructor_long_long2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Interval test = new Interval(dt1.getMillis(), dt1.getMillis()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt1.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } public void testConstructor_long_long3() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 10, 1, 1, 1, 1); DateTime dt2 = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { new Interval(dt1.getMillis(), dt2.getMillis()); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_long_long_Zone() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1.getMillis(), dt2.getMillis(), LONDON); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(LONDON), test.getChronology()); } public void testConstructor_long_long_nullZone() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1.getMillis(), dt2.getMillis(), (DateTimeZone) null); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testConstructor_long_long_Chronology() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1.getMillis(), dt2.getMillis(), GJChronology.getInstance()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(GJChronology.getInstance(), test.getChronology()); } public void testConstructor_long_long_nullChronology() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1.getMillis(), dt2.getMillis(), (Chronology) null); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testConstructor_RI_RI1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI2() throws Throwable { Instant dt1 = new Instant(new DateTime(2004, 6, 9, 0, 0, 0, 0)); Instant dt2 = new Instant(new DateTime(2005, 7, 10, 1, 1, 1, 1)); Interval test = new Interval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI3() throws Throwable { Interval test = new Interval((ReadableInstant) null, (ReadableInstant) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RI4() throws Throwable { DateTime dt1 = new DateTime(2000, 6, 9, 0, 0, 0, 0); Interval test = new Interval(dt1, (ReadableInstant) null); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RI5() throws Throwable { DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval((ReadableInstant) null, dt2); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI6() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Interval test = new Interval(dt1, dt1); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt1.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RI7() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 10, 1, 1, 1, 1); DateTime dt2 = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { new Interval(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor_RI_RI_chronoStart() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0, GJChronology.getInstance()); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(GJChronology.getInstance(), test.getChronology()); } public void testConstructor_RI_RI_chronoEnd() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1, GJChronology.getInstance()); Interval test = new Interval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } public void testConstructor_RI_RI_zones() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0, LONDON); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1, PARIS); Interval test = new Interval(dt1, dt2); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(LONDON), test.getChronology()); } public void testConstructor_RI_RI_instant() throws Throwable { Instant dt1 = new Instant(12345678L); Instant dt2 = new Instant(22345678L); Interval test = new Interval(dt1, dt2); assertEquals(12345678L, test.getStartMillis()); assertEquals(22345678L, test.getEndMillis()); assertEquals(ISOChronology.getInstanceUTC(), test.getChronology()); } //----------------------------------------------------------------------- public void testConstructor_RI_RP1() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, 6); result = ISOChronology.getInstance().hours().add(result, 1); Interval test = new Interval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP2() throws Throwable { Instant dt = new Instant(new DateTime(TEST_TIME_NOW)); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstanceUTC().months().add(result, 6); result = ISOChronology.getInstanceUTC().days().add(result, 3); result = ISOChronology.getInstanceUTC().hours().add(result, 1); Interval test = new Interval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW, CopticChronology.getInstanceUTC()); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0, PeriodType.standard()); long result = TEST_TIME_NOW; result = CopticChronology.getInstanceUTC().months().add(result, 6); result = CopticChronology.getInstanceUTC().days().add(result, 3); result = CopticChronology.getInstanceUTC().hours().add(result, 1); Interval test = new Interval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP4() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(1 * DateTimeConstants.MILLIS_PER_HOUR + 23L); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().hours().add(result, 1); result = ISOChronology.getInstance().millis().add(result, 23); Interval test = new Interval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP5() throws Throwable { Interval test = new Interval((ReadableInstant) null, (ReadablePeriod) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RP6() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Interval test = new Interval(dt, (ReadablePeriod) null); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RP7() throws Throwable { Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, 6); result = ISOChronology.getInstance().hourOfDay().add(result, 1); Interval test = new Interval((ReadableInstant) null, dur); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RP8() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 0, 0, 0, 0, 0, 0, -1); try { new Interval(dt, dur); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_RP_RI1() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, -6); result = ISOChronology.getInstance().hours().add(result, -1); Interval test = new Interval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI2() throws Throwable { Instant dt = new Instant(new DateTime(TEST_TIME_NOW)); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstanceUTC().months().add(result, -6); result = ISOChronology.getInstanceUTC().days().add(result, -3); result = ISOChronology.getInstanceUTC().hours().add(result, -1); Interval test = new Interval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW, CopticChronology.getInstanceUTC()); Period dur = new Period(0, 6, 0, 3, 1, 0, 0, 0, PeriodType.standard()); long result = TEST_TIME_NOW; result = CopticChronology.getInstanceUTC().months().add(result, -6); result = CopticChronology.getInstanceUTC().days().add(result, -3); result = CopticChronology.getInstanceUTC().hours().add(result, -1); Interval test = new Interval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI4() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(1 * DateTimeConstants.MILLIS_PER_HOUR + 23L); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().hours().add(result, -1); result = ISOChronology.getInstance().millis().add(result, -23); Interval test = new Interval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI5() throws Throwable { Interval test = new Interval((ReadablePeriod) null, (ReadableInstant) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RP_RI6() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Interval test = new Interval((ReadablePeriod) null, dt); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RP_RI7() throws Throwable { Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, -6); result = ISOChronology.getInstance().hourOfDay().add(result, -1); Interval test = new Interval(dur, (ReadableInstant) null); assertEquals(result, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RP_RI8() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 0, 0, 0, 0, 0, 0, -1); try { new Interval(dur, dt); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_RI_RD1() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, 6); result = ISOChronology.getInstance().hours().add(result, 1); DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(result - TEST_TIME_NOW); Interval test = new Interval(dt, dur); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RD2() throws Throwable { Interval test = new Interval((ReadableInstant) null, (ReadableDuration) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RI_RD3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Interval test = new Interval(dt, (ReadableDuration) null); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RI_RD4() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, 6); result = ISOChronology.getInstance().hourOfDay().add(result, 1); Duration dur = new Duration(result - TEST_TIME_NOW); Interval test = new Interval((ReadableInstant) null, dur); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(result, test.getEndMillis()); } public void testConstructor_RI_RD5() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(-1); try { new Interval(dt, dur); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_RD_RI1() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().months().add(result, -6); result = ISOChronology.getInstance().hours().add(result, -1); DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(TEST_TIME_NOW - result); Interval test = new Interval(dur, dt); assertEquals(result, test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RD_RI2() throws Throwable { Interval test = new Interval((ReadableDuration) null, (ReadableInstant) null); assertEquals(TEST_TIME_NOW, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RD_RI3() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Interval test = new Interval((ReadableDuration) null, dt); assertEquals(dt.getMillis(), test.getStartMillis()); assertEquals(dt.getMillis(), test.getEndMillis()); } public void testConstructor_RD_RI4() throws Throwable { long result = TEST_TIME_NOW; result = ISOChronology.getInstance().monthOfYear().add(result, -6); result = ISOChronology.getInstance().hourOfDay().add(result, -1); Duration dur = new Duration(TEST_TIME_NOW - result); Interval test = new Interval(dur, (ReadableInstant) null); assertEquals(result, test.getStartMillis()); assertEquals(TEST_TIME_NOW, test.getEndMillis()); } public void testConstructor_RD_RI5() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Duration dur = new Duration(-1); try { new Interval(dur, dt); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_Object1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1.toString() + '/' + dt2.toString()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_Object2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval base = new Interval(dt1, dt2); Interval test = new Interval(base); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_Object3() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval base = new MutableInterval(dt1, dt2); Interval test = new Interval(base); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); } public void testConstructor_Object4() throws Throwable { MockInterval base = new MockInterval(); Interval test = new Interval(base); assertEquals(base.getStartMillis(), test.getStartMillis()); assertEquals(base.getEndMillis(), test.getEndMillis()); } public void testConstructor_Object5() throws Throwable { IntervalConverter oldConv = ConverterManager.getInstance().getIntervalConverter(""); IntervalConverter conv = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) { return false; } public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) { interval.setChronology(chrono); interval.setInterval(1234L, 5678L); } public Class getSupportedType() { return String.class; } }; try { ConverterManager.getInstance().addIntervalConverter(conv); DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval test = new Interval(dt1.toString() + '/' + dt2.toString()); assertEquals(1234L, test.getStartMillis()); assertEquals(5678L, test.getEndMillis()); } finally { ConverterManager.getInstance().addIntervalConverter(oldConv); } } public void testConstructor_Object6() throws Throwable { IntervalConverter oldConv = ConverterManager.getInstance().getIntervalConverter(new Interval(0L, 0L)); IntervalConverter conv = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) { return false; } public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) { interval.setChronology(chrono); interval.setInterval(1234L, 5678L); } public Class getSupportedType() { return ReadableInterval.class; } }; try { ConverterManager.getInstance().addIntervalConverter(conv); Interval base = new Interval(-1000L, 1000L); Interval test = new Interval(base); assertEquals(1234L, test.getStartMillis()); assertEquals(5678L, test.getEndMillis()); } finally { ConverterManager.getInstance().addIntervalConverter(oldConv); } } class MockInterval implements ReadableInterval { public Chronology getChronology() { return ISOChronology.getInstance(); } public long getStartMillis() { return 1234L; } public DateTime getStart() { return new DateTime(1234L); } public long getEndMillis() { return 5678L; } public DateTime getEnd() { return new DateTime(5678L); } public long toDurationMillis() { return (5678L - 1234L); } public Duration toDuration() { return new Duration(5678L - 1234L); } public boolean contains(long millisInstant) { return false; } public boolean containsNow() { return false; } public boolean contains(ReadableInstant instant) { return false; } public boolean contains(ReadableInterval interval) { return false; } public boolean overlaps(ReadableInterval interval) { return false; } public boolean isBefore(ReadableInstant instant) { return false; } public boolean isBefore(ReadableInterval interval) { return false; } public boolean isAfter(ReadableInstant instant) { return false; } public boolean isAfter(ReadableInterval interval) { return false; } public Interval toInterval() { return null; } public MutableInterval toMutableInterval() { return null; } public Period toPeriod() { return null; } public Period toPeriod(PeriodType type) { return null; } } //----------------------------------------------------------------------- public void testConstructor_Object_Chronology1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval base = new Interval(dt1, dt2); Interval test = new Interval(base, BuddhistChronology.getInstance()); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(BuddhistChronology.getInstance(), test.getChronology()); } public void testConstructor_Object_Chronology2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Interval base = new Interval(dt1, dt2); Interval test = new Interval(base, null); assertEquals(dt1.getMillis(), test.getStartMillis()); assertEquals(dt2.getMillis(), test.getEndMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } } joda-time-2.3/src/test/java/org/joda/time/TestBasePartial.java0000644000175000017500000001063411564251363023614 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.BasePartial; /** * This class is a Junit unit test for YearMonthDay. * * @author Stephen Colebourne */ public class TestBasePartial extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestBasePartial.class); } public TestBasePartial(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testSetMethods() throws Throwable { MockPartial mock = new MockPartial(); assertEquals(1970, mock.getYear()); assertEquals(1, mock.getMonthOfYear()); mock.setYear(2004); assertEquals(2004, mock.getYear()); assertEquals(1, mock.getMonthOfYear()); mock.setMonthOfYear(6); assertEquals(2004, mock.getYear()); assertEquals(6, mock.getMonthOfYear()); mock.set(2005, 5); assertEquals(2005, mock.getYear()); assertEquals(5, mock.getMonthOfYear()); try { mock.setMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} assertEquals(2005, mock.getYear()); assertEquals(5, mock.getMonthOfYear()); try { mock.setMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} assertEquals(2005, mock.getYear()); assertEquals(5, mock.getMonthOfYear()); } static class MockPartial extends BasePartial { MockPartial() { super(new int[] {1970, 1}, null); } protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case 0: return chrono.year(); case 1: return chrono.monthOfYear(); default: throw new IndexOutOfBoundsException(); } } public int size() { return 2; } public int getYear() { return getValue(0); } public void setYear(int year) { setValue(0, year); } public int getMonthOfYear() { return getValue(1); } public void setMonthOfYear(int month) { setValue(1, month); } public void set(int year, int month) { setValues(new int[] {year, month}); } } } joda-time-2.3/src/test/java/org/joda/time/TestChronology.java0000644000175000017500000002654411564251363023557 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.EthiopicChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.IslamicChronology; import org.joda.time.chrono.JulianChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.LimitChronology; import org.joda.time.chrono.StrictChronology; import org.joda.time.chrono.ZonedChronology; /** * This class is a Junit unit test for Chronology. * * @author Stephen Colebourne */ public class TestChronology extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) // private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestChronology.class); } public TestChronology(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testEqualsHashCode_ISO() { Chronology chrono1 = ISOChronology.getInstanceUTC(); Chronology chrono2 = ISOChronology.getInstanceUTC(); Chronology chrono3 = ISOChronology.getInstance(); assertEquals(true, chrono1.equals(chrono2)); assertEquals(false, chrono1.equals(chrono3)); DateTime dt1 = new DateTime(0L, chrono1); DateTime dt2 = new DateTime(0L, chrono2); DateTime dt3 = new DateTime(0L, chrono3); assertEquals(true, dt1.equals(dt2)); assertEquals(false, dt1.equals(dt3)); assertEquals(true, chrono1.hashCode() == chrono2.hashCode()); assertEquals(false, chrono1.hashCode() == chrono3.hashCode()); } //----------------------------------------------------------------------- public void testEqualsHashCode_Lenient() { Chronology chrono1 = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); Chronology chrono2 = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); Chronology chrono3 = LenientChronology.getInstance(ISOChronology.getInstance()); assertEquals(true, chrono1.equals(chrono2)); assertEquals(false, chrono1.equals(chrono3)); DateTime dt1 = new DateTime(0L, chrono1); DateTime dt2 = new DateTime(0L, chrono2); DateTime dt3 = new DateTime(0L, chrono3); assertEquals(true, dt1.equals(dt2)); assertEquals(false, dt1.equals(dt3)); assertEquals(true, chrono1.hashCode() == chrono2.hashCode()); assertEquals(false, chrono1.hashCode() == chrono3.hashCode()); } //----------------------------------------------------------------------- public void testEqualsHashCode_Strict() { Chronology chrono1 = StrictChronology.getInstance(ISOChronology.getInstanceUTC()); Chronology chrono2 = StrictChronology.getInstance(ISOChronology.getInstanceUTC()); Chronology chrono3 = StrictChronology.getInstance(ISOChronology.getInstance()); assertEquals(true, chrono1.equals(chrono2)); assertEquals(false, chrono1.equals(chrono3)); DateTime dt1 = new DateTime(0L, chrono1); DateTime dt2 = new DateTime(0L, chrono2); DateTime dt3 = new DateTime(0L, chrono3); assertEquals(true, dt1.equals(dt2)); assertEquals(false, dt1.equals(dt3)); assertEquals(true, chrono1.hashCode() == chrono2.hashCode()); assertEquals(false, chrono1.hashCode() == chrono3.hashCode()); } //----------------------------------------------------------------------- public void testEqualsHashCode_Limit() { DateTime lower = new DateTime(0L); DateTime higherA = new DateTime(1000000L); DateTime higherB = new DateTime(2000000L); Chronology chrono1 = LimitChronology.getInstance(ISOChronology.getInstanceUTC(), lower, higherA); Chronology chrono2A = LimitChronology.getInstance(ISOChronology.getInstanceUTC(), lower, higherA); Chronology chrono2B = LimitChronology.getInstance(ISOChronology.getInstanceUTC(), lower, higherB); Chronology chrono3 = LimitChronology.getInstance(ISOChronology.getInstance(), lower, higherA); assertEquals(true, chrono1.equals(chrono2A)); assertEquals(false, chrono1.equals(chrono2B)); assertEquals(false, chrono1.equals(chrono3)); DateTime dt1 = new DateTime(0L, chrono1); DateTime dt2A = new DateTime(0L, chrono2A); DateTime dt2B = new DateTime(0L, chrono2B); DateTime dt3 = new DateTime(0L, chrono3); assertEquals(true, dt1.equals(dt2A)); assertEquals(false, dt1.equals(dt2B)); assertEquals(false, dt1.equals(dt3)); assertEquals(true, chrono1.hashCode() == chrono2A.hashCode()); assertEquals(false, chrono1.hashCode() == chrono2B.hashCode()); assertEquals(false, chrono1.hashCode() == chrono3.hashCode()); } //----------------------------------------------------------------------- public void testEqualsHashCode_Zoned() { DateTimeZone zoneA = DateTimeZone.forID("Europe/Paris"); DateTimeZone zoneB = DateTimeZone.forID("Asia/Tokyo"); Chronology chrono1 = ZonedChronology.getInstance(ISOChronology.getInstanceUTC(), zoneA); Chronology chrono2 = ZonedChronology.getInstance(ISOChronology.getInstanceUTC(), zoneA); Chronology chrono3 = ZonedChronology.getInstance(ISOChronology.getInstanceUTC(), zoneB); assertEquals(true, chrono1.equals(chrono2)); assertEquals(false, chrono1.equals(chrono3)); DateTime dt1 = new DateTime(0L, chrono1); DateTime dt2 = new DateTime(0L, chrono2); DateTime dt3 = new DateTime(0L, chrono3); assertEquals(true, dt1.equals(dt2)); assertEquals(false, dt1.equals(dt3)); assertEquals(true, chrono1.hashCode() == chrono2.hashCode()); assertEquals(false, chrono1.hashCode() == chrono3.hashCode()); } //----------------------------------------------------------------------- public void testToString() { DateTimeZone paris = DateTimeZone.forID("Europe/Paris"); ISOChronology isoParis = ISOChronology.getInstance(paris); assertEquals("ISOChronology[Europe/Paris]", isoParis.toString()); assertEquals("GJChronology[Europe/Paris]", GJChronology.getInstance(paris).toString()); assertEquals("GregorianChronology[Europe/Paris]", GregorianChronology.getInstance(paris).toString()); assertEquals("JulianChronology[Europe/Paris]", JulianChronology.getInstance(paris).toString()); assertEquals("BuddhistChronology[Europe/Paris]", BuddhistChronology.getInstance(paris).toString()); assertEquals("CopticChronology[Europe/Paris]", CopticChronology.getInstance(paris).toString()); assertEquals("EthiopicChronology[Europe/Paris]", EthiopicChronology.getInstance(paris).toString()); assertEquals("IslamicChronology[Europe/Paris]", IslamicChronology.getInstance(paris).toString()); assertEquals("LenientChronology[ISOChronology[Europe/Paris]]", LenientChronology.getInstance(isoParis).toString()); assertEquals("StrictChronology[ISOChronology[Europe/Paris]]", StrictChronology.getInstance(isoParis).toString()); assertEquals("LimitChronology[ISOChronology[Europe/Paris], NoLimit, NoLimit]", LimitChronology.getInstance(isoParis, null, null).toString()); assertEquals("ZonedChronology[ISOChronology[UTC], Europe/Paris]", ZonedChronology.getInstance(isoParis, paris).toString()); } } joda-time-2.3/src/test/java/org/joda/time/TestDateMidnight_Properties.java0000644000175000017500000007071412200501234026166 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.StrictChronology; /** * This class is a Junit unit test for DateTime. * * @author Stephen Colebourne * @author Mike Schrag */ @SuppressWarnings("deprecation") public class TestDateMidnight_Properties extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); //private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 Fri private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 Tue private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateMidnight_Properties.class); } public TestDateMidnight_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); Locale.setDefault(locale); zone = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testPropertyGetEra() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().era(), test.era().getField()); assertEquals("era", test.era().getName()); assertEquals("Property[era]", test.era().toString()); assertSame(test, test.era().getDateMidnight()); assertEquals(1, test.era().get()); assertEquals("AD", test.era().getAsText()); assertEquals("ap. J.-C.", test.era().getAsText(Locale.FRENCH)); assertEquals("AD", test.era().getAsShortText()); assertEquals("ap. J.-C.", test.era().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().eras(), test.era().getDurationField()); assertEquals(null, test.era().getRangeDurationField()); assertEquals(2, test.era().getMaximumTextLength(null)); assertEquals(9, test.era().getMaximumTextLength(Locale.FRENCH)); assertEquals(2, test.era().getMaximumShortTextLength(null)); assertEquals(9, test.era().getMaximumShortTextLength(Locale.FRENCH)); } //----------------------------------------------------------------------- public void testPropertyGetYearOfEra() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().yearOfEra(), test.yearOfEra().getField()); assertEquals("yearOfEra", test.yearOfEra().getName()); assertEquals("Property[yearOfEra]", test.yearOfEra().toString()); assertSame(test, test.yearOfEra().getDateMidnight()); assertEquals(2004, test.yearOfEra().get()); assertEquals("2004", test.yearOfEra().getAsText()); assertEquals("2004", test.yearOfEra().getAsText(Locale.FRENCH)); assertEquals("2004", test.yearOfEra().getAsShortText()); assertEquals("2004", test.yearOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfEra().getDurationField()); assertEquals(null, test.yearOfEra().getRangeDurationField()); assertEquals(9, test.yearOfEra().getMaximumTextLength(null)); assertEquals(9, test.yearOfEra().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetCenturyOfEra() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().centuryOfEra(), test.centuryOfEra().getField()); assertEquals("centuryOfEra", test.centuryOfEra().getName()); assertEquals("Property[centuryOfEra]", test.centuryOfEra().toString()); assertSame(test, test.centuryOfEra().getDateMidnight()); assertEquals(20, test.centuryOfEra().get()); assertEquals("20", test.centuryOfEra().getAsText()); assertEquals("20", test.centuryOfEra().getAsText(Locale.FRENCH)); assertEquals("20", test.centuryOfEra().getAsShortText()); assertEquals("20", test.centuryOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().centuries(), test.centuryOfEra().getDurationField()); assertEquals(null, test.centuryOfEra().getRangeDurationField()); assertEquals(7, test.centuryOfEra().getMaximumTextLength(null)); assertEquals(7, test.centuryOfEra().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetYearOfCentury() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().yearOfCentury(), test.yearOfCentury().getField()); assertEquals("yearOfCentury", test.yearOfCentury().getName()); assertEquals("Property[yearOfCentury]", test.yearOfCentury().toString()); assertSame(test, test.yearOfCentury().getDateMidnight()); assertEquals(4, test.yearOfCentury().get()); assertEquals("4", test.yearOfCentury().getAsText()); assertEquals("4", test.yearOfCentury().getAsText(Locale.FRENCH)); assertEquals("4", test.yearOfCentury().getAsShortText()); assertEquals("4", test.yearOfCentury().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfCentury().getDurationField()); assertEquals(test.getChronology().centuries(), test.yearOfCentury().getRangeDurationField()); assertEquals(2, test.yearOfCentury().getMaximumTextLength(null)); assertEquals(2, test.yearOfCentury().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetWeekyear() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().weekyear(), test.weekyear().getField()); assertEquals("weekyear", test.weekyear().getName()); assertEquals("Property[weekyear]", test.weekyear().toString()); assertSame(test, test.weekyear().getDateMidnight()); assertEquals(2004, test.weekyear().get()); assertEquals("2004", test.weekyear().getAsText()); assertEquals("2004", test.weekyear().getAsText(Locale.FRENCH)); assertEquals("2004", test.weekyear().getAsShortText()); assertEquals("2004", test.weekyear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().weekyears(), test.weekyear().getDurationField()); assertEquals(null, test.weekyear().getRangeDurationField()); assertEquals(9, test.weekyear().getMaximumTextLength(null)); assertEquals(9, test.weekyear().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetYear() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertSame(test, test.year().getDateMidnight()); assertEquals(2004, test.year().get()); assertEquals("2004", test.year().getAsText()); assertEquals("2004", test.year().getAsText(Locale.FRENCH)); assertEquals("2004", test.year().getAsShortText()); assertEquals("2004", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292278993, test.year().getMaximumValue()); assertEquals(292278993, test.year().getMaximumValueOverall()); } //----------------------------------------------------------------------- public void testPropertyGetMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getDateMidnight()); assertEquals(6, test.monthOfYear().get()); assertEquals("6", test.monthOfYear().getAsString()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new DateMidnight(2004, 7, 9); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertySetMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.monthOfYear().setCopy(8); assertEquals(2004, copy.getYear()); assertEquals(8, copy.getMonthOfYear()); assertEquals(9, copy.getDayOfMonth()); } public void testPropertySetTextMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.monthOfYear().setCopy("8"); assertEquals(2004, copy.getYear()); assertEquals(8, copy.getMonthOfYear()); assertEquals(9, copy.getDayOfMonth()); } public void testPropertySetTextLocaleMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.monthOfYear().setCopy("mars", Locale.FRENCH); assertEquals(2004, copy.getYear()); assertEquals(3, copy.getMonthOfYear()); assertEquals(9, copy.getDayOfMonth()); } public void testPropertyAddMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.monthOfYear().addToCopy(8); assertEquals(2005, copy.getYear()); assertEquals(2, copy.getMonthOfYear()); assertEquals(9, copy.getDayOfMonth()); } public void testPropertyAddLongMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.monthOfYear().addToCopy(8L); assertEquals(2005, copy.getYear()); assertEquals(2, copy.getMonthOfYear()); assertEquals(9, copy.getDayOfMonth()); } public void testPropertyAddWrapFieldMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.monthOfYear().addWrapFieldToCopy(8); assertEquals(2004, copy.getYear()); assertEquals(2, copy.getMonthOfYear()); assertEquals(9, copy.getDayOfMonth()); } public void testPropertyGetDifferenceMonthOfYear() { DateMidnight test1 = new DateMidnight(2004, 6, 9); DateMidnight test2 = new DateMidnight(2004, 8, 9); assertEquals(-2, test1.monthOfYear().getDifference(test2)); assertEquals(2, test2.monthOfYear().getDifference(test1)); assertEquals(-2L, test1.monthOfYear().getDifferenceAsLong(test2)); assertEquals(2L, test2.monthOfYear().getDifferenceAsLong(test1)); } public void testPropertyRoundFloorMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 16); DateMidnight copy = test.monthOfYear().roundFloorCopy(); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); } public void testPropertyRoundCeilingMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 16); DateMidnight copy = test.monthOfYear().roundCeilingCopy(); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); } public void testPropertyRoundHalfFloorMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 16); DateMidnight copy = test.monthOfYear().roundHalfFloorCopy(); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); test = new DateMidnight(2004, 6, 17); copy = test.monthOfYear().roundHalfFloorCopy(); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); test = new DateMidnight(2004, 6, 15); copy = test.monthOfYear().roundHalfFloorCopy(); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); } public void testPropertyRoundHalfCeilingMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 16); DateMidnight copy = test.monthOfYear().roundHalfCeilingCopy(); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); test = new DateMidnight(2004, 6, 17); copy = test.monthOfYear().roundHalfCeilingCopy(); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); test = new DateMidnight(2004, 6, 15); copy = test.monthOfYear().roundHalfCeilingCopy(); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); } public void testPropertyRoundHalfEvenMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 16); DateMidnight copy = test.monthOfYear().roundHalfEvenCopy(); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); test = new DateMidnight(2004, 9, 16); copy = test.monthOfYear().roundHalfEvenCopy(); assertEquals("2004-10-01T00:00:00.000+01:00", copy.toString()); test = new DateMidnight(2004, 6, 17); copy = test.monthOfYear().roundHalfEvenCopy(); assertEquals("2004-07-01T00:00:00.000+01:00", copy.toString()); test = new DateMidnight(2004, 6, 15); copy = test.monthOfYear().roundHalfEvenCopy(); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); } public void testPropertyRemainderMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); assertEquals((9L - 1L) * DateTimeConstants.MILLIS_PER_DAY, test.monthOfYear().remainder()); } //----------------------------------------------------------------------- public void testPropertyGetDayOfMonth() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertSame(test, test.dayOfMonth().getDateMidnight()); assertEquals(9, test.dayOfMonth().get()); assertEquals("9", test.dayOfMonth().getAsText()); assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("9", test.dayOfMonth().getAsShortText()); assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); assertEquals(false, test.dayOfMonth().isLeap()); assertEquals(0, test.dayOfMonth().getLeapAmount()); assertEquals(null, test.dayOfMonth().getLeapDurationField()); } public void testPropertyWithMaximumValueDayOfMonth() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.dayOfMonth().withMaximumValue(); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-30T00:00:00.000+01:00", copy.toString()); } public void testPropertyWithMinimumValueDayOfMonth() { DateMidnight test = new DateMidnight(2004, 6, 9); DateMidnight copy = test.dayOfMonth().withMinimumValue(); assertEquals("2004-06-09T00:00:00.000+01:00", test.toString()); assertEquals("2004-06-01T00:00:00.000+01:00", copy.toString()); } //----------------------------------------------------------------------- public void testPropertyGetDayOfYear() { // 31+29+31+30+31+9 = 161 DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().dayOfYear(), test.dayOfYear().getField()); assertEquals("dayOfYear", test.dayOfYear().getName()); assertEquals("Property[dayOfYear]", test.dayOfYear().toString()); assertSame(test, test.dayOfYear().getDateMidnight()); assertEquals(161, test.dayOfYear().get()); assertEquals("161", test.dayOfYear().getAsText()); assertEquals("161", test.dayOfYear().getAsText(Locale.FRENCH)); assertEquals("161", test.dayOfYear().getAsShortText()); assertEquals("161", test.dayOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.dayOfYear().getRangeDurationField()); assertEquals(3, test.dayOfYear().getMaximumTextLength(null)); assertEquals(3, test.dayOfYear().getMaximumShortTextLength(null)); assertEquals(false, test.dayOfYear().isLeap()); assertEquals(0, test.dayOfYear().getLeapAmount()); assertEquals(null, test.dayOfYear().getLeapDurationField()); } //----------------------------------------------------------------------- public void testPropertyGetWeekOfWeekyear() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().weekOfWeekyear(), test.weekOfWeekyear().getField()); assertEquals("weekOfWeekyear", test.weekOfWeekyear().getName()); assertEquals("Property[weekOfWeekyear]", test.weekOfWeekyear().toString()); assertSame(test, test.weekOfWeekyear().getDateMidnight()); assertEquals(24, test.weekOfWeekyear().get()); assertEquals("24", test.weekOfWeekyear().getAsText()); assertEquals("24", test.weekOfWeekyear().getAsText(Locale.FRENCH)); assertEquals("24", test.weekOfWeekyear().getAsShortText()); assertEquals("24", test.weekOfWeekyear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().weeks(), test.weekOfWeekyear().getDurationField()); assertEquals(test.getChronology().weekyears(), test.weekOfWeekyear().getRangeDurationField()); assertEquals(2, test.weekOfWeekyear().getMaximumTextLength(null)); assertEquals(2, test.weekOfWeekyear().getMaximumShortTextLength(null)); assertEquals(false, test.weekOfWeekyear().isLeap()); assertEquals(0, test.weekOfWeekyear().getLeapAmount()); assertEquals(null, test.weekOfWeekyear().getLeapDurationField()); } //----------------------------------------------------------------------- public void testPropertyGetDayOfWeek() { DateMidnight test = new DateMidnight(2004, 6, 9); assertSame(test.getChronology().dayOfWeek(), test.dayOfWeek().getField()); assertEquals("dayOfWeek", test.dayOfWeek().getName()); assertEquals("Property[dayOfWeek]", test.dayOfWeek().toString()); assertSame(test, test.dayOfWeek().getDateMidnight()); assertEquals(3, test.dayOfWeek().get()); assertEquals("3", test.dayOfWeek().getAsString()); assertEquals("Wednesday", test.dayOfWeek().getAsText()); assertEquals("mercredi", test.dayOfWeek().getAsText(Locale.FRENCH)); assertEquals("Wed", test.dayOfWeek().getAsShortText()); assertEquals("mer.", test.dayOfWeek().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfWeek().getDurationField()); assertEquals(test.getChronology().weeks(), test.dayOfWeek().getRangeDurationField()); assertEquals(9, test.dayOfWeek().getMaximumTextLength(null)); assertEquals(8, test.dayOfWeek().getMaximumTextLength(Locale.FRENCH)); assertEquals(3, test.dayOfWeek().getMaximumShortTextLength(null)); assertEquals(4, test.dayOfWeek().getMaximumShortTextLength(Locale.FRENCH)); assertEquals(1, test.dayOfWeek().getMinimumValue()); assertEquals(1, test.dayOfWeek().getMinimumValueOverall()); assertEquals(7, test.dayOfWeek().getMaximumValue()); assertEquals(7, test.dayOfWeek().getMaximumValueOverall()); assertEquals(false, test.dayOfWeek().isLeap()); assertEquals(0, test.dayOfWeek().getLeapAmount()); assertEquals(null, test.dayOfWeek().getLeapDurationField()); } //----------------------------------------------------------------------- public void testPropertyToIntervalYearOfEra() { DateMidnight test = new DateMidnight(2004, 6, 9); Interval testInterval = test.yearOfEra().toInterval(); assertEquals(new DateMidnight(2004, 1, 1), testInterval.getStart()); assertEquals(new DateMidnight(2005, 1, 1), testInterval.getEnd()); } public void testPropertyToIntervalYearOfCentury() { DateMidnight test = new DateMidnight(2004, 6, 9); Interval testInterval = test.yearOfCentury().toInterval(); assertEquals(new DateMidnight(2004, 1, 1), testInterval.getStart()); assertEquals(new DateMidnight(2005, 1, 1), testInterval.getEnd()); } public void testPropertyToIntervalYear() { DateMidnight test = new DateMidnight(2004, 6, 9); Interval testInterval = test.year().toInterval(); assertEquals(new DateMidnight(2004, 1, 1), testInterval.getStart()); assertEquals(new DateMidnight(2005, 1, 1), testInterval.getEnd()); } public void testPropertyToIntervalMonthOfYear() { DateMidnight test = new DateMidnight(2004, 6, 9); Interval testInterval = test.monthOfYear().toInterval(); assertEquals(new DateMidnight(2004, 6, 1), testInterval.getStart()); assertEquals(new DateMidnight(2004, 7, 1), testInterval.getEnd()); } public void testPropertyToIntervalDayOfMonth() { DateMidnight test = new DateMidnight(2004, 6, 9); Interval testInterval = test.dayOfMonth().toInterval(); assertEquals(new DateMidnight(2004, 6, 9), testInterval.getStart()); assertEquals(new DateMidnight(2004, 6, 10), testInterval.getEnd()); DateMidnight febTest = new DateMidnight(2004, 2, 29); Interval febTestInterval = febTest.dayOfMonth().toInterval(); assertEquals(new DateMidnight(2004, 2, 29), febTestInterval.getStart()); assertEquals(new DateMidnight(2004, 3, 1), febTestInterval.getEnd()); } public void testPropertyEqualsHashCodeLenient() { DateMidnight test1 = new DateMidnight(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); DateMidnight test2 = new DateMidnight(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } public void testPropertyEqualsHashCodeStrict() { DateMidnight test1 = new DateMidnight(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); DateMidnight test2 = new DateMidnight(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } } joda-time-2.3/src/test/java/org/joda/time/convert/0000755000175000017500000000000012205344143021366 5ustar ebourgebourgjoda-time-2.3/src/test/java/org/joda/time/convert/TestReadableIntervalConverter.java0000644000175000017500000001742211564251364030204 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.MutableInterval; import org.joda.time.MutablePeriod; import org.joda.time.PeriodType; import org.joda.time.ReadableInterval; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a JUnit test for ReadableIntervalConverter. * * @author Stephen Colebourne */ public class TestReadableIntervalConverter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology JULIAN; private static Chronology ISO; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestReadableIntervalConverter.class); } public TestReadableIntervalConverter(String name) { super(name); } protected void setUp() throws Exception { JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadableIntervalConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(ReadableInterval.class, ReadableIntervalConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetDurationMillis_Object() throws Exception { Interval i = new Interval(100L, 223L); assertEquals(123L, ReadableIntervalConverter.INSTANCE.getDurationMillis(i)); } //----------------------------------------------------------------------- public void testGetPeriodType_Object() throws Exception { Interval i = new Interval(100L, 223L); assertEquals(PeriodType.standard(), ReadableIntervalConverter.INSTANCE.getPeriodType(i)); } public void testSetIntoPeriod_Object1() throws Exception { Interval i = new Interval(100L, 223L); MutablePeriod m = new MutablePeriod(PeriodType.millis()); ReadableIntervalConverter.INSTANCE.setInto(m, i, null); assertEquals(0, m.getYears()); assertEquals(0, m.getMonths()); assertEquals(0, m.getWeeks()); assertEquals(0, m.getDays()); assertEquals(0, m.getHours()); assertEquals(0, m.getMinutes()); assertEquals(0, m.getSeconds()); assertEquals(123, m.getMillis()); } public void testSetIntoPeriod_Object2() throws Exception { Interval i = new Interval(100L, 223L); MutablePeriod m = new MutablePeriod(PeriodType.millis()); ReadableIntervalConverter.INSTANCE.setInto(m, i, CopticChronology.getInstance()); assertEquals(0, m.getYears()); assertEquals(0, m.getMonths()); assertEquals(0, m.getWeeks()); assertEquals(0, m.getDays()); assertEquals(0, m.getHours()); assertEquals(0, m.getMinutes()); assertEquals(0, m.getSeconds()); assertEquals(123, m.getMillis()); } //----------------------------------------------------------------------- public void testIsReadableInterval_Object_Chronology() throws Exception { Interval i = new Interval(1234L, 5678L); assertEquals(true, ReadableIntervalConverter.INSTANCE.isReadableInterval(i, null)); } public void testSetIntoInterval_Object1() throws Exception { Interval i = new Interval(0L, 123L, CopticChronology.getInstance()); MutableInterval m = new MutableInterval(-1000L, 1000L, BuddhistChronology.getInstance()); ReadableIntervalConverter.INSTANCE.setInto(m, i, null); assertEquals(0L, m.getStartMillis()); assertEquals(123L, m.getEndMillis()); assertEquals(CopticChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object2() throws Exception { Interval i = new Interval(0L, 123L, CopticChronology.getInstance()); MutableInterval m = new MutableInterval(-1000L, 1000L, BuddhistChronology.getInstance()); ReadableIntervalConverter.INSTANCE.setInto(m, i, GJChronology.getInstance()); assertEquals(0L, m.getStartMillis()); assertEquals(123L, m.getEndMillis()); assertEquals(GJChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object3() throws Exception { MutableInterval i = new MutableInterval(0L, 123L) { public Chronology getChronology() { return null; // bad } }; MutableInterval m = new MutableInterval(-1000L, 1000L, BuddhistChronology.getInstance()); ReadableIntervalConverter.INSTANCE.setInto(m, i, GJChronology.getInstance()); assertEquals(0L, m.getStartMillis()); assertEquals(123L, m.getEndMillis()); assertEquals(GJChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object4() throws Exception { MutableInterval i = new MutableInterval(0L, 123L) { public Chronology getChronology() { return null; // bad } }; MutableInterval m = new MutableInterval(-1000L, 1000L, BuddhistChronology.getInstance()); ReadableIntervalConverter.INSTANCE.setInto(m, i, null); assertEquals(0L, m.getStartMillis()); assertEquals(123L, m.getEndMillis()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[org.joda.time.ReadableInterval]", ReadableIntervalConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestStringConverter.java0000644000175000017500000006523312116342420026235 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.MutableInterval; import org.joda.time.MutablePeriod; import org.joda.time.PeriodType; import org.joda.time.TimeOfDay; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for StringConverter. * * @author Stephen Colebourne */ public class TestStringConverter extends TestCase { private static final DateTimeZone ONE_HOUR = DateTimeZone.forOffsetHours(1); private static final DateTimeZone SIX = DateTimeZone.forOffsetHours(6); private static final DateTimeZone SEVEN = DateTimeZone.forOffsetHours(7); private static final DateTimeZone EIGHT = DateTimeZone.forOffsetHours(8); private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final Chronology ISO_EIGHT = ISOChronology.getInstance(EIGHT); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON); private static Chronology ISO; private static Chronology JULIAN; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestStringConverter.class); } public TestStringConverter(String name) { super(name); } protected void setUp() throws Exception { zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); Locale.setDefault(Locale.UK); JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); } protected void tearDown() throws Exception { DateTimeZone.setDefault(zone); Locale.setDefault(locale); zone = null; } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = StringConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(String.class, StringConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetInstantMillis_Object() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501+08:00", ISO_EIGHT)); dt = new DateTime(2004, 1, 1, 0, 0, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004T+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 1, 0, 0, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06T+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-161T+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 0, 0, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-W24-3T+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 7, 0, 0, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-W24T+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 12, 0, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 12, 24, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 12, 24, 48, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 12, 30, 0, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12.5+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 12, 24, 30, 0, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24.5+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 12, 24, 48, 500, EIGHT); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.5+08:00", ISO_EIGHT)); dt = new DateTime(2004, 6, 9, 12, 24, 48, 501); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501", ISO)); } public void testGetInstantMillis_Object_Zone() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, PARIS); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501+02:00", ISO_PARIS)); dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, PARIS); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501", ISO_PARIS)); dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, LONDON); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501+01:00", ISO_LONDON)); dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, LONDON); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501", ISO_LONDON)); } public void testGetInstantMillis_Object_Chronology() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 12, 24, 48, 501, JulianChronology.getInstance(LONDON)); assertEquals(dt.getMillis(), StringConverter.INSTANCE.getInstantMillis("2004-06-09T12:24:48.501+01:00", JULIAN)); } public void testGetInstantMillisInvalid() { try { StringConverter.INSTANCE.getInstantMillis("", (Chronology) null); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getInstantMillis("X", (Chronology) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testGetChronology_Object_Zone() throws Exception { assertEquals(ISOChronology.getInstance(PARIS), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501+01:00", PARIS)); assertEquals(ISOChronology.getInstance(PARIS), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501", PARIS)); assertEquals(ISOChronology.getInstance(LONDON), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501+01:00", (DateTimeZone) null)); assertEquals(ISOChronology.getInstance(LONDON), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501", (DateTimeZone) null)); } public void testGetChronology_Object_Chronology() throws Exception { assertEquals(JulianChronology.getInstance(LONDON), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501+01:00", JULIAN)); assertEquals(JulianChronology.getInstance(LONDON), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501", JULIAN)); assertEquals(ISOChronology.getInstance(LONDON), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501+01:00", (Chronology) null)); assertEquals(ISOChronology.getInstance(LONDON), StringConverter.INSTANCE.getChronology("2004-06-09T12:24:48.501", (Chronology) null)); } //----------------------------------------------------------------------- public void testGetPartialValues() throws Exception { TimeOfDay tod = new TimeOfDay(); int[] expected = new int[] {3, 4, 5, 6}; int[] actual = StringConverter.INSTANCE.getPartialValues(tod, "T03:04:05.006", ISOChronology.getInstance()); assertEquals(true, Arrays.equals(expected, actual)); } //----------------------------------------------------------------------- public void testGetDateTime() throws Exception { DateTime base = new DateTime(2004, 6, 9, 12, 24, 48, 501, PARIS); DateTime test = new DateTime(base.toString(), PARIS); assertEquals(base, test); } public void testGetDateTime1() throws Exception { DateTime test = new DateTime("2004-06-09T12:24:48.501+01:00"); assertEquals(2004, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); assertEquals(LONDON, test.getZone()); } public void testGetDateTime2() throws Exception { DateTime test = new DateTime("2004-06-09T12:24:48.501"); assertEquals(2004, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); assertEquals(LONDON, test.getZone()); } public void testGetDateTime3() throws Exception { DateTime test = new DateTime("2004-06-09T12:24:48.501+02:00", PARIS); assertEquals(2004, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); assertEquals(PARIS, test.getZone()); } public void testGetDateTime4() throws Exception { DateTime test = new DateTime("2004-06-09T12:24:48.501", PARIS); assertEquals(2004, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); assertEquals(PARIS, test.getZone()); } public void testGetDateTime5() throws Exception { DateTime test = new DateTime("2004-06-09T12:24:48.501+02:00", JulianChronology.getInstance(PARIS)); assertEquals(2004, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); assertEquals(PARIS, test.getZone()); } public void testGetDateTime6() throws Exception { DateTime test = new DateTime("2004-06-09T12:24:48.501", JulianChronology.getInstance(PARIS)); assertEquals(2004, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); assertEquals(PARIS, test.getZone()); } //----------------------------------------------------------------------- public void testGetDurationMillis_Object1() throws Exception { long millis = StringConverter.INSTANCE.getDurationMillis("PT12.345S"); assertEquals(12345, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt12.345s"); assertEquals(12345, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt12s"); assertEquals(12000, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt12.s"); assertEquals(12000, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt-12.32s"); assertEquals(-12320, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt-0.32s"); assertEquals(-320, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt-0.0s"); assertEquals(0, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt0.0s"); assertEquals(0, millis); millis = StringConverter.INSTANCE.getDurationMillis("pt12.3456s"); assertEquals(12345, millis); } public void testGetDurationMillis_Object2() throws Exception { try { StringConverter.INSTANCE.getDurationMillis("P2Y6M9DXYZ"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("PTS"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("XT0S"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("PX0S"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("PT0X"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("PTXS"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("PT0.0.0S"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("PT0-00S"); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.getDurationMillis("PT-.001S"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testGetPeriodType_Object() throws Exception { assertEquals(PeriodType.standard(), StringConverter.INSTANCE.getPeriodType("P2Y6M9D")); } public void testSetIntoPeriod_Object1() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearMonthDayTime()); StringConverter.INSTANCE.setInto(m, "P2Y6M9DT12H24M48S", null); assertEquals(2, m.getYears()); assertEquals(6, m.getMonths()); assertEquals(9, m.getDays()); assertEquals(12, m.getHours()); assertEquals(24, m.getMinutes()); assertEquals(48, m.getSeconds()); assertEquals(0, m.getMillis()); } public void testSetIntoPeriod_Object2() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime()); StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48S", null); assertEquals(2, m.getYears()); assertEquals(4, m.getWeeks()); assertEquals(3, m.getDays()); assertEquals(12, m.getHours()); assertEquals(24, m.getMinutes()); assertEquals(48, m.getSeconds()); assertEquals(0, m.getMillis()); } public void testSetIntoPeriod_Object3() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime()); StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48.034S", null); assertEquals(2, m.getYears()); assertEquals(4, m.getWeeks()); assertEquals(3, m.getDays()); assertEquals(12, m.getHours()); assertEquals(24, m.getMinutes()); assertEquals(48, m.getSeconds()); assertEquals(34, m.getMillis()); } public void testSetIntoPeriod_Object4() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime()); StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M.056S", null); assertEquals(2, m.getYears()); assertEquals(4, m.getWeeks()); assertEquals(3, m.getDays()); assertEquals(12, m.getHours()); assertEquals(24, m.getMinutes()); assertEquals(0, m.getSeconds()); assertEquals(56, m.getMillis()); } public void testSetIntoPeriod_Object5() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime()); StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M56.S", null); assertEquals(2, m.getYears()); assertEquals(4, m.getWeeks()); assertEquals(3, m.getDays()); assertEquals(12, m.getHours()); assertEquals(24, m.getMinutes()); assertEquals(56, m.getSeconds()); assertEquals(0, m.getMillis()); } public void testSetIntoPeriod_Object6() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime()); StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M56.1234567S", null); assertEquals(2, m.getYears()); assertEquals(4, m.getWeeks()); assertEquals(3, m.getDays()); assertEquals(12, m.getHours()); assertEquals(24, m.getMinutes()); assertEquals(56, m.getSeconds()); assertEquals(123, m.getMillis()); } public void testSetIntoPeriod_Object7() throws Exception { MutablePeriod m = new MutablePeriod(1, 0, 1, 1, 1, 1, 1, 1, PeriodType.yearWeekDayTime()); StringConverter.INSTANCE.setInto(m, "P2Y4W3D", null); assertEquals(2, m.getYears()); assertEquals(4, m.getWeeks()); assertEquals(3, m.getDays()); assertEquals(0, m.getHours()); assertEquals(0, m.getMinutes()); assertEquals(0, m.getSeconds()); assertEquals(0, m.getMillis()); } public void testSetIntoPeriod_Object8() throws Exception { MutablePeriod m = new MutablePeriod(); try { StringConverter.INSTANCE.setInto(m, "", null); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.setInto(m, "PXY", null); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.setInto(m, "PT0SXY", null); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48SX", null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsReadableInterval_Object_Chronology() throws Exception { assertEquals(false, StringConverter.INSTANCE.isReadableInterval("", null)); } public void testSetIntoInterval_Object_Chronology1() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "2004-06-09/P1Y2M", null); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0), m.getStart()); assertEquals(new DateTime(2005, 8, 9, 0, 0, 0, 0), m.getEnd()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object_Chronology2() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "P1Y2M/2004-06-09", null); assertEquals(new DateTime(2003, 4, 9, 0, 0, 0, 0), m.getStart()); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0), m.getEnd()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object_Chronology3() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "2003-08-09/2004-06-09", null); assertEquals(new DateTime(2003, 8, 9, 0, 0, 0, 0), m.getStart()); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0), m.getEnd()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object_Chronology4() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "2004-06-09T+06:00/P1Y2M", null); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0, SIX).withChronology(null), m.getStart()); assertEquals(new DateTime(2005, 8, 9, 0, 0, 0, 0, SIX).withChronology(null), m.getEnd()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object_Chronology5() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "P1Y2M/2004-06-09T+06:00", null); assertEquals(new DateTime(2003, 4, 9, 0, 0, 0, 0, SIX).withChronology(null), m.getStart()); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0, SIX).withChronology(null), m.getEnd()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object_Chronology6() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "2003-08-09T+06:00/2004-06-09T+07:00", null); assertEquals(new DateTime(2003, 8, 9, 0, 0, 0, 0, SIX).withChronology(null), m.getStart()); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0, SEVEN).withChronology(null), m.getEnd()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object_Chronology7() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "2003-08-09/2004-06-09", BuddhistChronology.getInstance()); assertEquals(new DateTime(2003, 8, 9, 0, 0, 0, 0, BuddhistChronology.getInstance()), m.getStart()); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0, BuddhistChronology.getInstance()), m.getEnd()); assertEquals(BuddhistChronology.getInstance(), m.getChronology()); } public void testSetIntoInterval_Object_Chronology8() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); StringConverter.INSTANCE.setInto(m, "2003-08-09T+06:00/2004-06-09T+07:00", BuddhistChronology.getInstance(EIGHT)); assertEquals(new DateTime(2003, 8, 9, 0, 0, 0, 0, BuddhistChronology.getInstance(SIX)).withZone(EIGHT), m.getStart()); assertEquals(new DateTime(2004, 6, 9, 0, 0, 0, 0, BuddhistChronology.getInstance(SEVEN)).withZone(EIGHT), m.getEnd()); assertEquals(BuddhistChronology.getInstance(EIGHT), m.getChronology()); } public void testSetIntoIntervalEx_Object_Chronology1() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); try { StringConverter.INSTANCE.setInto(m, "", null); fail(); } catch (IllegalArgumentException ex) {} } public void testSetIntoIntervalEx_Object_Chronology2() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); try { StringConverter.INSTANCE.setInto(m, "/", null); fail(); } catch (IllegalArgumentException ex) {} } public void testSetIntoIntervalEx_Object_Chronology3() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); try { StringConverter.INSTANCE.setInto(m, "P1Y/", null); fail(); } catch (IllegalArgumentException ex) {} } public void testSetIntoIntervalEx_Object_Chronology4() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); try { StringConverter.INSTANCE.setInto(m, "/P1Y", null); fail(); } catch (IllegalArgumentException ex) {} } public void testSetIntoIntervalEx_Object_Chronology5() throws Exception { MutableInterval m = new MutableInterval(-1000L, 1000L); try { StringConverter.INSTANCE.setInto(m, "P1Y/P2Y", null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[java.lang.String]", StringConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestReadableInstantConverter.java0000644000175000017500000001525511564251364030042 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Instant; import org.joda.time.MutableDateTime; import org.joda.time.ReadableInstant; import org.joda.time.TimeOfDay; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for ReadableInstantConverter. * * @author Stephen Colebourne */ public class TestReadableInstantConverter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology JULIAN; private static Chronology ISO; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestReadableInstantConverter.class); } public TestReadableInstantConverter(String name) { super(name); } protected void setUp() throws Exception { JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadableInstantConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(ReadableInstant.class, ReadableInstantConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetInstantMillis_Object_Chronology() throws Exception { assertEquals(123L, ReadableInstantConverter.INSTANCE.getInstantMillis(new Instant(123L), JULIAN)); assertEquals(123L, ReadableInstantConverter.INSTANCE.getInstantMillis(new DateTime(123L), JULIAN)); assertEquals(123L, ReadableInstantConverter.INSTANCE.getInstantMillis(new Instant(123L), (Chronology) null)); assertEquals(123L, ReadableInstantConverter.INSTANCE.getInstantMillis(new DateTime(123L), (Chronology) null)); } //----------------------------------------------------------------------- public void testGetChronology_Object_Zone() throws Exception { assertEquals(ISO_PARIS, ReadableInstantConverter.INSTANCE.getChronology(new Instant(123L), PARIS)); assertEquals(ISO_PARIS, ReadableInstantConverter.INSTANCE.getChronology(new DateTime(123L), PARIS)); assertEquals(ISO, ReadableInstantConverter.INSTANCE.getChronology(new Instant(123L), DateTimeZone.getDefault())); assertEquals(ISO, ReadableInstantConverter.INSTANCE.getChronology(new DateTime(123L), DateTimeZone.getDefault())); assertEquals(ISO, ReadableInstantConverter.INSTANCE.getChronology(new Instant(123L), (DateTimeZone) null)); assertEquals(ISO, ReadableInstantConverter.INSTANCE.getChronology(new DateTime(123L), (DateTimeZone) null)); assertEquals(ISO_PARIS, ReadableInstantConverter.INSTANCE.getChronology(new DateTime(123L, new MockBadChronology()), PARIS)); MutableDateTime mdt = new MutableDateTime() { public Chronology getChronology() { return null; // bad } }; assertEquals(ISO_PARIS, ReadableInstantConverter.INSTANCE.getChronology(mdt, PARIS)); } public void testGetChronology_Object_nullChronology() throws Exception { assertEquals(ISO.withUTC(), ReadableInstantConverter.INSTANCE.getChronology(new Instant(123L), (Chronology) null)); assertEquals(ISO, ReadableInstantConverter.INSTANCE.getChronology(new DateTime(123L), (Chronology) null)); MutableDateTime mdt = new MutableDateTime() { public Chronology getChronology() { return null; // bad } }; assertEquals(ISO, ReadableInstantConverter.INSTANCE.getChronology(mdt, (Chronology) null)); } public void testGetChronology_Object_Chronology() throws Exception { assertEquals(JULIAN, ReadableInstantConverter.INSTANCE.getChronology(new Instant(123L), JULIAN)); assertEquals(JULIAN, ReadableInstantConverter.INSTANCE.getChronology(new DateTime(123L), JULIAN)); } //----------------------------------------------------------------------- public void testGetPartialValues() throws Exception { TimeOfDay tod = new TimeOfDay(); int[] expected = ISOChronology.getInstance().get(tod, 12345678L); int[] actual = ReadableInstantConverter.INSTANCE.getPartialValues(tod, new Instant(12345678L), ISOChronology.getInstance()); assertEquals(true, Arrays.equals(expected, actual)); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[org.joda.time.ReadableInstant]", ReadableInstantConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/MockUnknownCalendar.java0000644000175000017500000000325611564251364026153 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.util.Calendar; import java.util.TimeZone; /** * A basic mock testing class for an unknown calendar. * * @author Stephen Colebourne */ class MockUnknownCalendar extends Calendar { private long millis; private TimeZone zone; MockUnknownCalendar(long millis) { this.millis = millis; } MockUnknownCalendar(TimeZone zone) { this.zone = zone; } public long getTimeInMillis() { return millis; } public TimeZone getTimeZone() { return zone; } protected void computeTime() { } protected void computeFields() { } public void add(int field, int amount) { } public void roll(int field, boolean up) { } public int getMinimum(int field) { return 0; } public int getMaximum(int field) { return 0; } public int getGreatestMinimum(int field) { return 0; } public int getLeastMaximum(int field) { return 0; } } joda-time-2.3/src/test/java/org/joda/time/convert/TestAll.java0000644000175000017500000000372411564251364023620 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all tests in this package. * * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestConverterManager.suite()); suite.addTest(TestConverterSet.suite()); suite.addTest(TestCalendarConverter.suite()); suite.addTest(TestDateConverter.suite()); suite.addTest(TestLongConverter.suite()); suite.addTest(TestNullConverter.suite()); suite.addTest(TestReadableDurationConverter.suite()); suite.addTest(TestReadableIntervalConverter.suite()); suite.addTest(TestReadableInstantConverter.suite()); suite.addTest(TestReadablePartialConverter.suite()); suite.addTest(TestReadablePeriodConverter.suite()); suite.addTest(TestStringConverter.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestCalendarConverter.java0000644000175000017500000002052711564251364026511 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.TimeOfDay; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for CalendarConverter. * * @author Stephen Colebourne */ public class TestCalendarConverter extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone MOSCOW = DateTimeZone.forID("Europe/Moscow"); private static Chronology JULIAN; private static Chronology ISO; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestCalendarConverter.class); } public TestCalendarConverter(String name) { super(name); } protected void setUp() throws Exception { JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = CalendarConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(Calendar.class, CalendarConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetInstantMillis_Object_Chronology() throws Exception { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(123L)); assertEquals(123L, CalendarConverter.INSTANCE.getInstantMillis(cal, JULIAN)); assertEquals(123L, cal.getTime().getTime()); } //----------------------------------------------------------------------- public void testGetChronology_Object_Zone() throws Exception { GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris")); assertEquals(GJChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(cal, MOSCOW)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(GJChronology.getInstance(), CalendarConverter.INSTANCE.getChronology(cal, (DateTimeZone) null)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(0L)); assertEquals(GJChronology.getInstance(MOSCOW, 0L, 4), CalendarConverter.INSTANCE.getChronology(cal, MOSCOW)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(Long.MAX_VALUE)); assertEquals(JulianChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(cal, PARIS)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(Long.MIN_VALUE)); assertEquals(GregorianChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(cal, PARIS)); Calendar uc = new MockUnknownCalendar(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(ISOChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(uc, PARIS)); try { Calendar bc = (Calendar) Class.forName("sun.util.BuddhistCalendar").newInstance(); bc.setTimeZone(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(BuddhistChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(bc, PARIS)); } catch (ClassNotFoundException ex) { // ignore } } public void testGetChronology_Object_nullChronology() throws Exception { GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris")); assertEquals(GJChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(0L)); assertEquals(GJChronology.getInstance(MOSCOW, 0L, 4), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(Long.MAX_VALUE)); assertEquals(JulianChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null)); cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow")); cal.setGregorianChange(new Date(Long.MIN_VALUE)); assertEquals(GregorianChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null)); cal = new GregorianCalendar(new MockUnknownTimeZone()); assertEquals(GJChronology.getInstance(), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null)); Calendar uc = new MockUnknownCalendar(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(ISOChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(uc, (Chronology) null)); try { Calendar bc = (Calendar) Class.forName("sun.util.BuddhistCalendar").newInstance(); bc.setTimeZone(TimeZone.getTimeZone("Europe/Moscow")); assertEquals(BuddhistChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(bc, (Chronology) null)); } catch (ClassNotFoundException ex) { // ignore } } public void testGetChronology_Object_Chronology() throws Exception { GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris")); assertEquals(JULIAN, CalendarConverter.INSTANCE.getChronology(cal, JULIAN)); } //----------------------------------------------------------------------- public void testGetPartialValues() throws Exception { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(12345678L)); TimeOfDay tod = new TimeOfDay(); int[] expected = ISO.get(tod, 12345678L); int[] actual = CalendarConverter.INSTANCE.getPartialValues(tod, cal, ISO); assertEquals(true, Arrays.equals(expected, actual)); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[java.util.Calendar]", CalendarConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/MockZeroNullIntegerConverter.java0000644000175000017500000000312611564251364030036 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; /** * A basic mock testing class for a converter. * This converter returns zero and null for an Integer input. * * @author Stephen Colebourne */ public class MockZeroNullIntegerConverter implements InstantConverter { public static final InstantConverter INSTANCE = new MockZeroNullIntegerConverter(); public long getInstantMillis(Object object, Chronology chrono) { return 0; } public long getInstantMillis(Object object, Chronology chrono, DateTimeFormatter parser) { return 0; } public Chronology getChronology(Object object, DateTimeZone zone) { return null; } public Chronology getChronology(Object object, Chronology chrono) { return null; } public Class getSupportedType() { return Integer.class; } } joda-time-2.3/src/test/java/org/joda/time/convert/TestDateConverter.java0000644000175000017500000001133311564251364025650 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Date; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.TimeOfDay; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for DateConverter. * * @author Stephen Colebourne */ public class TestDateConverter extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology ISO; private static Chronology JULIAN; private static Chronology COPTIC; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateConverter.class); } public TestDateConverter(String name) { super(name); } protected void setUp() throws Exception { JULIAN = JulianChronology.getInstance(); COPTIC = CopticChronology.getInstance(); ISO = ISOChronology.getInstance(); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = DateConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(Date.class, DateConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetInstantMillis_Object_Chronology() throws Exception { Date date = new Date(123L); long millis = DateConverter.INSTANCE.getInstantMillis(date, JULIAN); assertEquals(123L, millis); assertEquals(123L, DateConverter.INSTANCE.getInstantMillis(date, (Chronology) null)); } //----------------------------------------------------------------------- public void testGetChronology_Object_Zone() throws Exception { assertEquals(ISO_PARIS, DateConverter.INSTANCE.getChronology(new Date(123L), PARIS)); assertEquals(ISO, DateConverter.INSTANCE.getChronology(new Date(123L), (DateTimeZone) null)); } public void testGetChronology_Object_Chronology() throws Exception { assertEquals(JULIAN, DateConverter.INSTANCE.getChronology(new Date(123L), JULIAN)); assertEquals(ISO, DateConverter.INSTANCE.getChronology(new Date(123L), (Chronology) null)); } //----------------------------------------------------------------------- public void testGetPartialValues() throws Exception { TimeOfDay tod = new TimeOfDay(); int[] expected = COPTIC.get(tod, 12345678L); int[] actual = DateConverter.INSTANCE.getPartialValues(tod, new Date(12345678L), COPTIC); assertEquals(true, Arrays.equals(expected, actual)); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[java.util.Date]", DateConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/MockUnknownTimeZone.java0000644000175000017500000000277211564251364026176 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * A basic mock testing class for an unknown time zone. * * @author Stephen Colebourne */ class MockUnknownTimeZone extends TimeZone { MockUnknownTimeZone() { super(); } public String getID() { return "!!!"; } public String getDisplayName(boolean daylight, int style, Locale locale) { return "!!!"; } public int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds) { return 0; } public void setRawOffset(int offsetMillis) { } public int getRawOffset() { return 0; } public boolean useDaylightTime() { return false; } public boolean inDaylightTime(Date date) { return false; } } joda-time-2.3/src/test/java/org/joda/time/convert/TestConverterSet.java0000644000175000017500000001470611564251364025535 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Calendar; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.ReadWritableDateTime; import org.joda.time.ReadWritableInstant; import org.joda.time.ReadableDateTime; import org.joda.time.ReadableInstant; /** * This class is a JUnit test for ConverterSet. * Mostly for coverage. * * @author Stephen Colebourne */ public class TestConverterSet extends TestCase { private static final Converter c1 = new Converter() { public Class getSupportedType() {return Boolean.class;} }; private static final Converter c2 = new Converter() { public Class getSupportedType() {return Character.class;} }; private static final Converter c3 = new Converter() { public Class getSupportedType() {return Byte.class;} }; private static final Converter c4 = new Converter() { public Class getSupportedType() {return Short.class;} }; private static final Converter c4a = new Converter() { public Class getSupportedType() {return Short.class;} }; private static final Converter c5 = new Converter() { public Class getSupportedType() {return Integer.class;} }; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestConverterSet.class); } public TestConverterSet(String name) { super(name); } //----------------------------------------------------------------------- public void testClass() throws Exception { Class cls = ConverterSet.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; assertEquals(false, Modifier.isPublic(con.getModifiers())); assertEquals(false, Modifier.isProtected(con.getModifiers())); assertEquals(false, Modifier.isPrivate(con.getModifiers())); } //----------------------------------------------------------------------- public void testBigHashtable() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); set.select(Boolean.class); set.select(Character.class); set.select(Byte.class); set.select(Short.class); set.select(Integer.class); set.select(Long.class); set.select(Float.class); set.select(Double.class); set.select(null); set.select(Calendar.class); set.select(GregorianCalendar.class); set.select(DateTime.class); set.select(DateMidnight.class); set.select(ReadableInstant.class); set.select(ReadableDateTime.class); set.select(ReadWritableInstant.class); // 16 set.select(ReadWritableDateTime.class); set.select(DateTime.class); assertEquals(4, set.size()); } //----------------------------------------------------------------------- public void testAddNullRemoved1() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); ConverterSet result = set.add(c5, null); assertEquals(4, set.size()); assertEquals(5, result.size()); } public void testAddNullRemoved2() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); ConverterSet result = set.add(c4, null); assertSame(set, result); } public void testAddNullRemoved3() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); ConverterSet result = set.add(c4a, null); assertTrue(set != result); assertEquals(4, set.size()); assertEquals(4, result.size()); } //----------------------------------------------------------------------- public void testRemoveNullRemoved1() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); ConverterSet result = set.remove(c3, null); assertEquals(4, set.size()); assertEquals(3, result.size()); } public void testRemoveNullRemoved2() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); ConverterSet result = set.remove(c5, null); assertSame(set, result); } //----------------------------------------------------------------------- public void testRemoveBadIndex1() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); try { set.remove(200, null); fail(); } catch (IndexOutOfBoundsException ex) {} assertEquals(4, set.size()); } public void testRemoveBadIndex2() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); try { set.remove(-1, null); fail(); } catch (IndexOutOfBoundsException ex) {} assertEquals(4, set.size()); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestReadableDurationConverter.java0000644000175000017500000001165411747474271030215 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.joda.time.PeriodType; import org.joda.time.MutablePeriod; import org.joda.time.ReadableDuration; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for ReadableDurationConverter. * * @author Stephen Colebourne */ public class TestReadableDurationConverter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology JULIAN; private static Chronology ISO; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestReadableDurationConverter.class); } public TestReadableDurationConverter(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(PARIS); } @Override protected void tearDown() throws Exception { super.tearDown(); DateTimeZone.setDefault(zone); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadableDurationConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(ReadableDuration.class, ReadableDurationConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetDurationMillis_Object() throws Exception { assertEquals(123L, ReadableDurationConverter.INSTANCE.getDurationMillis(new Duration(123L))); } //----------------------------------------------------------------------- public void testGetPeriodType_Object() throws Exception { assertEquals(PeriodType.standard(), ReadableDurationConverter.INSTANCE.getPeriodType(new Duration(123L))); } public void testSetInto_Object() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearMonthDayTime()); ReadableDurationConverter.INSTANCE.setInto(m, new Duration( 3L * DateTimeConstants.MILLIS_PER_DAY + 4L * DateTimeConstants.MILLIS_PER_MINUTE + 5L ), null); assertEquals(0, m.getYears()); assertEquals(0, m.getMonths()); assertEquals(0, m.getWeeks()); assertEquals(0, m.getDays()); assertEquals(3 * 24, m.getHours()); assertEquals(4, m.getMinutes()); assertEquals(0, m.getSeconds()); assertEquals(5, m.getMillis()); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[org.joda.time.ReadableDuration]", ReadableDurationConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/MockBadChronology.java0000644000175000017500000000240211564251364025604 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.chrono.BaseChronology; /** * A basic mock testing class for an unknown calendar. * * @author Stephen Colebourne */ class MockBadChronology extends BaseChronology { MockBadChronology() { super(); } public Chronology withZone(DateTimeZone zone) { return null; } public DateTimeZone getZone() { return null; } public Chronology withUTC() { return null; } public String toString() { return null; } } joda-time-2.3/src/test/java/org/joda/time/convert/TestLongConverter.java0000644000175000017500000001161711564251364025677 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.TimeOfDay; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for LongConverter. * * @author Stephen Colebourne */ public class TestLongConverter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology JULIAN; private static Chronology ISO; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLongConverter.class); } public TestLongConverter(String name) { super(name); } protected void setUp() throws Exception { JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = LongConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(Long.class, LongConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetInstantMillis_Object_Chronology() throws Exception { assertEquals(123L, LongConverter.INSTANCE.getInstantMillis(new Long(123L), JULIAN)); assertEquals(123L, LongConverter.INSTANCE.getInstantMillis(new Long(123L), (Chronology) null)); } //----------------------------------------------------------------------- public void testGetChronology_Object_Zone() throws Exception { assertEquals(ISO_PARIS, LongConverter.INSTANCE.getChronology(new Long(123L), PARIS)); assertEquals(ISO, LongConverter.INSTANCE.getChronology(new Long(123L), (DateTimeZone) null)); } public void testGetChronology_Object_Chronology() throws Exception { assertEquals(JULIAN, LongConverter.INSTANCE.getChronology(new Long(123L), JULIAN)); assertEquals(ISO, LongConverter.INSTANCE.getChronology(new Long(123L), (Chronology) null)); } //----------------------------------------------------------------------- public void testGetPartialValues() throws Exception { TimeOfDay tod = new TimeOfDay(); int[] expected = ISOChronology.getInstance().get(tod, 12345678L); int[] actual = LongConverter.INSTANCE.getPartialValues(tod, new Long(12345678L), ISOChronology.getInstance()); assertEquals(true, Arrays.equals(expected, actual)); } //----------------------------------------------------------------------- public void testGetDurationMillis_Object() throws Exception { assertEquals(123L, LongConverter.INSTANCE.getDurationMillis(new Long(123L))); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[java.lang.Long]", LongConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestConverterManager.java0000644000175000017500000013271611564251364026356 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.joda.time.ReadablePartial; import org.joda.time.ReadablePeriod; import org.joda.time.Period; import org.joda.time.PeriodType; import org.joda.time.Interval; import org.joda.time.JodaTimePermission; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadWritableInterval; import org.joda.time.ReadableDateTime; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; import org.joda.time.ReadableInterval; import org.joda.time.TimeOfDay; import org.joda.time.format.DateTimeFormatter; /** * This class is a JUnit test for ConverterManager. * * @author Stephen Colebourne */ public class TestConverterManager extends TestCase { private static final boolean OLD_JDK; static { String str = System.getProperty("java.version"); boolean old = true; if (str.length() > 3 && str.charAt(0) == '1' && str.charAt(1) == '.' && (str.charAt(2) == '4' || str.charAt(2) == '5' || str.charAt(2) == '6')) { old = false; } OLD_JDK = old; } private static final Policy RESTRICT; private static final Policy ALLOW; static { // don't call Policy.getPolicy() RESTRICT = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } public boolean implies(ProtectionDomain domain, Permission permission) { if (permission instanceof JodaTimePermission) { return false; } return true; // return super.implies(domain, permission); } }; ALLOW = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } }; } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestConverterManager.class); } public TestConverterManager(String name) { super(name); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ConverterManager.class; assertEquals(true, Modifier.isPublic(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(true, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testGetInstantConverter() { InstantConverter c = ConverterManager.getInstance().getInstantConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new DateTime()); assertEquals(ReadableInstant.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new Date()); assertEquals(Date.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new GregorianCalendar()); assertEquals(Calendar.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getInstantConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetInstantConverterRemovedNull() { try { ConverterManager.getInstance().removeInstantConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getInstantConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addInstantConverter(NullConverter.INSTANCE); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testGetInstantConverterOKMultipleMatches() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return ReadableDateTime.class;} }; try { ConverterManager.getInstance().addInstantConverter(c); InstantConverter ok = ConverterManager.getInstance().getInstantConverter(new DateTime()); // ReadableDateTime and ReadableInstant both match, but RI discarded as less specific assertEquals(ReadableDateTime.class, ok.getSupportedType()); } finally { ConverterManager.getInstance().removeInstantConverter(c); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testGetInstantConverterBadMultipleMatches() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Serializable.class;} }; try { ConverterManager.getInstance().addInstantConverter(c); try { ConverterManager.getInstance().getInstantConverter(new DateTime()); fail(); } catch (IllegalStateException ex) { // Serializable and ReadableInstant both match, so cannot pick } } finally { ConverterManager.getInstance().removeInstantConverter(c); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } //----------------------------------------------------------------------- public void testGetInstantConverters() { InstantConverter[] array = ConverterManager.getInstance().getInstantConverters(); assertEquals(6, array.length); } //----------------------------------------------------------------------- public void testAddInstantConverter1() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; try { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getInstantConverter(Boolean.TRUE).getSupportedType()); assertEquals(7, ConverterManager.getInstance().getInstantConverters().length); } finally { ConverterManager.getInstance().removeInstantConverter(c); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverter2() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return String.class;} }; try { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getInstantConverter("").getSupportedType()); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } finally { ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverter3() { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverter4() { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(null); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } //----------------------------------------------------------------------- public void testRemoveInstantConverter1() { try { InstantConverter removed = ConverterManager.getInstance().removeInstantConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(5, ConverterManager.getInstance().getInstantConverters().length); } finally { ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testRemoveInstantConverter2() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; InstantConverter removed = ConverterManager.getInstance().removeInstantConverter(c); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testRemoveInstantConverter3() { InstantConverter removed = ConverterManager.getInstance().removeInstantConverter(null); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testRemoveInstantConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeInstantConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static final int PARTIAL_SIZE = 7; public void testGetPartialConverter() { PartialConverter c = ConverterManager.getInstance().getPartialConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new TimeOfDay()); assertEquals(ReadablePartial.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new DateTime()); assertEquals(ReadableInstant.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new Date()); assertEquals(Date.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new GregorianCalendar()); assertEquals(Calendar.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getPartialConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetPartialConverterRemovedNull() { try { ConverterManager.getInstance().removePartialConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getPartialConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addPartialConverter(NullConverter.INSTANCE); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testGetPartialConverterOKMultipleMatches() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return ReadableDateTime.class;} }; try { ConverterManager.getInstance().addPartialConverter(c); PartialConverter ok = ConverterManager.getInstance().getPartialConverter(new DateTime()); // ReadableDateTime and ReadablePartial both match, but RI discarded as less specific assertEquals(ReadableDateTime.class, ok.getSupportedType()); } finally { ConverterManager.getInstance().removePartialConverter(c); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testGetPartialConverterBadMultipleMatches() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Serializable.class;} }; try { ConverterManager.getInstance().addPartialConverter(c); try { ConverterManager.getInstance().getPartialConverter(new DateTime()); fail(); } catch (IllegalStateException ex) { // Serializable and ReadablePartial both match, so cannot pick } } finally { ConverterManager.getInstance().removePartialConverter(c); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } //----------------------------------------------------------------------- public void testGetPartialConverters() { PartialConverter[] array = ConverterManager.getInstance().getPartialConverters(); assertEquals(PARTIAL_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddPartialConverter1() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; try { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getPartialConverter(Boolean.TRUE).getSupportedType()); assertEquals(PARTIAL_SIZE + 1, ConverterManager.getInstance().getPartialConverters().length); } finally { ConverterManager.getInstance().removePartialConverter(c); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverter2() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return String.class;} }; try { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getPartialConverter("").getSupportedType()); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } finally { ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverter3() { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverter4() { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(null); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } //----------------------------------------------------------------------- public void testRemovePartialConverter1() { try { PartialConverter removed = ConverterManager.getInstance().removePartialConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(PARTIAL_SIZE - 1, ConverterManager.getInstance().getPartialConverters().length); } finally { ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testRemovePartialConverter2() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; PartialConverter removed = ConverterManager.getInstance().removePartialConverter(c); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testRemovePartialConverter3() { PartialConverter removed = ConverterManager.getInstance().removePartialConverter(null); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testRemovePartialConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeInstantConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static int DURATION_SIZE = 5; public void testGetDurationConverter() { DurationConverter c = ConverterManager.getInstance().getDurationConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(new Duration(123L)); assertEquals(ReadableDuration.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getDurationConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetDurationConverterRemovedNull() { try { ConverterManager.getInstance().removeDurationConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getDurationConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addDurationConverter(NullConverter.INSTANCE); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } //----------------------------------------------------------------------- public void testGetDurationConverters() { DurationConverter[] array = ConverterManager.getInstance().getDurationConverters(); assertEquals(DURATION_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddDurationConverter1() { DurationConverter c = new DurationConverter() { public long getDurationMillis(Object object) {return 0;} public Class getSupportedType() {return Boolean.class;} }; try { DurationConverter removed = ConverterManager.getInstance().addDurationConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getDurationConverter(Boolean.TRUE).getSupportedType()); assertEquals(DURATION_SIZE + 1, ConverterManager.getInstance().getDurationConverters().length); } finally { ConverterManager.getInstance().removeDurationConverter(c); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testAddDurationConverter2() { DurationConverter c = new DurationConverter() { public long getDurationMillis(Object object) {return 0;} public Class getSupportedType() {return String.class;} }; try { DurationConverter removed = ConverterManager.getInstance().addDurationConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getDurationConverter("").getSupportedType()); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } finally { ConverterManager.getInstance().addDurationConverter(StringConverter.INSTANCE); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testAddDurationConverter3() { DurationConverter removed = ConverterManager.getInstance().addDurationConverter(null); assertEquals(null, removed); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testAddDurationConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addDurationConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } //----------------------------------------------------------------------- public void testRemoveDurationConverter1() { try { DurationConverter removed = ConverterManager.getInstance().removeDurationConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(DURATION_SIZE - 1, ConverterManager.getInstance().getDurationConverters().length); } finally { ConverterManager.getInstance().addDurationConverter(StringConverter.INSTANCE); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testRemoveDurationConverter2() { DurationConverter c = new DurationConverter() { public long getDurationMillis(Object object) {return 0;} public Class getSupportedType() {return Boolean.class;} }; DurationConverter removed = ConverterManager.getInstance().removeDurationConverter(c); assertEquals(null, removed); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testRemoveDurationConverter3() { DurationConverter removed = ConverterManager.getInstance().removeDurationConverter(null); assertEquals(null, removed); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testRemoveDurationConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeDurationConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static int PERIOD_SIZE = 5; public void testGetPeriodConverter() { PeriodConverter c = ConverterManager.getInstance().getPeriodConverter(new Period(1, 2, 3, 4, 5, 6, 7, 8)); assertEquals(ReadablePeriod.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(new Duration(123L)); assertEquals(ReadableDuration.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getPeriodConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetPeriodConverterRemovedNull() { try { ConverterManager.getInstance().removePeriodConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getPeriodConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addPeriodConverter(NullConverter.INSTANCE); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } //----------------------------------------------------------------------- public void testGetPeriodConverters() { PeriodConverter[] array = ConverterManager.getInstance().getPeriodConverters(); assertEquals(PERIOD_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddPeriodConverter1() { PeriodConverter c = new PeriodConverter() { public void setInto(ReadWritablePeriod duration, Object object, Chronology c) {} public PeriodType getPeriodType(Object object) {return null;} public Class getSupportedType() {return Boolean.class;} }; try { PeriodConverter removed = ConverterManager.getInstance().addPeriodConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getPeriodConverter(Boolean.TRUE).getSupportedType()); assertEquals(PERIOD_SIZE + 1, ConverterManager.getInstance().getPeriodConverters().length); } finally { ConverterManager.getInstance().removePeriodConverter(c); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testAddPeriodConverter2() { PeriodConverter c = new PeriodConverter() { public void setInto(ReadWritablePeriod duration, Object object, Chronology c) {} public PeriodType getPeriodType(Object object) {return null;} public Class getSupportedType() {return String.class;} }; try { PeriodConverter removed = ConverterManager.getInstance().addPeriodConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getPeriodConverter("").getSupportedType()); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } finally { ConverterManager.getInstance().addPeriodConverter(StringConverter.INSTANCE); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testAddPeriodConverter3() { PeriodConverter removed = ConverterManager.getInstance().addPeriodConverter(null); assertEquals(null, removed); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testAddPeriodConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addPeriodConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } //----------------------------------------------------------------------- public void testRemovePeriodConverter1() { try { PeriodConverter removed = ConverterManager.getInstance().removePeriodConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(PERIOD_SIZE - 1, ConverterManager.getInstance().getPeriodConverters().length); } finally { ConverterManager.getInstance().addPeriodConverter(StringConverter.INSTANCE); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testRemovePeriodConverter2() { PeriodConverter c = new PeriodConverter() { public void setInto(ReadWritablePeriod duration, Object object, Chronology c) {} public PeriodType getPeriodType(Object object) {return null;} public Class getSupportedType() {return Boolean.class;} }; PeriodConverter removed = ConverterManager.getInstance().removePeriodConverter(c); assertEquals(null, removed); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testRemovePeriodConverter3() { PeriodConverter removed = ConverterManager.getInstance().removePeriodConverter(null); assertEquals(null, removed); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testRemovePeriodConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removePeriodConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static int INTERVAL_SIZE = 3; public void testGetIntervalConverter() { IntervalConverter c = ConverterManager.getInstance().getIntervalConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getIntervalConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getIntervalConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getIntervalConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} try { ConverterManager.getInstance().getIntervalConverter(new Long(0)); fail(); } catch (IllegalArgumentException ex) {} } public void testGetIntervalConverterRemovedNull() { try { ConverterManager.getInstance().removeIntervalConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getIntervalConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addIntervalConverter(NullConverter.INSTANCE); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } //----------------------------------------------------------------------- public void testGetIntervalConverters() { IntervalConverter[] array = ConverterManager.getInstance().getIntervalConverters(); assertEquals(INTERVAL_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddIntervalConverter1() { IntervalConverter c = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) {return false;} public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) {} public Class getSupportedType() {return Boolean.class;} }; try { IntervalConverter removed = ConverterManager.getInstance().addIntervalConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getIntervalConverter(Boolean.TRUE).getSupportedType()); assertEquals(INTERVAL_SIZE + 1, ConverterManager.getInstance().getIntervalConverters().length); } finally { ConverterManager.getInstance().removeIntervalConverter(c); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testAddIntervalConverter2() { IntervalConverter c = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) {return false;} public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) {} public Class getSupportedType() {return String.class;} }; try { IntervalConverter removed = ConverterManager.getInstance().addIntervalConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getIntervalConverter("").getSupportedType()); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } finally { ConverterManager.getInstance().addIntervalConverter(StringConverter.INSTANCE); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testAddIntervalConverter3() { IntervalConverter removed = ConverterManager.getInstance().addIntervalConverter(null); assertEquals(null, removed); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testAddIntervalConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addIntervalConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } //----------------------------------------------------------------------- public void testRemoveIntervalConverter1() { try { IntervalConverter removed = ConverterManager.getInstance().removeIntervalConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(INTERVAL_SIZE - 1, ConverterManager.getInstance().getIntervalConverters().length); } finally { ConverterManager.getInstance().addIntervalConverter(StringConverter.INSTANCE); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testRemoveIntervalConverter2() { IntervalConverter c = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) {return false;} public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) {} public Class getSupportedType() {return Boolean.class;} }; IntervalConverter removed = ConverterManager.getInstance().removeIntervalConverter(c); assertEquals(null, removed); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testRemoveIntervalConverter3() { IntervalConverter removed = ConverterManager.getInstance().removeIntervalConverter(null); assertEquals(null, removed); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testRemoveIntervalConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeIntervalConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } //----------------------------------------------------------------------- public void testToString() { assertEquals("ConverterManager[6 instant,7 partial,5 duration,5 period,3 interval]", ConverterManager.getInstance().toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestReadablePeriodConverter.java0000644000175000017500000001065511564251364027643 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.PeriodType; import org.joda.time.MutablePeriod; import org.joda.time.ReadablePeriod; import org.joda.time.Period; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for ReadablePeriodConverter. * * @author Stephen Colebourne */ public class TestReadablePeriodConverter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology JULIAN; private static Chronology ISO; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestReadablePeriodConverter.class); } public TestReadablePeriodConverter(String name) { super(name); } protected void setUp() throws Exception { JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadablePeriodConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(ReadablePeriod.class, ReadablePeriodConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetPeriodType_Object() throws Exception { assertEquals(PeriodType.standard(), ReadablePeriodConverter.INSTANCE.getPeriodType(new Period(123L, PeriodType.standard()))); assertEquals(PeriodType.yearMonthDayTime(), ReadablePeriodConverter.INSTANCE.getPeriodType(new Period(123L, PeriodType.yearMonthDayTime()))); } public void testSetInto_Object() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.yearMonthDayTime()); ReadablePeriodConverter.INSTANCE.setInto(m, new Period(0, 0, 0, 3, 0, 4, 0, 5), null); assertEquals(0, m.getYears()); assertEquals(0, m.getMonths()); assertEquals(0, m.getWeeks()); assertEquals(3, m.getDays()); assertEquals(0, m.getHours()); assertEquals(4, m.getMinutes()); assertEquals(0, m.getSeconds()); assertEquals(5, m.getMillis()); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[org.joda.time.ReadablePeriod]", ReadablePeriodConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestNullConverter.java0000644000175000017500000001754011564251364025713 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.MutableInterval; import org.joda.time.MutablePeriod; import org.joda.time.PeriodType; import org.joda.time.TimeOfDay; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for NullConverter. * * @author Stephen Colebourne */ public class TestNullConverter extends TestCase { private long TEST_TIME_NOW = 20 * DateTimeConstants.MILLIS_PER_DAY + 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology ISO; private static Chronology JULIAN; private DateTimeZone zone = null; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestNullConverter.class); } public TestNullConverter(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(DateTimeZone.forID("Europe/London")); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); ISO = ISOChronology.getInstance(); JULIAN = JulianChronology.getInstance(); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = NullConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(null, NullConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetInstantMillis_Object_Chronology() throws Exception { assertEquals(TEST_TIME_NOW, NullConverter.INSTANCE.getInstantMillis(null, JULIAN)); assertEquals(TEST_TIME_NOW, NullConverter.INSTANCE.getInstantMillis(null, (Chronology) null)); } //----------------------------------------------------------------------- public void testGetChronology_Object_Zone() throws Exception { assertEquals(ISO_PARIS, NullConverter.INSTANCE.getChronology(null, PARIS)); assertEquals(ISO, NullConverter.INSTANCE.getChronology(null, (DateTimeZone) null)); } public void testGetChronology_Object_Chronology() throws Exception { assertEquals(JULIAN, NullConverter.INSTANCE.getChronology(null, JULIAN)); assertEquals(ISO, NullConverter.INSTANCE.getChronology(null, (Chronology) null)); } //----------------------------------------------------------------------- public void testGetPartialValues() throws Exception { TimeOfDay tod = new TimeOfDay(); int[] expected = new int[] {10 + 1, 20, 30, 40}; // now int[] actual = NullConverter.INSTANCE.getPartialValues(tod, null, ISOChronology.getInstance()); assertEquals(true, Arrays.equals(expected, actual)); } //----------------------------------------------------------------------- public void testGetDurationMillis_Object() throws Exception { assertEquals(0L, NullConverter.INSTANCE.getDurationMillis(null)); } //----------------------------------------------------------------------- public void testGetPeriodType_Object() throws Exception { assertEquals(PeriodType.standard(), NullConverter.INSTANCE.getPeriodType(null)); } public void testSetInto_Object() throws Exception { MutablePeriod m = new MutablePeriod(PeriodType.millis()); NullConverter.INSTANCE.setInto(m, null, null); assertEquals(0L, m.getMillis()); } //----------------------------------------------------------------------- public void testIsReadableInterval_Object_Chronology() throws Exception { assertEquals(false, NullConverter.INSTANCE.isReadableInterval(null, null)); } public void testSetInto_Object_Chronology1() throws Exception { MutableInterval m = new MutableInterval(1000L, 2000L, GJChronology.getInstance()); NullConverter.INSTANCE.setInto(m, null, null); assertEquals(TEST_TIME_NOW, m.getStartMillis()); assertEquals(TEST_TIME_NOW, m.getEndMillis()); assertEquals(ISOChronology.getInstance(), m.getChronology()); } public void testSetInto_Object_Chronology2() throws Exception { MutableInterval m = new MutableInterval(1000L, 2000L, GJChronology.getInstance()); NullConverter.INSTANCE.setInto(m, null, CopticChronology.getInstance()); assertEquals(TEST_TIME_NOW, m.getStartMillis()); assertEquals(TEST_TIME_NOW, m.getEndMillis()); assertEquals(CopticChronology.getInstance(), m.getChronology()); } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[null]", NullConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/convert/TestReadablePartialConverter.java0000644000175000017500000001365111564251364030014 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.ReadablePartial; import org.joda.time.TimeOfDay; import org.joda.time.YearMonthDay; import org.joda.time.base.BasePartial; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * This class is a Junit unit test for ReadablePartialConverter. * * @author Stephen Colebourne */ public class TestReadablePartialConverter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static Chronology JULIAN; private static Chronology ISO; private static Chronology BUDDHIST; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestReadablePartialConverter.class); } public TestReadablePartialConverter(String name) { super(name); } protected void setUp() throws Exception { JULIAN = JulianChronology.getInstance(); ISO = ISOChronology.getInstance(); BUDDHIST = BuddhistChronology.getInstance(); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ReadablePartialConverter.class; assertEquals(false, Modifier.isPublic(cls.getModifiers())); assertEquals(false, Modifier.isProtected(cls.getModifiers())); assertEquals(false, Modifier.isPrivate(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(false, Modifier.isPublic(fld.getModifiers())); assertEquals(false, Modifier.isProtected(fld.getModifiers())); assertEquals(false, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testSupportedType() throws Exception { assertEquals(ReadablePartial.class, ReadablePartialConverter.INSTANCE.getSupportedType()); } //----------------------------------------------------------------------- public void testGetChronology_Object_Zone() throws Exception { assertEquals(ISO_PARIS, ReadablePartialConverter.INSTANCE.getChronology(new TimeOfDay(123L), PARIS)); assertEquals(ISO, ReadablePartialConverter.INSTANCE.getChronology(new TimeOfDay(123L), DateTimeZone.getDefault())); assertEquals(ISO, ReadablePartialConverter.INSTANCE.getChronology(new TimeOfDay(123L), (DateTimeZone) null)); } public void testGetChronology_Object_Chronology() throws Exception { assertEquals(JULIAN, ReadablePartialConverter.INSTANCE.getChronology(new TimeOfDay(123L, BUDDHIST), JULIAN)); assertEquals(JULIAN, ReadablePartialConverter.INSTANCE.getChronology(new TimeOfDay(123L), JULIAN)); assertEquals(BUDDHIST.withUTC(), ReadablePartialConverter.INSTANCE.getChronology(new TimeOfDay(123L, BUDDHIST), (Chronology) null)); } //----------------------------------------------------------------------- public void testGetPartialValues() throws Exception { TimeOfDay tod = new TimeOfDay(); int[] expected = new int[] {1, 2, 3, 4}; int[] actual = ReadablePartialConverter.INSTANCE.getPartialValues(tod, new TimeOfDay(1, 2, 3, 4), ISOChronology.getInstance(PARIS)); assertEquals(true, Arrays.equals(expected, actual)); try { ReadablePartialConverter.INSTANCE.getPartialValues(tod, new YearMonthDay(2005, 6, 9), JULIAN); fail(); } catch (IllegalArgumentException ex) {} try { ReadablePartialConverter.INSTANCE.getPartialValues(tod, new MockTOD(), JULIAN); fail(); } catch (IllegalArgumentException ex) {} } static class MockTOD extends BasePartial { protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case 0: return chrono.hourOfDay(); case 1: return chrono.minuteOfHour(); case 2: return chrono.year(); case 3: return chrono.era(); } return null; } public int size() { return 4; } } //----------------------------------------------------------------------- public void testToString() { assertEquals("Converter[org.joda.time.ReadablePartial]", ReadablePartialConverter.INSTANCE.toString()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutablePeriod_Constructors.java0000644000175000017500000012774611564251364026767 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a JUnit test for MutableDuration. * * @author Stephen Colebourne */ public class TestMutablePeriod_Constructors extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutablePeriod_Constructors.class); } public TestMutablePeriod_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 890), MutablePeriod.parse("P1Y2M3W4DT5H6M7.890S")); } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstructor1() throws Throwable { MutablePeriod test = new MutablePeriod(); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (PeriodType) */ public void testConstructor_PeriodType1() throws Throwable { MutablePeriod test = new MutablePeriod(PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_PeriodType2() throws Throwable { MutablePeriod test = new MutablePeriod((PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long2() throws Throwable { long length = 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long3() throws Throwable { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; MutablePeriod test = new MutablePeriod(length); assertEquals(PeriodType.standard(), test.getPeriodType()); // only time fields are precise in AllType assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_PeriodType1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, (PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType2() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, PeriodType.millis()); assertEquals(PeriodType.millis(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(length, test.getMillis()); } public void testConstructor_long_PeriodType3() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, PeriodType.standard()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType4() throws Throwable { long length = 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, PeriodType.standard().withMillisRemoved()); assertEquals(PeriodType.standard().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_Chronology1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, ISOChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_Chronology2() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, ISOChronology.getInstanceUTC()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_Chronology3() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_PeriodType_Chronology1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, PeriodType.time().withMillisRemoved(), ISOChronology.getInstance()); assertEquals(PeriodType.time().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_long_PeriodType_Chronology2() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, PeriodType.standard(), ISOChronology.getInstanceUTC()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType_Chronology3() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, PeriodType.standard(), (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_long_PeriodType_Chronology4() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, (PeriodType) null, (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (4ints) */ public void testConstructor_4int1() throws Throwable { MutablePeriod test = new MutablePeriod(5, 6, 7, 8); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (8ints) */ public void testConstructor_8int1() throws Throwable { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (8ints) */ public void testConstructor_8int__PeriodType1() throws Throwable { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_8int__PeriodType2() throws Throwable { MutablePeriod test = new MutablePeriod(0, 0, 0, 0, 5, 6, 7, 8, PeriodType.dayTime()); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_8int__PeriodType3() throws Throwable { try { new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.dayTime()); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testConstructor_long_long1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_long_PeriodType1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis(), (PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_PeriodType2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis(), PeriodType.dayTime()); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(31, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_PeriodType3() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 6, 9, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis(), PeriodType.standard().withMillisRemoved()); assertEquals(PeriodType.standard().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_long_Chronology1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0, CopticChronology.getInstance()); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1, CopticChronology.getInstance()); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis(), CopticChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_Chronology2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis(), (Chronology) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_long_long_PeriodType_Chronology1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0, CopticChronology.getInstance()); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1, CopticChronology.getInstance()); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis(), (PeriodType) null, CopticChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_long_long_PeriodType_Chronology2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1.getMillis(), dt2.getMillis(), (PeriodType) null, null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RI_RI1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI3() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(3, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI4() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 17, 1, 1, 1, 1); DateTime dt2 = null; // 2002-06-09T01:00+01:00 MutablePeriod test = new MutablePeriod(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(-3, test.getYears()); assertEquals(-1, test.getMonths()); assertEquals(-1, test.getWeeks()); assertEquals(-1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(-1, test.getMinutes()); assertEquals(-1, test.getSeconds()); assertEquals(-1, test.getMillis()); } public void testConstructor_RI_RI5() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = null; // 2002-06-09T01:00+01:00 MutablePeriod test = new MutablePeriod(dt1, dt2); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RI_RI_PeriodType1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1, dt2, null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI_PeriodType2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 7, 10, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1, dt2, PeriodType.dayTime()); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(31, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI_PeriodType3() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2004, 6, 9, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1, dt2, PeriodType.standard().withMillisRemoved()); assertEquals(PeriodType.standard().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_RI_RI_PeriodType4() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = new DateTime(2005, 7, 17, 1, 1, 1, 1); MutablePeriod test = new MutablePeriod(dt1, dt2, PeriodType.standard()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(3, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(1, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(0, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RI_PeriodType5() throws Throwable { DateTime dt1 = null; // 2002-06-09T01:00+01:00 DateTime dt2 = null; // 2002-06-09T01:00+01:00 MutablePeriod test = new MutablePeriod(dt1, dt2, PeriodType.standard()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RI_RD1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Duration dur = new Interval(dt1, dt2).toDuration(); MutablePeriod test = new MutablePeriod(dt1, dur); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RD2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Duration dur = null; MutablePeriod test = new MutablePeriod(dt1, dur); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_RI_RD_PeriodType1() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); Duration dur = new Interval(dt1, dt2).toDuration(); MutablePeriod test = new MutablePeriod(dt1, dur, PeriodType.yearDayTime()); assertEquals(PeriodType.yearDayTime(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(31, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } public void testConstructor_RI_RD_PeriodType2() throws Throwable { DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); Duration dur = null; MutablePeriod test = new MutablePeriod(dt1, dur, (PeriodType) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (Object) */ public void testConstructor_Object1() throws Throwable { MutablePeriod test = new MutablePeriod("P1Y2M3D"); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(3, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object2() throws Throwable { MutablePeriod test = new MutablePeriod((Object) null); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object3() throws Throwable { MutablePeriod test = new MutablePeriod(new Period(0, 0, 0, 0, 1, 2, 3, 4, PeriodType.dayTime())); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(2, test.getMinutes()); assertEquals(3, test.getSeconds()); assertEquals(4, test.getMillis()); } public void testConstructor_Object4() throws Throwable { Period base = new Period(1, 1, 0, 1, 1, 1, 1, 1, PeriodType.standard()); MutablePeriod test = new MutablePeriod(base); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(1, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(1, test.getDays()); assertEquals(1, test.getHours()); assertEquals(1, test.getMinutes()); assertEquals(1, test.getSeconds()); assertEquals(1, test.getMillis()); } //----------------------------------------------------------------------- /** * Test constructor (Object,PeriodType) */ public void testConstructor_Object_PeriodType1() throws Throwable { MutablePeriod test = new MutablePeriod("P1Y2M3D", PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), test.getPeriodType()); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(3, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object_PeriodType2() throws Throwable { MutablePeriod test = new MutablePeriod((Object) null, PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); } public void testConstructor_Object_PeriodType3() throws Throwable { MutablePeriod test = new MutablePeriod(new Period(0, 0, 0, 0, 1, 2, 3, 4, PeriodType.dayTime()), PeriodType.yearMonthDayTime()); assertEquals(PeriodType.yearMonthDayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(2, test.getMinutes()); assertEquals(3, test.getSeconds()); assertEquals(4, test.getMillis()); } public void testConstructor_Object_PeriodType4() throws Throwable { MutablePeriod test = new MutablePeriod(new Period(0, 0, 0, 0, 1, 2, 3, 4, PeriodType.dayTime()), (PeriodType) null); assertEquals(PeriodType.dayTime(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(1, test.getHours()); assertEquals(2, test.getMinutes()); assertEquals(3, test.getSeconds()); assertEquals(4, test.getMillis()); } //----------------------------------------------------------------------- public void testConstructor_Object_Chronology1() throws Throwable { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; MutablePeriod test = new MutablePeriod(new Duration(length), ISOChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } public void testConstructor_Object_Chronology2() throws Throwable { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; MutablePeriod test = new MutablePeriod(new Duration(length), ISOChronology.getInstanceUTC()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(64, test.getWeeks()); assertEquals(2, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } } joda-time-2.3/src/test/java/org/joda/time/TestMonthDay_Basics.java0000644000175000017500000007210311757146440024436 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for MonthDay. Based on {@link TestYearMonth_Basics} */ public class TestMonthDay_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); // private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); // private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); // private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON); // private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); // private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS); // private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMonthDay_Basics.class); } public TestMonthDay_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testGet() { MonthDay test = new MonthDay(); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.year()); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { MonthDay test = new MonthDay(); assertEquals(2, test.size()); } public void testGetFieldType() { MonthDay test = new MonthDay(COPTIC_PARIS); assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(0)); assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(1)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { MonthDay test = new MonthDay(COPTIC_PARIS); DateTimeFieldType[] fields = test.getFieldTypes(); assertEquals(2, fields.length); assertSame(DateTimeFieldType.monthOfYear(), fields[0]); assertSame(DateTimeFieldType.dayOfMonth(), fields[1]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField() { MonthDay test = new MonthDay(COPTIC_PARIS); assertSame(COPTIC_UTC.monthOfYear(), test.getField(0)); assertSame(COPTIC_UTC.dayOfMonth(), test.getField(1)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { MonthDay test = new MonthDay(COPTIC_PARIS); DateTimeField[] fields = test.getFields(); assertEquals(2, fields.length); assertSame(COPTIC_UTC.monthOfYear(), fields[0]); assertSame(COPTIC_UTC.dayOfMonth(), fields[1]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue() { MonthDay test = new MonthDay(); assertEquals(6, test.getValue(0)); assertEquals(9, test.getValue(1)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(2); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { MonthDay test = new MonthDay(); int[] values = test.getValues(); assertEquals(2, values.length); assertEquals(6, values[0]); assertEquals(9, values[1]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported() { MonthDay test = new MonthDay(COPTIC_PARIS); assertEquals(false, test.isSupported(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay())); } public void testEqualsHashCode() { MonthDay test1 = new MonthDay(10, 6, COPTIC_PARIS); MonthDay test2 = new MonthDay(10, 6, COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); MonthDay test3 = new MonthDay(10, 6); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockMD())); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); } class MockMD extends MockPartial { @Override public Chronology getChronology() { return COPTIC_UTC; } @Override public DateTimeField[] getFields() { return new DateTimeField[] { COPTIC_UTC.monthOfYear(), COPTIC_UTC.dayOfMonth() }; } @Override public int[] getValues() { return new int[] {10, 6}; } } //----------------------------------------------------------------------- public void testCompareTo() { MonthDay test1 = new MonthDay(6, 6); MonthDay test1a = new MonthDay(6, 6); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); MonthDay test2 = new MonthDay(6, 7); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC()); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth() }; int[] values = new int[] {6, 6}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} try { test1.compareTo(new LocalTime()); fail(); } catch (ClassCastException ex) {} Partial partial = new Partial() .with(DateTimeFieldType.centuryOfEra(), 1) .with(DateTimeFieldType.halfdayOfDay(), 0) .with(DateTimeFieldType.dayOfMonth(), 9); try { new MonthDay(10, 6).compareTo(partial); fail(); } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_MD() { MonthDay test1 = new MonthDay(6, 6); MonthDay test1a = new MonthDay(6, 6); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); MonthDay test2 = new MonthDay(6, 7); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { new MonthDay(6, 7).isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_MD() { MonthDay test1 = new MonthDay(6, 6); MonthDay test1a = new MonthDay(6, 6); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); MonthDay test2 = new MonthDay(6, 7); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC()); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new MonthDay(6, 7).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_MD() { MonthDay test1 = new MonthDay(6, 6); MonthDay test1a = new MonthDay(6, 6); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); MonthDay test2 = new MonthDay(6, 7); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new MonthDay(6, 7).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithChronologyRetainFields_Chrono() { MonthDay base = new MonthDay(6, 6, COPTIC_PARIS); MonthDay test = base.withChronologyRetainFields(BUDDHIST_TOKYO); check(base, 6, 6); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 6, 6); assertEquals(BUDDHIST_UTC, test.getChronology()); } public void testWithChronologyRetainFields_sameChrono() { MonthDay base = new MonthDay(6, 6, COPTIC_PARIS); MonthDay test = base.withChronologyRetainFields(COPTIC_TOKYO); assertSame(base, test); } public void testWithChronologyRetainFields_nullChrono() { MonthDay base = new MonthDay(6, 6, COPTIC_PARIS); MonthDay test = base.withChronologyRetainFields(null); check(base, 6, 6); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 6, 6); assertEquals(ISO_UTC, test.getChronology()); } //----------------------------------------------------------------------- public void testWithField() { MonthDay test = new MonthDay(9, 6); MonthDay result = test.withField(DateTimeFieldType.monthOfYear(), 10); assertEquals(new MonthDay(9, 6), test); assertEquals(new MonthDay(10, 6), result); } public void testWithField_nullField() { MonthDay test = new MonthDay(9, 6); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_unknownField() { MonthDay test = new MonthDay(9, 6); try { test.withField(DateTimeFieldType.hourOfDay(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_same() { MonthDay test = new MonthDay(9, 6); MonthDay result = test.withField(DateTimeFieldType.monthOfYear(), 9); assertEquals(new MonthDay(9, 6), test); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded() { MonthDay test = new MonthDay(9, 6); MonthDay result = test.withFieldAdded(DurationFieldType.months(), 1); assertEquals(new MonthDay(9, 6), test); assertEquals(new MonthDay(10, 6), result); } public void testWithFieldAdded_nullField_zero() { MonthDay test = new MonthDay(9, 6); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_nullField_nonZero() { MonthDay test = new MonthDay(9, 6); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_zero() { MonthDay test = new MonthDay(9, 6); MonthDay result = test.withFieldAdded(DurationFieldType.months(), 0); assertSame(test, result); } public void testWithFieldAdded_unknownField() { MonthDay test = new MonthDay(9, 6); try { test.withFieldAdded(DurationFieldType.hours(), 6); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPlus_RP() { MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance()); MonthDay result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8)); MonthDay expected = new MonthDay(8, 9, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusMonths_int() { MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance()); MonthDay result = test.plusMonths(1); MonthDay expected = new MonthDay(7, 5, BuddhistChronology.getInstance()); assertEquals(expected, result); } public void testPlusMonths_int_fromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.plusMonths(1); MonthDay expected = new MonthDay(3, 29, ISOChronology.getInstance()); assertEquals(expected, result); } public void testPlusMonths_int_negativeFromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.plusMonths(-1); MonthDay expected = new MonthDay(1, 29, ISOChronology.getInstance()); assertEquals(expected, result); } public void testPlusMonths_int_endOfMonthAdjust() { MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC()); MonthDay result = test.plusMonths(1); MonthDay expected = new MonthDay(4, 30, ISOChronology.getInstance()); assertEquals(expected, result); } public void testPlusMonths_int_negativeEndOfMonthAdjust() { MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC()); MonthDay result = test.plusMonths(-1); MonthDay expected = new MonthDay(2, 29, ISOChronology.getInstance()); assertEquals(expected, result); } public void testPlusMonths_int_same() { MonthDay test = new MonthDay(6, 5, ISO_UTC); MonthDay result = test.plusMonths(0); assertSame(test, result); } public void testPlusMonths_int_wrap() { MonthDay test = new MonthDay(6, 5, ISO_UTC); MonthDay result = test.plusMonths(10); MonthDay expected = new MonthDay(4, 5, ISO_UTC); assertEquals(expected, result); } public void testPlusMonths_int_adjust() { MonthDay test = new MonthDay(7, 31, ISO_UTC); MonthDay result = test.plusMonths(2); MonthDay expected = new MonthDay(9, 30, ISO_UTC); assertEquals(expected, result); } //------------------------------------------------------------------------- public void testPlusDays_int() { MonthDay test = new MonthDay(5, 10, BuddhistChronology.getInstance()); MonthDay result = test.plusDays(1); MonthDay expected = new MonthDay(5, 11, BuddhistChronology.getInstance()); assertEquals(expected, result); } public void testPlusDays_int_fromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.plusDays(1); MonthDay expected = new MonthDay(3, 1, ISOChronology.getInstance()); assertEquals(expected, result); } public void testPlusDays_int_negativeFromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.plusDays(-1); MonthDay expected = new MonthDay(2, 28, ISOChronology.getInstance()); assertEquals(expected, result); } public void testPlusDays_same() { MonthDay test = new MonthDay(5, 10, BuddhistChronology.getInstance()); MonthDay result = test.plusDays(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance()); MonthDay result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); MonthDay expected = new MonthDay(5, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusMonths_int() { MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance()); MonthDay result = test.minusMonths(1); MonthDay expected = new MonthDay(5, 5, BuddhistChronology.getInstance()); assertEquals(expected, result); } public void testMinusMonths_int_fromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.minusMonths(1); MonthDay expected = new MonthDay(1, 29, ISOChronology.getInstance()); assertEquals(expected, result); } public void testMinusMonths_int_negativeFromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.minusMonths(-1); MonthDay expected = new MonthDay(3, 29, ISOChronology.getInstance()); assertEquals(expected, result); } public void testMinusMonths_int_endOfMonthAdjust() { MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC()); MonthDay result = test.minusMonths(1); MonthDay expected = new MonthDay(2, 29, ISOChronology.getInstance()); assertEquals(expected, result); } public void testMinusMonths_int_negativeEndOfMonthAdjust() { MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC()); MonthDay result = test.minusMonths(-1); MonthDay expected = new MonthDay(4, 30, ISOChronology.getInstance()); assertEquals(expected, result); } public void testMinusMonths_int_same() { MonthDay test = new MonthDay(6, 5, ISO_UTC); MonthDay result = test.minusMonths(0); assertSame(test, result); } public void testMinusMonths_int_wrap() { MonthDay test = new MonthDay(6, 5, ISO_UTC); MonthDay result = test.minusMonths(10); MonthDay expected = new MonthDay(8, 5, ISO_UTC); assertEquals(expected, result); } public void testMinusMonths_int_adjust() { MonthDay test = new MonthDay(7, 31, ISO_UTC); MonthDay result = test.minusMonths(3); MonthDay expected = new MonthDay(4, 30, ISO_UTC); assertEquals(expected, result); } //------------------------------------------------------------------------- public void testMinusDays_int() { MonthDay test = new MonthDay(5, 11, BuddhistChronology.getInstance()); MonthDay result = test.minusDays(1); MonthDay expected = new MonthDay(5, 10, BuddhistChronology.getInstance()); assertEquals(expected, result); } public void testMinusDays_int_fromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.minusDays(1); MonthDay expected = new MonthDay(2, 28, ISOChronology.getInstance()); assertEquals(expected, result); } public void testMinusDays_int_negativeFromLeap() { MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC()); MonthDay result = test.minusDays(-1); MonthDay expected = new MonthDay(3, 1, ISOChronology.getInstance()); assertEquals(expected, result); } public void testMinusDays_same() { MonthDay test = new MonthDay(5, 11, BuddhistChronology.getInstance()); MonthDay result = test.minusDays(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testToLocalDate() { MonthDay base = new MonthDay(6, 6, COPTIC_UTC); LocalDate test = base.toLocalDate(2009); assertEquals(new LocalDate(2009, 6, 6, COPTIC_UTC), test); try { base.toLocalDate(0); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testToDateTime_RI() { MonthDay base = new MonthDay(6, 6, COPTIC_PARIS); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTime test = base.toDateTime(dt); check(base, 6, 6); DateTime expected = dt; expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(6); assertEquals(expected, test); } public void testToDateTime_nullRI() { MonthDay base = new MonthDay(6, 6); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 6, 6); DateTime expected = dt; expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(6); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testWithers() { MonthDay test = new MonthDay(10, 6); check(test.withMonthOfYear(5), 5, 6); check(test.withDayOfMonth(2), 10, 2); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testProperty() { MonthDay test = new MonthDay(6, 6); assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear())); assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth())); try { test.property(DateTimeFieldType.millisOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { MonthDay test = new MonthDay(5, 6, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); MonthDay result = (MonthDay) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); } //----------------------------------------------------------------------- public void testToString() { MonthDay test = new MonthDay(5, 6); assertEquals("--05-06", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { MonthDay test = new MonthDay(5, 6); assertEquals("05 \ufffd\ufffd", test.toString("MM HH")); assertEquals("--05-06", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { MonthDay test = new MonthDay(5, 6); assertEquals("\ufffd 6/5", test.toString("EEE d/M", Locale.ENGLISH)); assertEquals("\ufffd 6/5", test.toString("EEE d/M", Locale.FRENCH)); assertEquals("--05-06", test.toString(null, Locale.ENGLISH)); assertEquals("\ufffd 6/5", test.toString("EEE d/M", null)); assertEquals("--05-06", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { MonthDay test = new MonthDay(5, 6); assertEquals("05 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("MM HH"))); assertEquals("--05-06", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private void check(MonthDay test, int month, int day) { assertEquals(month, test.getMonthOfYear()); assertEquals(day, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestYearMonthDay_Properties.java0000644000175000017500000005645512200501234026177 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.StrictChronology; /** * This class is a Junit unit test for YearMonthDay. * * @author Stephen Colebourne */ @SuppressWarnings("deprecation") public class TestYearMonthDay_Properties extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale systemDefaultLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestYearMonthDay_Properties.class); } public TestYearMonthDay_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); systemDefaultLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; Locale.setDefault(systemDefaultLocale); systemDefaultLocale = null; } //----------------------------------------------------------------------- public void testPropertyGetYear() { YearMonthDay test = new YearMonthDay(1972, 6, 9); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertSame(test, test.year().getReadablePartial()); assertSame(test, test.year().getYearMonthDay()); assertEquals(1972, test.year().get()); assertEquals("1972", test.year().getAsString()); assertEquals("1972", test.year().getAsText()); assertEquals("1972", test.year().getAsText(Locale.FRENCH)); assertEquals("1972", test.year().getAsShortText()); assertEquals("1972", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesYear() { YearMonthDay test = new YearMonthDay(1972, 6, 9); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292278993, test.year().getMaximumValue()); assertEquals(292278993, test.year().getMaximumValueOverall()); } public void testPropertyAddYear() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.year().addToCopy(9); check(test, 1972, 6, 9); check(copy, 1981, 6, 9); copy = test.year().addToCopy(0); check(copy, 1972, 6, 9); copy = test.year().addToCopy(292277023 - 1972); check(copy, 292277023, 6, 9); try { test.year().addToCopy(292278993 - 1972 + 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9); copy = test.year().addToCopy(-1972); check(copy, 0, 6, 9); copy = test.year().addToCopy(-1973); check(copy, -1, 6, 9); try { test.year().addToCopy(-292275054 - 1972 - 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9); } public void testPropertyAddWrapFieldYear() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.year().addWrapFieldToCopy(9); check(test, 1972, 6, 9); check(copy, 1981, 6, 9); copy = test.year().addWrapFieldToCopy(0); check(copy, 1972, 6, 9); copy = test.year().addWrapFieldToCopy(292278993 - 1972 + 1); check(copy, -292275054, 6, 9); copy = test.year().addWrapFieldToCopy(-292275054 - 1972 - 1); check(copy, 292278993, 6, 9); } public void testPropertySetYear() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.year().setCopy(12); check(test, 1972, 6, 9); check(copy, 12, 6, 9); } public void testPropertySetTextYear() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.year().setCopy("12"); check(test, 1972, 6, 9); check(copy, 12, 6, 9); } public void testPropertyCompareToYear() { YearMonthDay test1 = new YearMonthDay(TEST_TIME1); YearMonthDay test2 = new YearMonthDay(TEST_TIME2); assertEquals(true, test1.year().compareTo(test2) < 0); assertEquals(true, test2.year().compareTo(test1) > 0); assertEquals(true, test1.year().compareTo(test1) == 0); try { test1.year().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.year().compareTo(dt2) < 0); assertEquals(true, test2.year().compareTo(dt1) > 0); assertEquals(true, test1.year().compareTo(dt1) == 0); try { test1.year().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getReadablePartial()); assertSame(test, test.monthOfYear().getYearMonthDay()); assertEquals(6, test.monthOfYear().get()); assertEquals("6", test.monthOfYear().getAsString()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new YearMonthDay(1972, 7, 9); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); } public void testPropertyGetMaxMinValuesMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyAddMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.monthOfYear().addToCopy(6); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); copy = test.monthOfYear().addToCopy(7); check(copy, 1973, 1, 9); copy = test.monthOfYear().addToCopy(-5); check(copy, 1972, 1, 9); copy = test.monthOfYear().addToCopy(-6); check(copy, 1971, 12, 9); test = new YearMonthDay(1972, 1, 31); copy = test.monthOfYear().addToCopy(1); check(copy, 1972, 2, 29); copy = test.monthOfYear().addToCopy(2); check(copy, 1972, 3, 31); copy = test.monthOfYear().addToCopy(3); check(copy, 1972, 4, 30); test = new YearMonthDay(1971, 1, 31); copy = test.monthOfYear().addToCopy(1); check(copy, 1971, 2, 28); } public void testPropertyAddWrapFieldMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.monthOfYear().addWrapFieldToCopy(4); check(test, 1972, 6, 9); check(copy, 1972, 10, 9); copy = test.monthOfYear().addWrapFieldToCopy(8); check(copy, 1972, 2, 9); copy = test.monthOfYear().addWrapFieldToCopy(-8); check(copy, 1972, 10, 9); test = new YearMonthDay(1972, 1, 31); copy = test.monthOfYear().addWrapFieldToCopy(1); check(copy, 1972, 2, 29); copy = test.monthOfYear().addWrapFieldToCopy(2); check(copy, 1972, 3, 31); copy = test.monthOfYear().addWrapFieldToCopy(3); check(copy, 1972, 4, 30); test = new YearMonthDay(1971, 1, 31); copy = test.monthOfYear().addWrapFieldToCopy(1); check(copy, 1971, 2, 28); } public void testPropertySetMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.monthOfYear().setCopy(12); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); test = new YearMonthDay(1972, 1, 31); copy = test.monthOfYear().setCopy(2); check(copy, 1972, 2, 29); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.monthOfYear().setCopy("12"); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); copy = test.monthOfYear().setCopy("December"); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); copy = test.monthOfYear().setCopy("Dec"); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); } public void testPropertyCompareToMonth() { YearMonthDay test1 = new YearMonthDay(TEST_TIME1); YearMonthDay test2 = new YearMonthDay(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetDay() { YearMonthDay test = new YearMonthDay(1972, 6, 9); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertSame(test, test.dayOfMonth().getReadablePartial()); assertSame(test, test.dayOfMonth().getYearMonthDay()); assertEquals(9, test.dayOfMonth().get()); assertEquals("9", test.dayOfMonth().getAsString()); assertEquals("9", test.dayOfMonth().getAsText()); assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("9", test.dayOfMonth().getAsShortText()); assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesDay() { YearMonthDay test = new YearMonthDay(1972, 6, 9); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); test = new YearMonthDay(1972, 7, 9); assertEquals(31, test.dayOfMonth().getMaximumValue()); test = new YearMonthDay(1972, 2, 9); assertEquals(29, test.dayOfMonth().getMaximumValue()); test = new YearMonthDay(1971, 2, 9); assertEquals(28, test.dayOfMonth().getMaximumValue()); } public void testPropertyAddDay() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.dayOfMonth().addToCopy(9); check(test, 1972, 6, 9); check(copy, 1972, 6, 18); copy = test.dayOfMonth().addToCopy(21); check(copy, 1972, 6, 30); copy = test.dayOfMonth().addToCopy(22); check(copy, 1972, 7, 1); copy = test.dayOfMonth().addToCopy(22 + 30); check(copy, 1972, 7, 31); copy = test.dayOfMonth().addToCopy(22 + 31); check(copy, 1972, 8, 1); copy = test.dayOfMonth().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); check(copy, 1972, 12, 31); copy = test.dayOfMonth().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); check(copy, 1973, 1, 1); copy = test.dayOfMonth().addToCopy(-8); check(copy, 1972, 6, 1); copy = test.dayOfMonth().addToCopy(-9); check(copy, 1972, 5, 31); copy = test.dayOfMonth().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); check(copy, 1972, 1, 1); copy = test.dayOfMonth().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); check(copy, 1971, 12, 31); } public void testPropertyAddWrapFieldDay() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.dayOfMonth().addWrapFieldToCopy(21); check(test, 1972, 6, 9); check(copy, 1972, 6, 30); copy = test.dayOfMonth().addWrapFieldToCopy(22); check(copy, 1972, 6, 1); copy = test.dayOfMonth().addWrapFieldToCopy(-12); check(copy, 1972, 6, 27); test = new YearMonthDay(1972, 7, 9); copy = test.dayOfMonth().addWrapFieldToCopy(21); check(copy, 1972, 7, 30); copy = test.dayOfMonth().addWrapFieldToCopy(22); check(copy, 1972, 7, 31); copy = test.dayOfMonth().addWrapFieldToCopy(23); check(copy, 1972, 7, 1); copy = test.dayOfMonth().addWrapFieldToCopy(-12); check(copy, 1972, 7, 28); } public void testPropertySetDay() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.dayOfMonth().setCopy(12); check(test, 1972, 6, 9); check(copy, 1972, 6, 12); try { test.dayOfMonth().setCopy(31); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfMonth().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDay() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.dayOfMonth().setCopy("12"); check(test, 1972, 6, 9); check(copy, 1972, 6, 12); } public void testPropertyWithMaximumValueDayOfMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.dayOfMonth().withMaximumValue(); check(test, 1972, 6, 9); check(copy, 1972, 6, 30); } public void testPropertyWithMinimumValueDayOfMonth() { YearMonthDay test = new YearMonthDay(1972, 6, 9); YearMonthDay copy = test.dayOfMonth().withMinimumValue(); check(test, 1972, 6, 9); check(copy, 1972, 6, 1); } public void testPropertyCompareToDay() { YearMonthDay test1 = new YearMonthDay(TEST_TIME1); YearMonthDay test2 = new YearMonthDay(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0); try { test1.dayOfMonth().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyEquals() { YearMonthDay test1 = new YearMonthDay(2005, 11, 8); YearMonthDay test2 = new YearMonthDay(2005, 11, 9); YearMonthDay test3 = new YearMonthDay(2005, 11, 8, CopticChronology.getInstanceUTC()); assertEquals(false, test1.dayOfMonth().equals(test1.year())); assertEquals(false, test1.dayOfMonth().equals(test1.monthOfYear())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(test2.year())); assertEquals(false, test1.dayOfMonth().equals(test2.monthOfYear())); assertEquals(false, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(false, test1.monthOfYear().equals(test1.year())); assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test1.dayOfMonth())); assertEquals(false, test1.monthOfYear().equals(test2.year())); assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test2.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(null)); assertEquals(false, test1.dayOfMonth().equals("any")); // chrono assertEquals(false, test1.dayOfMonth().equals(test3.dayOfMonth())); } public void testPropertyHashCode() { YearMonthDay test1 = new YearMonthDay(2005, 11, 8); YearMonthDay test2 = new YearMonthDay(2005, 11, 9); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(false, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); } public void testPropertyEqualsHashCodeLenient() { YearMonthDay test1 = new YearMonthDay(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); YearMonthDay test2 = new YearMonthDay(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } public void testPropertyEqualsHashCodeStrict() { YearMonthDay test1 = new YearMonthDay(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); YearMonthDay test2 = new YearMonthDay(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } //----------------------------------------------------------------------- private void check(YearMonthDay test, int year, int month, int day) { assertEquals(year, test.getYear()); assertEquals(month, test.getMonthOfYear()); assertEquals(day, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestPartial_Constructors.java0000644000175000017500000003763112200501234025576 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Arrays; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for Partial. * * @author Stephen Colebourne */ public class TestPartial_Constructors extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology GREGORIAN_PARIS = GregorianChronology.getInstance(PARIS); private static final Chronology GREGORIAN_UTC = GregorianChronology.getInstanceUTC(); private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestPartial_Constructors.class); } public TestPartial_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- /** * Test constructor */ public void testConstructor() throws Throwable { Partial test = new Partial(); assertEquals(ISO_UTC, test.getChronology()); assertEquals(0, test.size()); } //----------------------------------------------------------------------- /** * Test constructor */ public void testConstructor_Chrono() throws Throwable { Partial test = new Partial((Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(0, test.size()); test = new Partial(GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(0, test.size()); } //----------------------------------------------------------------------- /** * Test constructor */ public void testConstructor_Type_int() throws Throwable { Partial test = new Partial(DateTimeFieldType.dayOfYear(), 4); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1, test.size()); assertEquals(4, test.getValue(0)); assertEquals(4, test.get(DateTimeFieldType.dayOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear())); } /** * Test constructor */ public void testConstructorEx1_Type_int() throws Throwable { try { new Partial(null, 4); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } } /** * Test constructor */ public void testConstructorEx2_Type_int() throws Throwable { try { new Partial(DateTimeFieldType.dayOfYear(), 0); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- /** * Test constructor */ public void testConstructor_Type_int_Chrono() throws Throwable { Partial test = new Partial(DateTimeFieldType.dayOfYear(), 4, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1, test.size()); assertEquals(4, test.getValue(0)); assertEquals(4, test.get(DateTimeFieldType.dayOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear())); } /** * Test constructor */ public void testConstructorEx_Type_int_Chrono() throws Throwable { try { new Partial(null, 4, ISO_UTC); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } } /** * Test constructor */ public void testConstructorEx2_Type_int_Chrono() throws Throwable { try { new Partial(DateTimeFieldType.dayOfYear(), 0, ISO_UTC); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- /** * Test constructor */ public void testConstructor_TypeArray_intArray() throws Throwable { DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.dayOfYear() }; int[] values = new int[] {2005, 33}; Partial test = new Partial(types, values); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2, test.size()); assertEquals(2005, test.getValue(0)); assertEquals(2005, test.get(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(33, test.getValue(1)); assertEquals(33, test.get(DateTimeFieldType.dayOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear())); assertEquals(true, Arrays.equals(test.getFieldTypes(), types)); assertEquals(true, Arrays.equals(test.getValues(), values)); } /** * Test constructor */ public void testConstructor2_TypeArray_intArray() throws Throwable { DateTimeFieldType[] types = new DateTimeFieldType[0]; int[] values = new int[0]; Partial test = new Partial(types, values); assertEquals(ISO_UTC, test.getChronology()); assertEquals(0, test.size()); } /** * Test constructor */ public void testConstructorEx1_TypeArray_intArray() throws Throwable { try { new Partial((DateTimeFieldType[]) null, new int[] {1}); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } } /** * Test constructor */ public void testConstructorEx3_TypeArray_intArray() throws Throwable { try { new Partial(new DateTimeFieldType[] {DateTimeFieldType.dayOfYear()}, null); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } } /** * Test constructor */ public void testConstructorEx5_TypeArray_intArray() throws Throwable { try { new Partial(new DateTimeFieldType[] {DateTimeFieldType.dayOfYear()}, new int[2]); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "same length"); } } /** * Test constructor */ public void testConstructorEx6_TypeArray_intArray() throws Throwable { try { new Partial(new DateTimeFieldType[] {null, DateTimeFieldType.dayOfYear()}, new int[2]); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "contain null"); } try { new Partial(new DateTimeFieldType[] {DateTimeFieldType.dayOfYear(), null}, new int[2]); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "contain null"); } } /** * Test constructor */ public void testConstructorEx7_TypeArray_intArray() throws Throwable { int[] values = new int[] {1, 1, 1}; DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.dayOfMonth(), DateTimeFieldType.year(), DateTimeFieldType.monthOfYear() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must be in order", "largest-smallest"); } types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.dayOfMonth(), DateTimeFieldType.monthOfYear() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must be in order", "largest-smallest"); } types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.era(), DateTimeFieldType.monthOfYear() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must be in order", "largest-smallest"); } types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.dayOfMonth(), DateTimeFieldType.era() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must be in order", "largest-smallest"); } types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.dayOfMonth(), DateTimeFieldType.dayOfYear() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must be in order", "largest-smallest"); } types = new DateTimeFieldType[] { DateTimeFieldType.yearOfEra(), DateTimeFieldType.year(), DateTimeFieldType.dayOfYear() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must be in order", "largest-smallest"); } } /** * Test constructor */ public void testConstructorEx8_TypeArray_intArray() throws Throwable { int[] values = new int[] {1, 1, 1}; DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.era(), DateTimeFieldType.year(), DateTimeFieldType.year() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not", "duplicate"); } types = new DateTimeFieldType[] { DateTimeFieldType.era(), DateTimeFieldType.era(), DateTimeFieldType.monthOfYear() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not", "duplicate"); } types = new DateTimeFieldType[] { DateTimeFieldType.dayOfYear(), DateTimeFieldType.dayOfMonth(), DateTimeFieldType.dayOfMonth() }; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not", "duplicate"); } } /** * Test constructor */ public void testConstructorEx9_TypeArray_intArray() throws Throwable { int[] values = new int[] {3, 0}; DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.dayOfMonth(), DateTimeFieldType.dayOfWeek()}; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- /** * Test constructor */ public void testConstructor_TypeArray_intArray_Chrono() throws Throwable { DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.dayOfYear() }; int[] values = new int[] {2005, 33}; Partial test = new Partial(types, values, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(2, test.size()); assertEquals(2005, test.getValue(0)); assertEquals(2005, test.get(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(33, test.getValue(1)); assertEquals(33, test.get(DateTimeFieldType.dayOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear())); assertEquals(true, Arrays.equals(test.getFieldTypes(), types)); assertEquals(true, Arrays.equals(test.getValues(), values)); } //----------------------------------------------------------------------- /** * Test constructor */ @SuppressWarnings("deprecation") public void testConstructor_Partial() throws Throwable { YearMonthDay ymd = new YearMonthDay(2005, 6, 25, GREGORIAN_PARIS); Partial test = new Partial(ymd); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(3, test.size()); assertEquals(2005, test.getValue(0)); assertEquals(2005, test.get(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(6, test.getValue(1)); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear())); assertEquals(25, test.getValue(2)); assertEquals(25, test.get(DateTimeFieldType.dayOfMonth())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth())); } /** * Test constructor */ public void testConstructorEx_Partial() throws Throwable { try { new Partial((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } } //----------------------------------------------------------------------- /** * Checks if the exception message is valid. * * @param ex the exception to check * @param str the string to check */ private void assertMessageContains(Exception ex, String str) { assertEquals(ex.getMessage() + ": " + str, true, ex.getMessage().indexOf(str) >= 0); } /** * Checks if the exception message is valid. * * @param ex the exception to check * @param str1 the string to check * @param str2 the string to check */ private void assertMessageContains(Exception ex, String str1, String str2) { assertEquals(ex.getMessage() + ": " + str1 + "/" + str2, true, ex.getMessage().indexOf(str1) >= 0 && ex.getMessage().indexOf(str2) >= 0 && ex.getMessage().indexOf(str1) < ex.getMessage().indexOf(str2)); } } joda-time-2.3/src/test/java/org/joda/time/MockZone.java0000644000175000017500000000337011564251363022311 0ustar ebourgebourg/* * Copyright 2001-2007 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; public class MockZone extends DateTimeZone { long transition; int winterOffset; int sizeMillis; public MockZone(long transition, int winterOffset, int sizeSecs) { super("MockZone"); this.transition = transition; this.winterOffset = winterOffset; this.sizeMillis = sizeSecs * 1000; } public int getOffset(long instant) { return (instant < transition ? winterOffset : winterOffset + sizeMillis); } public int getStandardOffset(long instant) { return winterOffset; } public long nextTransition(long instant) { return (instant < transition ? transition : transition + 180L * DateTimeConstants.MILLIS_PER_DAY); } public long previousTransition(long instant) { return (instant > transition ? transition : transition - 180L * DateTimeConstants.MILLIS_PER_DAY); } public boolean isFixed() { return false; } public String getNameKey(long instant) { return null; } public boolean equals(Object object) { return false; } } joda-time-2.3/src/test/java/org/joda/time/TestMonthDay_Properties.java0000644000175000017500000003544611640073667025400 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.StrictChronology; /** * This class is a Junit unit test for MonthDay. Based on {@link TestYearMonth_Propeties} */ public class TestMonthDay_Properties extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMonthDay_Properties.class); } public TestMonthDay_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); Locale.setDefault(Locale.UK); DateTimeZone.setDefault(DateTimeZone.UTC); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; Locale.setDefault(locale); locale = null; } //----------------------------------------------------------------------- public void testPropertyGetMonthOfYear() { MonthDay test = new MonthDay(9, 6); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getReadablePartial()); assertSame(test, test.monthOfYear().getMonthDay()); assertEquals(9, test.monthOfYear().get()); assertEquals("9", test.monthOfYear().getAsString()); assertEquals("September", test.monthOfYear().getAsText()); assertEquals("septembre", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Sep", test.monthOfYear().getAsShortText()); assertEquals("sept.", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); // assertEquals(test.getChronology().days(), test.dayOfMonth().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMonthOfYear() { MonthDay test = new MonthDay(10, 6); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyAddMonthOfYear() { MonthDay test = new MonthDay(3, 6); MonthDay copy = test.monthOfYear().addToCopy(9); check(test, 3, 6); check(copy, 12, 6); copy = test.monthOfYear().addToCopy(0); check(copy, 3, 6); check(test, 3, 6); copy = test.monthOfYear().addToCopy(-3); check(copy, 12, 6); check(test, 3, 6); } public void testPropertyAddWrapFieldMonthOfYear() { MonthDay test = new MonthDay(5, 6); MonthDay copy = test.monthOfYear().addWrapFieldToCopy(2); check(test, 5, 6); check(copy, 7, 6); copy = test.monthOfYear().addWrapFieldToCopy(2); check(copy, 7, 6); copy = test.monthOfYear().addWrapFieldToCopy(292278993 - 4 + 1); check(copy, 11, 6); copy = test.monthOfYear().addWrapFieldToCopy(-292275054 - 4 - 1); check(copy, 6, 6); } public void testPropertySetMonthOfYear() { MonthDay test = new MonthDay(10, 6); MonthDay copy = test.monthOfYear().setCopy(12); check(test, 10, 6); check(copy, 12, 6); } public void testPropertySetTextMonthOfYear() { MonthDay test = new MonthDay(10, 6); MonthDay copy = test.monthOfYear().setCopy("12"); check(test, 10, 6); check(copy, 12, 6); } public void testPropertyCompareToMonthOfYear() { MonthDay test1 = new MonthDay(TEST_TIME1); MonthDay test2 = new MonthDay(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetDayOfMonth() { MonthDay test = new MonthDay(4, 6); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertSame(test, test.dayOfMonth().getReadablePartial()); assertSame(test, test.dayOfMonth().getMonthDay()); assertEquals(6, test.dayOfMonth().get()); assertEquals("6", test.dayOfMonth().getAsString()); assertEquals("6", test.dayOfMonth().getAsText()); assertEquals("6", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("6", test.dayOfMonth().getAsShortText()); assertEquals("6", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); test = new MonthDay(4, 7); assertEquals("7", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("7", test.dayOfMonth().getAsShortText(Locale.FRENCH)); } public void testPropertyGetMaxMinValuesDayOfMonth() { MonthDay test = new MonthDay(4, 6); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); } public void testPropertyAddDayOfMonth() { MonthDay test = new MonthDay(4, 6); MonthDay copy = test.dayOfMonth().addToCopy(6); check(test, 4, 6); check(copy, 4, 12); copy = test.dayOfMonth().addToCopy(7); check(copy, 4, 13); copy = test.dayOfMonth().addToCopy(-5); check(copy, 4, 1); copy = test.dayOfMonth().addToCopy(-6); check(copy, 3, 31); } public void testPropertyAddWrapFieldDayOfMonth() { MonthDay test = new MonthDay(4, 6); MonthDay copy = test.dayOfMonth().addWrapFieldToCopy(4); check(test, 4, 6); check(copy, 4, 10); copy = test.dayOfMonth().addWrapFieldToCopy(8); check(copy, 4, 14); copy = test.dayOfMonth().addWrapFieldToCopy(-8); check(copy, 4, 28); } public void testPropertySetDayOfMonth() { MonthDay test = new MonthDay(4, 6); MonthDay copy = test.dayOfMonth().setCopy(12); check(test, 4, 6); check(copy, 4, 12); try { test.dayOfMonth().setCopy(33); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfMonth().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextDayOfMonth() { MonthDay test = new MonthDay(4, 6); MonthDay copy = test.dayOfMonth().setCopy("12"); check(test, 4, 6); check(copy, 4, 12); copy = test.dayOfMonth().setCopy("2"); check(test, 4, 6); check(copy, 4, 2); copy = test.dayOfMonth().setCopy("4"); check(test, 4, 6); check(copy, 4, 4); } public void testPropertyCompareToDayOfMonth() { MonthDay test1 = new MonthDay(TEST_TIME1); MonthDay test2 = new MonthDay(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0); try { test1.dayOfMonth().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyEquals() { MonthDay test1 = new MonthDay(11, 11); MonthDay test2 = new MonthDay(11, 12); MonthDay test3 = new MonthDay(11, 11, CopticChronology.getInstanceUTC()); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(test1.monthOfYear())); assertEquals(false, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(test2.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test1.dayOfMonth())); assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test2.dayOfMonth())); assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear())); assertEquals(false, test1.dayOfMonth().equals(null)); assertEquals(false, test1.dayOfMonth().equals("any")); // chrono assertEquals(false, test1.dayOfMonth().equals(test3.dayOfMonth())); } public void testPropertyHashCode() { MonthDay test1 = new MonthDay(5, 11); MonthDay test2 = new MonthDay(5, 12); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(false, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); } public void testPropertyEqualsHashCodeLenient() { MonthDay test1 = new MonthDay(5, 6, LenientChronology.getInstance(COPTIC_PARIS)); MonthDay test2 = new MonthDay(5, 6, LenientChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } public void testPropertyEqualsHashCodeStrict() { MonthDay test1 = new MonthDay(5, 6, StrictChronology.getInstance(COPTIC_PARIS)); MonthDay test2 = new MonthDay(5, 6, StrictChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } //----------------------------------------------------------------------- private void check(MonthDay test, int monthOfYear, int dayOfMonth) { assertEquals(monthOfYear, test.getMonthOfYear()); assertEquals(dayOfMonth, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutableDateTime_Sets.java0000644000175000017500000006437712035524574025447 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a JUnit test for MutableDateTime. * * @author Stephen Colebourne */ public class TestMutableDateTime_Sets extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutableDateTime_Sets.class); } public TestMutableDateTime_Sets(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testSetMillis_long1() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.setMillis(TEST_TIME2); assertEquals(TEST_TIME2, test.getMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testSetChronology_Chronology1() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.setChronology(GregorianChronology.getInstance(PARIS)); assertEquals(TEST_TIME1, test.getMillis()); assertEquals(GregorianChronology.getInstance(PARIS), test.getChronology()); } public void testSetChronology_Chronology2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.setChronology(null); assertEquals(TEST_TIME1, test.getMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testSetZone_DateTimeZone1() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.setZone(PARIS); assertEquals(TEST_TIME1, test.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); } public void testSetZone_DateTimeZone2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.setZone(null); assertEquals(TEST_TIME1, test.getMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testSetZoneRetainFields_DateTimeZone1() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.setZoneRetainFields(PARIS); assertEquals(TEST_TIME1 - DateTimeConstants.MILLIS_PER_HOUR, test.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), test.getChronology()); } public void testSetZoneRetainFields_DateTimeZone2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.setZoneRetainFields(null); assertEquals(TEST_TIME1, test.getMillis()); assertEquals(ISOChronology.getInstance(), test.getChronology()); } public void testSetZoneRetainFields_DateTimeZone3() { MutableDateTime test = new MutableDateTime(TEST_TIME1, GregorianChronology.getInstance(PARIS)); test.setZoneRetainFields(null); assertEquals(TEST_TIME1 + DateTimeConstants.MILLIS_PER_HOUR, test.getMillis()); assertEquals(GregorianChronology.getInstance(), test.getChronology()); } public void testSetZoneRetainFields_DateTimeZone4() { Chronology chrono = new MockNullZoneChronology(); MutableDateTime test = new MutableDateTime(TEST_TIME1, chrono); test.setZoneRetainFields(PARIS); assertEquals(TEST_TIME1 - DateTimeConstants.MILLIS_PER_HOUR, test.getMillis()); assertSame(chrono, test.getChronology()); } //----------------------------------------------------------------------- public void testSetMillis_RI1() { MutableDateTime test = new MutableDateTime(TEST_TIME1, BuddhistChronology.getInstance()); test.setMillis(new Instant(TEST_TIME2)); assertEquals(TEST_TIME2, test.getMillis()); assertEquals(BuddhistChronology.getInstance(), test.getChronology()); } public void testSetMillis_RI2() { MutableDateTime test = new MutableDateTime(TEST_TIME1, BuddhistChronology.getInstance()); test.setMillis(null); assertEquals(TEST_TIME_NOW, test.getMillis()); assertEquals(BuddhistChronology.getInstance(), test.getChronology()); } //----------------------------------------------------------------------- public void testSet_DateTimeFieldType_int1() { MutableDateTime test = new MutableDateTime(TEST_TIME1); test.set(DateTimeFieldType.year(), 2010); assertEquals(2010, test.getYear()); } public void testSet_DateTimeFieldType_int2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.set(null, 0); fail(); } catch (IllegalArgumentException ex) {} assertEquals(TEST_TIME1, test.getMillis()); } public void testSet_DateTimeFieldType_int3() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.set(DateTimeFieldType.monthOfYear(), 13); fail(); } catch (IllegalArgumentException ex) {} assertEquals(TEST_TIME1, test.getMillis()); } //----------------------------------------------------------------------- public void testSetDate_int_int_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setDate(2010, 12, 3); assertEquals(2010, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); } public void testSetDate_int_int_int2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.setDate(2010, 13, 3); fail(); } catch (IllegalArgumentException ex) {} assertEquals(TEST_TIME1, test.getMillis()); } //----------------------------------------------------------------------- public void testSetDate_long1() { long setter = new DateTime(2010, 12, 3, 5, 7, 9, 501).getMillis(); MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setDate(setter); assertEquals(2010, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testSetDate_RI1() { DateTime setter = new DateTime(2010, 12, 3, 5, 7, 9, 501); MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setDate(setter); assertEquals(2010, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); } public void testSetDate_RI2() { MutableDateTime test = new MutableDateTime(2010, 7, 8, 12, 24, 48, 501); test.setDate(null); // sets to TEST_TIME_NOW assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(12, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); } public void testSetDate_RI_same() { MutableDateTime setter = new MutableDateTime(2010, 12, 3, 2, 24, 48, 501, DateTimeZone.forID("America/Los_Angeles")); MutableDateTime test = new MutableDateTime(2010, 12, 3, 2, 24, 48, 501, DateTimeZone.forID("America/Los_Angeles")); test.setDate(setter); assertEquals(2010, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); assertEquals(2, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); } public void testSetDate_RI_different1() { MutableDateTime setter = new MutableDateTime(2010, 12, 1, 0, 0, 0, 0, DateTimeZone.forID("America/Los_Angeles")); MutableDateTime test = new MutableDateTime(2010, 12, 3, 2, 24, 48, 501, DateTimeZone.forID("Europe/Moscow")); test.setDate(setter); assertEquals(2010, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); assertEquals(2, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); } public void testSetDate_RI_different2() { MutableDateTime setter = new MutableDateTime(2010, 12, 1, 0, 0, 0, 0, DateTimeZone.forID("Europe/Moscow")); MutableDateTime test = new MutableDateTime(2010, 12, 3, 2, 24, 48, 501, DateTimeZone.forID("America/Los_Angeles")); test.setDate(setter); assertEquals(2010, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(1, test.getDayOfMonth()); assertEquals(2, test.getHourOfDay()); assertEquals(24, test.getMinuteOfHour()); assertEquals(48, test.getSecondOfMinute()); assertEquals(501, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testSetTime_int_int_int_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setTime(5, 6, 7, 8); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(5, test.getHourOfDay()); assertEquals(6, test.getMinuteOfHour()); assertEquals(7, test.getSecondOfMinute()); assertEquals(8, test.getMillisOfSecond()); } public void testSetTime_int_int_int2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.setTime(60, 6, 7, 8); fail(); } catch (IllegalArgumentException ex) {} assertEquals(TEST_TIME1, test.getMillis()); } //----------------------------------------------------------------------- public void testSetTime_long1() { long setter = new DateTime(2010, 12, 3, 5, 7, 9, 11).getMillis(); MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setTime(setter); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(5, test.getHourOfDay()); assertEquals(7, test.getMinuteOfHour()); assertEquals(9, test.getSecondOfMinute()); assertEquals(11, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testSetTime_RI1() { DateTime setter = new DateTime(2010, 12, 3, 5, 7, 9, 11); MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setTime(setter); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(5, test.getHourOfDay()); assertEquals(7, test.getMinuteOfHour()); assertEquals(9, test.getSecondOfMinute()); assertEquals(11, test.getMillisOfSecond()); } public void testSetTime_RI2() { MutableDateTime test = new MutableDateTime(2010, 7, 8, 12, 24, 48, 501); test.setTime(null); // sets to TEST_TIME_NOW, which has no time part assertEquals(2010, test.getYear()); assertEquals(7, test.getMonthOfYear()); assertEquals(8, test.getDayOfMonth()); assertEquals(new DateTime(TEST_TIME_NOW).getHourOfDay(), test.getHourOfDay()); assertEquals(new DateTime(TEST_TIME_NOW).getMinuteOfHour(), test.getMinuteOfHour()); assertEquals(new DateTime(TEST_TIME_NOW).getSecondOfMinute(), test.getSecondOfMinute()); assertEquals(new DateTime(TEST_TIME_NOW).getMillisOfSecond(), test.getMillisOfSecond()); } public void testSetTime_Object3() { DateTime temp = new DateTime(2010, 12, 3, 5, 7, 9, 11); DateTime setter = new DateTime(temp.getMillis(), new MockNullZoneChronology()); MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setTime(setter); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(5, test.getHourOfDay()); assertEquals(7, test.getMinuteOfHour()); assertEquals(9, test.getSecondOfMinute()); assertEquals(11, test.getMillisOfSecond()); } //----------------------------------------------------------------------- public void testSetDateTime_int_int_int_int_int_int_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 12, 24, 48, 501); test.setDateTime(2010, 12, 3, 5, 6, 7, 8); assertEquals(2010, test.getYear()); assertEquals(12, test.getMonthOfYear()); assertEquals(3, test.getDayOfMonth()); assertEquals(5, test.getHourOfDay()); assertEquals(6, test.getMinuteOfHour()); assertEquals(7, test.getSecondOfMinute()); assertEquals(8, test.getMillisOfSecond()); } public void testSetDateTime_int_int_int_int_int_int_int2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.setDateTime(2010, 13, 3, 5, 6, 7, 8); fail(); } catch (IllegalArgumentException ex) { } assertEquals(TEST_TIME1, test.getMillis()); } //----------------------------------------------------------------------- public void testSetYear_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setYear(2010); assertEquals("2010-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetMonthOfYear_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setMonthOfYear(12); assertEquals("2002-12-09T05:06:07.008Z", test.toString()); } public void testSetMonthOfYear_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetDayOfMonth_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setDayOfMonth(17); assertEquals("2002-06-17T05:06:07.008+01:00", test.toString()); } public void testSetDayOfMonth_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setDayOfMonth(31); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetDayOfYear_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setDayOfYear(3); assertEquals("2002-01-03T05:06:07.008Z", test.toString()); } public void testSetDayOfYear_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setDayOfYear(366); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetWeekyear_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setWeekyear(2001); assertEquals("2001-06-10T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetWeekOfWeekyear_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setWeekOfWeekyear(2); assertEquals("2002-01-13T05:06:07.008Z", test.toString()); } public void testSetWeekOfWeekyear_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setWeekOfWeekyear(53); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetDayOfWeek_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setDayOfWeek(5); assertEquals("2002-06-07T05:06:07.008+01:00", test.toString()); } public void testSetDayOfWeek_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setDayOfWeek(8); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetHourOfDay_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setHourOfDay(13); assertEquals("2002-06-09T13:06:07.008+01:00", test.toString()); } public void testSetHourOfDay_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setHourOfDay(24); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetMinuteOfHour_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setMinuteOfHour(13); assertEquals("2002-06-09T05:13:07.008+01:00", test.toString()); } public void testSetMinuteOfHour_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setMinuteOfHour(60); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetMinuteOfDay_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setMinuteOfDay(13); assertEquals("2002-06-09T00:13:07.008+01:00", test.toString()); } public void testSetMinuteOfDay_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setMinuteOfDay(24 * 60); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetSecondOfMinute_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setSecondOfMinute(13); assertEquals("2002-06-09T05:06:13.008+01:00", test.toString()); } public void testSetSecondOfMinute_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setSecondOfMinute(60); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetSecondOfDay_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setSecondOfDay(13); assertEquals("2002-06-09T00:00:13.008+01:00", test.toString()); } public void testSetSecondOfDay_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setSecondOfDay(24 * 60 * 60); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetMilliOfSecond_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setMillisOfSecond(13); assertEquals("2002-06-09T05:06:07.013+01:00", test.toString()); } public void testSetMilliOfSecond_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setMillisOfSecond(1000); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } //----------------------------------------------------------------------- public void testSetMilliOfDay_int1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setMillisOfDay(13); assertEquals("2002-06-09T00:00:00.013+01:00", test.toString()); } public void testSetMilliOfDay_int2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setMillisOfDay(24 * 60 * 60 * 1000); fail(); } catch (IllegalArgumentException ex) {} assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); } } joda-time-2.3/src/test/java/org/joda/time/TestYearMonth_Constructors.java0000644000175000017500000003522611616003375026123 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for YearMonth. * * @author Stephen Colebourne */ public class TestYearMonth_Constructors extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology GREGORIAN_UTC = GregorianChronology.getInstanceUTC(); private static final Chronology GREGORIAN_PARIS = GregorianChronology.getInstance(PARIS); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestYearMonth_Constructors.class); } public TestYearMonth_Constructors(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testParse_noFormatter() throws Throwable { assertEquals(new YearMonth(2010, 6), YearMonth.parse("2010-06-30")); assertEquals(new YearMonth(2010, 1), YearMonth.parse("2010-002")); } public void testParse_formatter() throws Throwable { DateTimeFormatter f = DateTimeFormat.forPattern("yyyy--MM").withChronology(ISOChronology.getInstance(PARIS)); assertEquals(new YearMonth(2010, 6), YearMonth.parse("2010--06", f)); } //----------------------------------------------------------------------- public void testFactory_FromCalendarFields() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); YearMonth expected = new YearMonth(1970, 2); assertEquals(expected, YearMonth.fromCalendarFields(cal)); try { YearMonth.fromCalendarFields(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testFactory_FromDateFields() throws Exception { GregorianCalendar cal = new GregorianCalendar(1970, 1, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 7); YearMonth expected = new YearMonth(1970, 2); assertEquals(expected, YearMonth.fromDateFields(cal.getTime())); try { YearMonth.fromDateFields(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Test constructor () */ public void testConstructor() throws Throwable { YearMonth test = new YearMonth(); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(test, YearMonth.now()); } /** * Test constructor (DateTimeZone) */ public void testConstructor_DateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 30, 23, 59, 0, 0, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris YearMonth test = new YearMonth(LONDON); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(test, YearMonth.now(LONDON)); test = new YearMonth(PARIS); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(7, test.getMonthOfYear()); assertEquals(test, YearMonth.now(PARIS)); } /** * Test constructor (DateTimeZone=null) */ public void testConstructor_nullDateTimeZone() throws Throwable { DateTime dt = new DateTime(2005, 6, 30, 23, 59, 0, 0, LONDON); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); // 23:59 in London is 00:59 the following day in Paris YearMonth test = new YearMonth((DateTimeZone) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); } /** * Test constructor (Chronology) */ public void testConstructor_Chronology() throws Throwable { YearMonth test = new YearMonth(GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(test, YearMonth.now(GREGORIAN_PARIS)); } /** * Test constructor (Chronology=null) */ public void testConstructor_nullChronology() throws Throwable { YearMonth test = new YearMonth((Chronology) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); } //----------------------------------------------------------------------- /** * Test constructor (long) */ public void testConstructor_long1() throws Throwable { YearMonth test = new YearMonth(TEST_TIME1); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); } /** * Test constructor (long) */ public void testConstructor_long2() throws Throwable { YearMonth test = new YearMonth(TEST_TIME2); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long1_Chronology() throws Throwable { YearMonth test = new YearMonth(TEST_TIME1, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); } /** * Test constructor (long, Chronology) */ public void testConstructor_long2_Chronology() throws Throwable { YearMonth test = new YearMonth(TEST_TIME2, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1971, test.getYear()); assertEquals(5, test.getMonthOfYear()); } /** * Test constructor (long, Chronology=null) */ public void testConstructor_long_nullChronology() throws Throwable { YearMonth test = new YearMonth(TEST_TIME1, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); } //----------------------------------------------------------------------- public void testConstructor_Object() throws Throwable { Date date = new Date(TEST_TIME1); YearMonth test = new YearMonth(date); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); } public void testConstructor_nullObject() throws Throwable { YearMonth test = new YearMonth((Object) null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); } public void testConstructor_ObjectString1() throws Throwable { YearMonth test = new YearMonth("1972-12"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1972, test.getYear()); assertEquals(12, test.getMonthOfYear()); } public void testConstructor_ObjectString5() throws Throwable { YearMonth test = new YearMonth("10"); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getYear()); assertEquals(1, test.getMonthOfYear()); } public void testConstructor_ObjectStringEx1() throws Throwable { try { new YearMonth("T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testConstructor_ObjectStringEx2() throws Throwable { try { new YearMonth("T10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testConstructor_ObjectStringEx3() throws Throwable { try { new YearMonth("10:20:30.040"); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testConstructor_ObjectStringEx4() throws Throwable { try { new YearMonth("10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- /** * Test constructor (Object, Chronology) */ public void testConstructor_Object_Chronology() throws Throwable { Date date = new Date(TEST_TIME1); YearMonth test = new YearMonth(date, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); } /** * Test constructor (Object=null, Chronology) */ public void testConstructor_nullObject_Chronology() throws Throwable { YearMonth test = new YearMonth((Object) null, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); } /** * Test constructor (Object, Chronology=null) */ public void testConstructor_Object_nullChronology() throws Throwable { Date date = new Date(TEST_TIME1); YearMonth test = new YearMonth(date, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(4, test.getMonthOfYear()); } /** * Test constructor (Object=null, Chronology=null) */ public void testConstructor_nullObject_nullChronology() throws Throwable { YearMonth test = new YearMonth((Object) null, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); } //----------------------------------------------------------------------- /** * Test constructor (int, int) */ public void testConstructor_int_int() throws Throwable { YearMonth test = new YearMonth(1970, 6); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); try { new YearMonth(Integer.MIN_VALUE, 6); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(Integer.MAX_VALUE, 6); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(1970, 0); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(1970, 13); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, Chronology) */ public void testConstructor_int_int_Chronology() throws Throwable { YearMonth test = new YearMonth(1970, 6, GREGORIAN_PARIS); assertEquals(GREGORIAN_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); try { new YearMonth(Integer.MIN_VALUE, 6, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(Integer.MAX_VALUE, 6, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(1970, 0, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(1970, 13, GREGORIAN_PARIS); fail(); } catch (IllegalArgumentException ex) {} } /** * Test constructor (int, int, Chronology=null) */ public void testConstructor_int_int_nullChronology() throws Throwable { YearMonth test = new YearMonth(1970, 6, null); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutableDateTime_Basics.java0000644000175000017500000010647212200501234025704 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractInstant; import org.joda.time.chrono.BaseChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.UnsupportedDateTimeField; import org.joda.time.field.UnsupportedDurationField; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a JUnit test for MutableDateTime. * * @author Stephen Colebourne */ public class TestMutableDateTime_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutableDateTime_Basics.class); } public TestMutableDateTime_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGet_DateTimeField() { MutableDateTime test = new MutableDateTime(); assertEquals(1, test.get(ISOChronology.getInstance().era())); assertEquals(20, test.get(ISOChronology.getInstance().centuryOfEra())); assertEquals(2, test.get(ISOChronology.getInstance().yearOfCentury())); assertEquals(2002, test.get(ISOChronology.getInstance().yearOfEra())); assertEquals(2002, test.get(ISOChronology.getInstance().year())); assertEquals(6, test.get(ISOChronology.getInstance().monthOfYear())); assertEquals(9, test.get(ISOChronology.getInstance().dayOfMonth())); assertEquals(2002, test.get(ISOChronology.getInstance().weekyear())); assertEquals(23, test.get(ISOChronology.getInstance().weekOfWeekyear())); assertEquals(7, test.get(ISOChronology.getInstance().dayOfWeek())); assertEquals(160, test.get(ISOChronology.getInstance().dayOfYear())); assertEquals(0, test.get(ISOChronology.getInstance().halfdayOfDay())); assertEquals(1, test.get(ISOChronology.getInstance().hourOfHalfday())); assertEquals(1, test.get(ISOChronology.getInstance().clockhourOfDay())); assertEquals(1, test.get(ISOChronology.getInstance().clockhourOfHalfday())); assertEquals(1, test.get(ISOChronology.getInstance().hourOfDay())); assertEquals(0, test.get(ISOChronology.getInstance().minuteOfHour())); assertEquals(60, test.get(ISOChronology.getInstance().minuteOfDay())); assertEquals(0, test.get(ISOChronology.getInstance().secondOfMinute())); assertEquals(60 * 60, test.get(ISOChronology.getInstance().secondOfDay())); assertEquals(0, test.get(ISOChronology.getInstance().millisOfSecond())); assertEquals(60 * 60 * 1000, test.get(ISOChronology.getInstance().millisOfDay())); try { test.get((DateTimeField) null); fail(); } catch (IllegalArgumentException ex) {} } public void testGet_DateTimeFieldType() { MutableDateTime test = new MutableDateTime(); assertEquals(1, test.get(DateTimeFieldType.era())); assertEquals(20, test.get(DateTimeFieldType.centuryOfEra())); assertEquals(2, test.get(DateTimeFieldType.yearOfCentury())); assertEquals(2002, test.get(DateTimeFieldType.yearOfEra())); assertEquals(2002, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); assertEquals(2002, test.get(DateTimeFieldType.weekyear())); assertEquals(23, test.get(DateTimeFieldType.weekOfWeekyear())); assertEquals(7, test.get(DateTimeFieldType.dayOfWeek())); assertEquals(160, test.get(DateTimeFieldType.dayOfYear())); assertEquals(0, test.get(DateTimeFieldType.halfdayOfDay())); assertEquals(1, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(1, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(1, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(1, test.get(DateTimeFieldType.hourOfDay())); assertEquals(0, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(60, test.get(DateTimeFieldType.minuteOfDay())); assertEquals(0, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(60 * 60, test.get(DateTimeFieldType.secondOfDay())); assertEquals(0, test.get(DateTimeFieldType.millisOfSecond())); assertEquals(60 * 60 * 1000, test.get(DateTimeFieldType.millisOfDay())); try { test.get((DateTimeFieldType) null); fail(); } catch (IllegalArgumentException ex) {} } public void testGetMethods() { MutableDateTime test = new MutableDateTime(); assertEquals(ISOChronology.getInstance(), test.getChronology()); assertEquals(LONDON, test.getZone()); assertEquals(TEST_TIME_NOW, test.getMillis()); assertEquals(1, test.getEra()); assertEquals(20, test.getCenturyOfEra()); assertEquals(2, test.getYearOfCentury()); assertEquals(2002, test.getYearOfEra()); assertEquals(2002, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(2002, test.getWeekyear()); assertEquals(23, test.getWeekOfWeekyear()); assertEquals(7, test.getDayOfWeek()); assertEquals(160, test.getDayOfYear()); assertEquals(1, test.getHourOfDay()); assertEquals(0, test.getMinuteOfHour()); assertEquals(60, test.getMinuteOfDay()); assertEquals(0, test.getSecondOfMinute()); assertEquals(60 * 60, test.getSecondOfDay()); assertEquals(0, test.getMillisOfSecond()); assertEquals(60 * 60 * 1000, test.getMillisOfDay()); } public void testEqualsHashCode() { MutableDateTime test1 = new MutableDateTime(TEST_TIME1); MutableDateTime test2 = new MutableDateTime(TEST_TIME1); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); MutableDateTime test3 = new MutableDateTime(TEST_TIME2); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); DateTime test4 = new DateTime(TEST_TIME2); assertEquals(true, test4.equals(test3)); assertEquals(true, test3.equals(test4)); assertEquals(false, test4.equals(test1)); assertEquals(false, test1.equals(test4)); assertEquals(true, test3.hashCode() == test4.hashCode()); assertEquals(false, test1.hashCode() == test4.hashCode()); MutableDateTime test5 = new MutableDateTime(TEST_TIME2); test5.setRounding(ISOChronology.getInstance().millisOfSecond()); assertEquals(true, test5.equals(test3)); assertEquals(true, test5.equals(test4)); assertEquals(true, test3.equals(test5)); assertEquals(true, test4.equals(test5)); assertEquals(true, test3.hashCode() == test5.hashCode()); assertEquals(true, test4.hashCode() == test5.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInstant())); assertEquals(false, test1.equals(new MutableDateTime(TEST_TIME1, GregorianChronology.getInstance()))); assertEquals(true, new MutableDateTime(TEST_TIME1, new MockEqualsChronology()).equals(new MutableDateTime(TEST_TIME1, new MockEqualsChronology()))); assertEquals(false, new MutableDateTime(TEST_TIME1, new MockEqualsChronology()).equals(new MutableDateTime(TEST_TIME1, ISOChronology.getInstance()))); } class MockInstant extends AbstractInstant { public String toString() { return null; } public long getMillis() { return TEST_TIME1; } public Chronology getChronology() { return ISOChronology.getInstance(); } } class MockEqualsChronology extends BaseChronology { private static final long serialVersionUID = 1L; public boolean equals(Object obj) { return obj instanceof MockEqualsChronology; } public DateTimeZone getZone() { return null; } public Chronology withUTC() { return this; } public Chronology withZone(DateTimeZone zone) { return this; } public String toString() { return ""; } } public void testCompareTo() { MutableDateTime test1 = new MutableDateTime(TEST_TIME1); MutableDateTime test1a = new MutableDateTime(TEST_TIME1); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); MutableDateTime test2 = new MutableDateTime(TEST_TIME2); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); MutableDateTime test3 = new MutableDateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); assertEquals(+1, test2.compareTo(new MockInstant())); assertEquals(0, test1.compareTo(new MockInstant())); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} } public void testIsEqual() { MutableDateTime test1 = new MutableDateTime(TEST_TIME1); MutableDateTime test1a = new MutableDateTime(TEST_TIME1); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); MutableDateTime test2 = new MutableDateTime(TEST_TIME2); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); MutableDateTime test3 = new MutableDateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); assertEquals(false, test2.isEqual(new MockInstant())); assertEquals(true, test1.isEqual(new MockInstant())); assertEquals(false, new MutableDateTime(TEST_TIME_NOW + 1).isEqual(null)); assertEquals(true, new MutableDateTime(TEST_TIME_NOW).isEqual(null)); assertEquals(false, new MutableDateTime(TEST_TIME_NOW - 1).isEqual(null)); } public void testIsBefore() { MutableDateTime test1 = new MutableDateTime(TEST_TIME1); MutableDateTime test1a = new MutableDateTime(TEST_TIME1); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); MutableDateTime test2 = new MutableDateTime(TEST_TIME2); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); MutableDateTime test3 = new MutableDateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); assertEquals(false, test2.isBefore(new MockInstant())); assertEquals(false, test1.isBefore(new MockInstant())); assertEquals(false, new MutableDateTime(TEST_TIME_NOW + 1).isBefore(null)); assertEquals(false, new MutableDateTime(TEST_TIME_NOW).isBefore(null)); assertEquals(true, new MutableDateTime(TEST_TIME_NOW - 1).isBefore(null)); } public void testIsAfter() { MutableDateTime test1 = new MutableDateTime(TEST_TIME1); MutableDateTime test1a = new MutableDateTime(TEST_TIME1); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); MutableDateTime test2 = new MutableDateTime(TEST_TIME2); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); MutableDateTime test3 = new MutableDateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); assertEquals(true, test2.isAfter(new MockInstant())); assertEquals(false, test1.isAfter(new MockInstant())); assertEquals(true, new MutableDateTime(TEST_TIME_NOW + 1).isAfter(null)); assertEquals(false, new MutableDateTime(TEST_TIME_NOW).isAfter(null)); assertEquals(false, new MutableDateTime(TEST_TIME_NOW - 1).isAfter(null)); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { MutableDateTime test = new MutableDateTime(TEST_TIME_NOW); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); MutableDateTime result = (MutableDateTime) ois.readObject(); ois.close(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToString() { MutableDateTime test = new MutableDateTime(TEST_TIME_NOW); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString()); test = new MutableDateTime(TEST_TIME_NOW, PARIS); assertEquals("2002-06-09T02:00:00.000+02:00", test.toString()); } public void testToString_String() { MutableDateTime test = new MutableDateTime(TEST_TIME_NOW); assertEquals("2002 01", test.toString("yyyy HH")); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString((String) null)); } public void testToString_String_String() { MutableDateTime test = new MutableDateTime(TEST_TIME_NOW); assertEquals("Sun 9/6", test.toString("EEE d/M", Locale.ENGLISH)); assertEquals("dim. 9/6", test.toString("EEE d/M", Locale.FRENCH)); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString(null, Locale.ENGLISH)); assertEquals("Sun 9/6", test.toString("EEE d/M", null)); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString(null, null)); } public void testToString_DTFormatter() { MutableDateTime test = new MutableDateTime(TEST_TIME_NOW); assertEquals("2002 01", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("2002-06-09T01:00:00.000+01:00", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- public void testToInstant() { MutableDateTime test = new MutableDateTime(TEST_TIME1); Instant result = test.toInstant(); assertEquals(TEST_TIME1, result.getMillis()); } public void testToDateTime() { MutableDateTime test = new MutableDateTime(TEST_TIME1, PARIS); DateTime result = test.toDateTime(); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); } public void testToDateTimeISO() { MutableDateTime test = new MutableDateTime(TEST_TIME1, PARIS); DateTime result = test.toDateTimeISO(); assertSame(DateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); } public void testToDateTime_DateTimeZone() { MutableDateTime test = new MutableDateTime(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(LONDON); assertEquals(test.getMillis(), result.getMillis()); assertEquals(test.getChronology(), result.getChronology()); assertEquals(LONDON, result.getZone()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime(PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(PARIS, result.getZone()); test = new MutableDateTime(TEST_TIME1, GregorianChronology.getInstance(PARIS)); result = test.toMutableDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GregorianChronology.getInstance(LONDON), result.getChronology()); test = new MutableDateTime(TEST_TIME1, PARIS); result = test.toMutableDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(LONDON, result.getZone()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(LONDON, result.getZone()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToDateTime_Chronology() { MutableDateTime test = new MutableDateTime(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(ISOChronology.getInstance()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime(GregorianChronology.getInstance(PARIS)); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GregorianChronology.getInstance(PARIS), result.getChronology()); test = new MutableDateTime(TEST_TIME1, GregorianChronology.getInstance(PARIS)); result = test.toMutableDateTime((Chronology) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime((Chronology) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToMutableDateTime() { MutableDateTime test = new MutableDateTime(TEST_TIME1, PARIS); MutableDateTime result = test.toMutableDateTime(); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); } public void testToMutableDateTimeISO() { MutableDateTime test = new MutableDateTime(TEST_TIME1, PARIS); MutableDateTime result = test.toMutableDateTimeISO(); assertSame(MutableDateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); assertNotSame(test, result); } public void testToMutableDateTime_DateTimeZone() { MutableDateTime test = new MutableDateTime(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(LONDON); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(LONDON), result.getChronology()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime(PARIS); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); test = new MutableDateTime(TEST_TIME1, PARIS); result = test.toMutableDateTime((DateTimeZone) null); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime((DateTimeZone) null); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToMutableDateTime_Chronology() { MutableDateTime test = new MutableDateTime(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(ISOChronology.getInstance()); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime(GregorianChronology.getInstance(PARIS)); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GregorianChronology.getInstance(PARIS), result.getChronology()); test = new MutableDateTime(TEST_TIME1, GregorianChronology.getInstance(PARIS)); result = test.toMutableDateTime((Chronology) null); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new MutableDateTime(TEST_TIME1); result = test.toMutableDateTime((Chronology) null); assertTrue(test != result); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToDate() { MutableDateTime test = new MutableDateTime(TEST_TIME1); Date result = test.toDate(); assertEquals(test.getMillis(), result.getTime()); } public void testToCalendar_Locale() { MutableDateTime test = new MutableDateTime(TEST_TIME1); Calendar result = test.toCalendar(null); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/London"), result.getTimeZone()); test = new MutableDateTime(TEST_TIME1, PARIS); result = test.toCalendar(null); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/Paris"), result.getTimeZone()); test = new MutableDateTime(TEST_TIME1, PARIS); result = test.toCalendar(Locale.UK); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/Paris"), result.getTimeZone()); } public void testToGregorianCalendar() { MutableDateTime test = new MutableDateTime(TEST_TIME1); GregorianCalendar result = test.toGregorianCalendar(); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/London"), result.getTimeZone()); test = new MutableDateTime(TEST_TIME1, PARIS); result = test.toGregorianCalendar(); assertEquals(test.getMillis(), result.getTime().getTime()); assertEquals(TimeZone.getTimeZone("Europe/Paris"), result.getTimeZone()); } public void testClone() { MutableDateTime test = new MutableDateTime(TEST_TIME1); MutableDateTime result = (MutableDateTime) test.clone(); assertEquals(true, test.equals(result)); assertEquals(true, test != result); } public void testCopy() { MutableDateTime test = new MutableDateTime(TEST_TIME1); MutableDateTime result = test.copy(); assertEquals(true, test.equals(result)); assertEquals(true, test != result); } public void testRounding1() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setRounding(ISOChronology.getInstance().hourOfDay()); assertEquals("2002-06-09T05:00:00.000+01:00", test.toString()); assertEquals(MutableDateTime.ROUND_FLOOR, test.getRoundingMode()); assertEquals(ISOChronology.getInstance().hourOfDay(), test.getRoundingField()); } public void testRounding2() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_CEILING); assertEquals("2002-06-09T06:00:00.000+01:00", test.toString()); assertEquals(MutableDateTime.ROUND_CEILING, test.getRoundingMode()); assertEquals(ISOChronology.getInstance().hourOfDay(), test.getRoundingField()); } public void testRounding3() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_HALF_CEILING); assertEquals("2002-06-09T05:00:00.000+01:00", test.toString()); assertEquals(MutableDateTime.ROUND_HALF_CEILING, test.getRoundingMode()); assertEquals(ISOChronology.getInstance().hourOfDay(), test.getRoundingField()); test = new MutableDateTime(2002, 6, 9, 5, 30, 0, 0); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_HALF_CEILING); assertEquals("2002-06-09T06:00:00.000+01:00", test.toString()); } public void testRounding4() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_HALF_FLOOR); assertEquals("2002-06-09T05:00:00.000+01:00", test.toString()); assertEquals(MutableDateTime.ROUND_HALF_FLOOR, test.getRoundingMode()); assertEquals(ISOChronology.getInstance().hourOfDay(), test.getRoundingField()); test = new MutableDateTime(2002, 6, 9, 5, 30, 0, 0); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_HALF_FLOOR); assertEquals("2002-06-09T05:00:00.000+01:00", test.toString()); } public void testRounding5() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_HALF_EVEN); assertEquals("2002-06-09T05:00:00.000+01:00", test.toString()); assertEquals(MutableDateTime.ROUND_HALF_EVEN, test.getRoundingMode()); assertEquals(ISOChronology.getInstance().hourOfDay(), test.getRoundingField()); test = new MutableDateTime(2002, 6, 9, 5, 30, 0, 0); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_HALF_EVEN); assertEquals("2002-06-09T06:00:00.000+01:00", test.toString()); test = new MutableDateTime(2002, 6, 9, 4, 30, 0, 0); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_HALF_EVEN); assertEquals("2002-06-09T04:00:00.000+01:00", test.toString()); } public void testRounding6() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_NONE); assertEquals("2002-06-09T05:06:07.008+01:00", test.toString()); assertEquals(MutableDateTime.ROUND_NONE, test.getRoundingMode()); assertEquals(null, test.getRoundingField()); } public void testRounding7() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); try { test.setRounding(ISOChronology.getInstance().hourOfDay(), -1); fail(); } catch (IllegalArgumentException ex) {} } public void testRounding8() { MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8); assertEquals(MutableDateTime.ROUND_NONE, test.getRoundingMode()); assertEquals(null, test.getRoundingField()); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_CEILING); assertEquals(MutableDateTime.ROUND_CEILING, test.getRoundingMode()); assertEquals(ISOChronology.getInstance().hourOfDay(), test.getRoundingField()); test.setRounding(ISOChronology.getInstance().hourOfDay(), MutableDateTime.ROUND_NONE); assertEquals(MutableDateTime.ROUND_NONE, test.getRoundingMode()); assertEquals(null, test.getRoundingField()); test.setRounding(null, -1); assertEquals(MutableDateTime.ROUND_NONE, test.getRoundingMode()); assertEquals(null, test.getRoundingField()); test.setRounding(ISOChronology.getInstance().hourOfDay()); assertEquals(MutableDateTime.ROUND_FLOOR, test.getRoundingMode()); assertEquals(ISOChronology.getInstance().hourOfDay(), test.getRoundingField()); test.setRounding(null); assertEquals(MutableDateTime.ROUND_NONE, test.getRoundingMode()); assertEquals(null, test.getRoundingField()); } //----------------------------------------------------------------------- public void testProperty() { MutableDateTime test = new MutableDateTime(); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek())); assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute())); assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond())); DateTimeFieldType bad = new DateTimeFieldType("bad") { private static final long serialVersionUID = 1L; public DurationFieldType getDurationType() { return DurationFieldType.weeks(); } public DurationFieldType getRangeDurationType() { return null; } public DateTimeField getField(Chronology chronology) { return UnsupportedDateTimeField.getInstance(this, UnsupportedDurationField.getInstance(getDurationType())); } }; try { test.property(bad); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } } joda-time-2.3/src/test/java/org/joda/time/TestSerialization.java0000644000175000017500000004737112200501234024231 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; import org.joda.time.field.UnsupportedDateTimeField; import org.joda.time.field.UnsupportedDurationField; /** * This class is a Junit unit test for serialization. * * @author Stephen Colebourne */ public class TestSerialization extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; // private static class MockDelegatedDurationField extends DelegatedDurationField implements Serializable { // private static final long serialVersionUID = 1878496002811998493L; // public MockDelegatedDurationField() { // super(MillisDurationField.INSTANCE); // } // } private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestSerialization.class); } public TestSerialization(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testSerializedInstant() throws Exception { Instant test = new Instant(); loadAndCompare(test, "Instant", false); inlineCompare(test, false); } public void testSerializedDateTime() throws Exception { DateTime test = new DateTime(); loadAndCompare(test, "DateTime", false); inlineCompare(test, false); } public void testSerializedDateTimeProperty() throws Exception { DateTime.Property test = new DateTime().hourOfDay(); loadAndCompare(test, "DateTimeProperty", false); inlineCompare(test, false); } public void testSerializedMutableDateTime() throws Exception { MutableDateTime test = new MutableDateTime(); loadAndCompare(test, "MutableDateTime", false); inlineCompare(test, false); } public void testSerializedMutableDateTimeProperty() throws Exception { MutableDateTime.Property test = new MutableDateTime().hourOfDay(); loadAndCompare(test, "MutableDateTimeProperty", false); inlineCompare(test, false); } @SuppressWarnings("deprecation") public void testSerializedDateMidnight() throws Exception { DateMidnight test = new DateMidnight(); loadAndCompare(test, "DateMidnight", false); inlineCompare(test, false); } @SuppressWarnings("deprecation") public void testSerializedDateMidnightProperty() throws Exception { DateMidnight.Property test = new DateMidnight().monthOfYear(); loadAndCompare(test, "DateMidnightProperty", false); inlineCompare(test, false); } public void testSerializedLocalDate() throws Exception { LocalDate test = new LocalDate(); loadAndCompare(test, "LocalDate", false); inlineCompare(test, false); } public void testSerializedLocalDateBuddhist() throws Exception { LocalDate test = new LocalDate(BuddhistChronology.getInstanceUTC()); loadAndCompare(test, "LocalDateBuddhist", false); inlineCompare(test, false); } public void testSerializedLocalTime() throws Exception { LocalTime test = new LocalTime(); loadAndCompare(test, "LocalTime", false); inlineCompare(test, false); } public void testSerializedLocalDateTime() throws Exception { LocalDateTime test = new LocalDateTime(); loadAndCompare(test, "LocalDateTime", false); inlineCompare(test, false); } @SuppressWarnings("deprecation") public void testSerializedYearMonthDay() throws Exception { YearMonthDay test = new YearMonthDay(); loadAndCompare(test, "YearMonthDay", false); inlineCompare(test, false); } @SuppressWarnings("deprecation") public void testSerializedTimeOfDay() throws Exception { TimeOfDay test = new TimeOfDay(); loadAndCompare(test, "TimeOfDay", false); inlineCompare(test, false); } public void testSerializedDateTimeZoneUTC() throws Exception { DateTimeZone test = DateTimeZone.UTC; loadAndCompare(test, "DateTimeZoneUTC", true); inlineCompare(test, true); } public void testSerializedDateTimeZone() throws Exception { // have to re-get the zone, as TestDateTimeZone may have // changed the cache, or a SoftReference may have got cleared DateTimeZone test = DateTimeZone.forID("Europe/Paris"); loadAndCompare(test, "DateTimeZone", true); inlineCompare(test, true); } public void testDuration() throws Exception { Duration test = Duration.millis(12345); loadAndCompare(test, "Duration", false); inlineCompare(test, false); } public void testSerializedCopticChronology() throws Exception { CopticChronology test = CopticChronology.getInstance(LONDON); loadAndCompare(test, "CopticChronology", true); inlineCompare(test, true); } public void testSerializedISOChronology() throws Exception { ISOChronology test = ISOChronology.getInstance(PARIS); loadAndCompare(test, "ISOChronology", true); inlineCompare(test, true); } public void testSerializedGJChronology() throws Exception { GJChronology test = GJChronology.getInstance(TOKYO); loadAndCompare(test, "GJChronology", true); inlineCompare(test, true); } public void testSerializedGJChronologyChangedInternals() throws Exception { GJChronology test = GJChronology.getInstance(PARIS, 123L, 2); loadAndCompare(test, "GJChronologyChangedInternals", true); inlineCompare(test, true); } public void testSerializedGregorianChronology() throws Exception { GregorianChronology test = GregorianChronology.getInstance(PARIS); loadAndCompare(test, "GregorianChronology", true); inlineCompare(test, true); } public void testSerializedJulianChronology() throws Exception { JulianChronology test = JulianChronology.getInstance(PARIS); loadAndCompare(test, "JulianChronology", true); inlineCompare(test, true); } public void testSerializedBuddhistChronology() throws Exception { BuddhistChronology test = BuddhistChronology.getInstance(PARIS); loadAndCompare(test, "BuddhistChronology", true); inlineCompare(test, true); } public void testSerializedPeriodType() throws Exception { PeriodType test = PeriodType.dayTime(); loadAndCompare(test, "PeriodType", false); inlineCompare(test, false); } public void testSerializedDateTimeFieldType() throws Exception { DateTimeFieldType test = DateTimeFieldType.clockhourOfDay(); loadAndCompare(test, "DateTimeFieldType", true); inlineCompare(test, true); } public void testSerializedUnsupportedDateTimeField() throws Exception { UnsupportedDateTimeField test = UnsupportedDateTimeField.getInstance( DateTimeFieldType.year(), UnsupportedDurationField.getInstance(DurationFieldType.years())); loadAndCompare(test, "UnsupportedDateTimeField", true); inlineCompare(test, true); } private void loadAndCompare(Serializable test, String filename, boolean same) throws Exception { FileInputStream fis = new FileInputStream("src/test/resources/" + filename + ".dat"); ObjectInputStream ois = new ObjectInputStream(fis); Object obj = ois.readObject(); ois.close(); if (same) { assertSame(test, obj); } else { assertEquals(test, obj); } // try { // fis = new FileInputStream("src/test/resources/" + filename + "2.dat"); // ois = new ObjectInputStream(fis); // obj = ois.readObject(); // ois.close(); // if (same) { // assertSame(test, obj); // } else { // assertEquals(test, obj); // } // } catch (FileNotFoundException ex) { // // ignore // } } public void inlineCompare(Serializable test, boolean same) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); Object obj = ois.readObject(); ois.close(); if (same) { assertSame(test, obj); } else { assertEquals(test, obj); } } // //----------------------------------------------------------------------- // public void testStoreSerializedInstant() throws Exception { // Instant test = new Instant(); // store(test, "Instant.dat"); // } // // public void testStoreSerializedDateTime() throws Exception { // DateTime test = new DateTime(); // store(test, "DateTime.dat"); // } // // public void testStoreSerializedMutableDateTime() throws Exception { // MutableDateTime test = new MutableDateTime(); // store(test, "MutableDateTime.dat"); // } // // public void testStoreSerializedDateMidnight() throws Exception { // DateMidnight test = new DateMidnight(); // store(test, "DateMidnight.dat"); // } // // public void testStoreSerializedLocalDate() throws Exception { // LocalDate test = new LocalDate(); // store(test, "LocalDate.dat"); // } // // public void testStoreSerializedLocalDateBuddhist() throws Exception { // LocalDate test = new LocalDate(BuddhistChronology.getInstanceUTC()); // store(test, "LocalDateBuddhist.dat"); // } // // public void testStoreSerializedLocalTime() throws Exception { // LocalTime test = new LocalTime(); // store(test, "LocalTime.dat"); // } // // public void testStoreSerializedLocalDateTime() throws Exception { // LocalDateTime test = new LocalDateTime(); // store(test, "LocalDateTime.dat"); // } // // public void testStoreSerializedYearMonthDay() throws Exception { // YearMonthDay test = new YearMonthDay(); // store(test, "YearMonthDay.dat"); // } // // public void testStoreSerializedYearMonthDayProperty() throws Exception { // YearMonthDay.Property test = new YearMonthDay().monthOfYear(); // store(test, "YearMonthDayProperty.dat"); // } // // public void testStoreSerializedTimeOfDay() throws Exception { // TimeOfDay test = new TimeOfDay(); // store(test, "TimeOfDay.dat"); // } // // public void testStoreSerializedTimeOfDayProperty() throws Exception { // TimeOfDay.Property test = new TimeOfDay().hourOfDay(); // store(test, "TimeOfDayProperty.dat"); // } // // public void testStoreSerializedDateTimeZoneUTC() throws Exception { // DateTimeZone test = DateTimeZone.UTC; // store(test, "DateTimeZoneUTC.dat"); // } // // public void testStoreSerializedDateTimeZone() throws Exception { // DateTimeZone test = PARIS; // store(test, "DateTimeZone.dat"); // } // // public void testStoreSerializedCopticChronology() throws Exception { // CopticChronology test = CopticChronology.getInstance(LONDON); // store(test, "CopticChronology.dat"); // } // // public void testStoreSerializedISOChronology() throws Exception { // ISOChronology test = ISOChronology.getInstance(PARIS); // store(test, "ISOChronology.dat"); // } // // public void testStoreSerializedGJChronology() throws Exception { // GJChronology test = GJChronology.getInstance(TOKYO); // store(test, "GJChronology.dat"); // } // // // Format changed in v1.2 - min days in first week not deserialized in v1.0/1.1 // public void testStoreSerializedGJChronologyChangedInternals() throws Exception { // GJChronology test = GJChronology.getInstance(PARIS, 123L, 2); // store(test, "GJChronologyChangedInternals.dat"); // } // // public void testStoreSerializedGregorianChronology() throws Exception { // GregorianChronology test = GregorianChronology.getInstance(PARIS); // store(test, "GregorianChronology.dat"); // } // // public void testStoreSerializedJulianChronology() throws Exception { // JulianChronology test = JulianChronology.getInstance(PARIS); // store(test, "JulianChronology.dat"); // } // // public void testStoreSerializedBuddhistChronology() throws Exception { // BuddhistChronology test = BuddhistChronology.getInstance(PARIS); // store(test, "BuddhistChronology.dat"); // } // // public void testStoreSerializedPeriodType() throws Exception { // PeriodType test = PeriodType.dayTime(); // store(test, "PeriodType.dat"); // } // // public void testStoreSerializedDateTimeFieldType() throws Exception { // DateTimeFieldType test = DateTimeFieldType.clockhourOfDay(); // store(test, "DateTimeFieldType.dat"); // } // // public void testStoreSerializedUnsupportedDateTimeField() throws Exception { // UnsupportedDateTimeField test = UnsupportedDateTimeField.getInstance( // DateTimeFieldType.year(), // UnsupportedDurationField.getInstance(DurationFieldType.years())); // store(test, "UnsupportedDateTimeField.dat"); // } // // public void testStoreSerializedDurationFieldType() throws Exception { // DurationFieldType test = DurationFieldType.MINUTES_TYPE; // store(test, "DurationFieldType.dat"); // } // // public void testStoreSerializedMillisDurationField() throws Exception { // MillisDurationField test = (MillisDurationField) MillisDurationField.INSTANCE; // store(test, "MillisDurationField.dat"); // } // // public void testStoreSerializedDelegatedDurationField() throws Exception { // DelegatedDurationField test = new MockDelegatedDurationField(); // store(test, "DelegatedDurationField.dat"); // } // // public void testStoreSerializedUnsupportedDurationField() throws Exception { // UnsupportedDurationField test = UnsupportedDurationField.getInstance(DurationFieldType.eras()); // store(test, "UnsupportedDurationField.dat"); // } // // format changed (properly defined) in v1.1 // public void testStoreSerializedDateTimeProperty() throws Exception { // DateTime.Property test = new DateTime().hourOfDay(); // store(test, "DateTimeProperty.dat"); // } // // public void testStoreSerializedMutableDateTimeProperty() throws Exception { // MutableDateTime.Property test = new MutableDateTime().hourOfDay(); // store(test, "MutableDateTimeProperty.dat"); // } // // public void testStoreSerializedDateMidnightProperty() throws Exception { // DateMidnight.Property test = new DateMidnight().monthOfYear(); // store(test, "DateMidnightProperty.dat"); // } // // public void testStoreSerializedDateMidnightProperty() throws Exception { // Duration test = Duration.millis(12345); // store(test, "Duration.dat"); // } // private void store(Serializable test, String filename) throws Exception { // FileOutputStream fos = new FileOutputStream("src/test/resources/" + filename); // ObjectOutputStream oos = new ObjectOutputStream(fos); // try { // oos.writeObject(test); // } finally { // oos.close(); // } // oos.close(); // } } joda-time-2.3/src/test/java/org/joda/time/TestDuration_Basics.java0000644000175000017500000010014111564251363024467 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractDuration; import org.joda.time.base.BaseDuration; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for Duration. * * @author Stephen Colebourne */ public class TestDuration_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDuration_Basics.class); } public TestDuration_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGetMillis() { Duration test = new Duration(0L); assertEquals(0, test.getMillis()); test = new Duration(1234567890L); assertEquals(1234567890L, test.getMillis()); } public void testEqualsHashCode() { Duration test1 = new Duration(123L); Duration test2 = new Duration(123L); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); Duration test3 = new Duration(321L); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockDuration(123L))); } class MockDuration extends AbstractDuration { private final long iValue; public MockDuration(long value) { super(); iValue = value; } public long getMillis() { return iValue; } } public void testCompareTo() { Duration test1 = new Duration(123L); Duration test1a = new Duration(123L); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); Duration test2 = new Duration(321L); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); assertEquals(+1, test2.compareTo(new MockDuration(123L))); assertEquals(0, test1.compareTo(new MockDuration(123L))); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Long(123L)); // fail(); // } catch (ClassCastException ex) {} } public void testIsEqual() { Duration test1 = new Duration(123L); Duration test1a = new Duration(123L); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); Duration test2 = new Duration(321L); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); assertEquals(false, test2.isEqual(new MockDuration(123L))); assertEquals(true, test1.isEqual(new MockDuration(123L))); assertEquals(false, test1.isEqual(null)); assertEquals(true, new Duration(0L).isEqual(null)); } public void testIsBefore() { Duration test1 = new Duration(123L); Duration test1a = new Duration(123L); assertEquals(false, test1.isShorterThan(test1a)); assertEquals(false, test1a.isShorterThan(test1)); assertEquals(false, test1.isShorterThan(test1)); assertEquals(false, test1a.isShorterThan(test1a)); Duration test2 = new Duration(321L); assertEquals(true, test1.isShorterThan(test2)); assertEquals(false, test2.isShorterThan(test1)); assertEquals(false, test2.isShorterThan(new MockDuration(123L))); assertEquals(false, test1.isShorterThan(new MockDuration(123L))); assertEquals(false, test1.isShorterThan(null)); assertEquals(false, new Duration(0L).isShorterThan(null)); } public void testIsAfter() { Duration test1 = new Duration(123L); Duration test1a = new Duration(123L); assertEquals(false, test1.isLongerThan(test1a)); assertEquals(false, test1a.isLongerThan(test1)); assertEquals(false, test1.isLongerThan(test1)); assertEquals(false, test1a.isLongerThan(test1a)); Duration test2 = new Duration(321L); assertEquals(false, test1.isLongerThan(test2)); assertEquals(true, test2.isLongerThan(test1)); assertEquals(true, test2.isLongerThan(new MockDuration(123L))); assertEquals(false, test1.isLongerThan(new MockDuration(123L))); assertEquals(true, test1.isLongerThan(null)); assertEquals(false, new Duration(0L).isLongerThan(null)); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Duration test = new Duration(123L); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Duration result = (Duration) ois.readObject(); ois.close(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testGetStandardSeconds() { Duration test = new Duration(0L); assertEquals(0, test.getStandardSeconds()); test = new Duration(1L); assertEquals(0, test.getStandardSeconds()); test = new Duration(999L); assertEquals(0, test.getStandardSeconds()); test = new Duration(1000L); assertEquals(1, test.getStandardSeconds()); test = new Duration(1001L); assertEquals(1, test.getStandardSeconds()); test = new Duration(1999L); assertEquals(1, test.getStandardSeconds()); test = new Duration(2000L); assertEquals(2, test.getStandardSeconds()); test = new Duration(-1L); assertEquals(0, test.getStandardSeconds()); test = new Duration(-999L); assertEquals(0, test.getStandardSeconds()); test = new Duration(-1000L); assertEquals(-1, test.getStandardSeconds()); } //----------------------------------------------------------------------- public void testToString() { long length = (365L + 2L * 30L + 3L * 7L + 4L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 845L; Duration test = new Duration(length); assertEquals("PT" + (length / 1000) + "." + (length % 1000) + "S", test.toString()); assertEquals("PT0S", new Duration(0L).toString()); assertEquals("PT10S", new Duration(10000L).toString()); assertEquals("PT1S", new Duration(1000L).toString()); assertEquals("PT12.345S", new Duration(12345L).toString()); assertEquals("PT-12.345S", new Duration(-12345L).toString()); assertEquals("PT-1.123S", new Duration(-1123L).toString()); assertEquals("PT-0.123S", new Duration(-123L).toString()); assertEquals("PT-0.012S", new Duration(-12L).toString()); assertEquals("PT-0.001S", new Duration(-1L).toString()); } //----------------------------------------------------------------------- public void testToDuration1() { Duration test = new Duration(123L); Duration result = test.toDuration(); assertSame(test, result); } public void testToDuration2() { MockDuration test = new MockDuration(123L); Duration result = test.toDuration(); assertNotSame(test, result); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToStandardDays() { Duration test = new Duration(0L); assertEquals(Days.days(0), test.toStandardDays()); test = new Duration(1L); assertEquals(Days.days(0), test.toStandardDays()); test = new Duration(24 * 60 * 60000L - 1); assertEquals(Days.days(0), test.toStandardDays()); test = new Duration(24 * 60 * 60000L); assertEquals(Days.days(1), test.toStandardDays()); test = new Duration(24 * 60 * 60000L + 1); assertEquals(Days.days(1), test.toStandardDays()); test = new Duration(2 * 24 * 60 * 60000L - 1); assertEquals(Days.days(1), test.toStandardDays()); test = new Duration(2 * 24 * 60 * 60000L); assertEquals(Days.days(2), test.toStandardDays()); test = new Duration(-1L); assertEquals(Days.days(0), test.toStandardDays()); test = new Duration(-24 * 60 * 60000L + 1); assertEquals(Days.days(0), test.toStandardDays()); test = new Duration(-24 * 60 * 60000L); assertEquals(Days.days(-1), test.toStandardDays()); } public void testToStandardDays_overflow() { Duration test = new Duration((((long) Integer.MAX_VALUE) + 1) * 24L * 60L * 60000L); try { test.toStandardDays(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testToStandardHours() { Duration test = new Duration(0L); assertEquals(Hours.hours(0), test.toStandardHours()); test = new Duration(1L); assertEquals(Hours.hours(0), test.toStandardHours()); test = new Duration(3600000L - 1); assertEquals(Hours.hours(0), test.toStandardHours()); test = new Duration(3600000L); assertEquals(Hours.hours(1), test.toStandardHours()); test = new Duration(3600000L + 1); assertEquals(Hours.hours(1), test.toStandardHours()); test = new Duration(2 * 3600000L - 1); assertEquals(Hours.hours(1), test.toStandardHours()); test = new Duration(2 * 3600000L); assertEquals(Hours.hours(2), test.toStandardHours()); test = new Duration(-1L); assertEquals(Hours.hours(0), test.toStandardHours()); test = new Duration(-3600000L + 1); assertEquals(Hours.hours(0), test.toStandardHours()); test = new Duration(-3600000L); assertEquals(Hours.hours(-1), test.toStandardHours()); } public void testToStandardHours_overflow() { Duration test = new Duration(((long) Integer.MAX_VALUE) * 3600000L + 3600000L); try { test.toStandardHours(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testToStandardMinutes() { Duration test = new Duration(0L); assertEquals(Minutes.minutes(0), test.toStandardMinutes()); test = new Duration(1L); assertEquals(Minutes.minutes(0), test.toStandardMinutes()); test = new Duration(60000L - 1); assertEquals(Minutes.minutes(0), test.toStandardMinutes()); test = new Duration(60000L); assertEquals(Minutes.minutes(1), test.toStandardMinutes()); test = new Duration(60000L + 1); assertEquals(Minutes.minutes(1), test.toStandardMinutes()); test = new Duration(2 * 60000L - 1); assertEquals(Minutes.minutes(1), test.toStandardMinutes()); test = new Duration(2 * 60000L); assertEquals(Minutes.minutes(2), test.toStandardMinutes()); test = new Duration(-1L); assertEquals(Minutes.minutes(0), test.toStandardMinutes()); test = new Duration(-60000L + 1); assertEquals(Minutes.minutes(0), test.toStandardMinutes()); test = new Duration(-60000L); assertEquals(Minutes.minutes(-1), test.toStandardMinutes()); } public void testToStandardMinutes_overflow() { Duration test = new Duration(((long) Integer.MAX_VALUE) * 60000L + 60000L); try { test.toStandardMinutes(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testToStandardSeconds() { Duration test = new Duration(0L); assertEquals(Seconds.seconds(0), test.toStandardSeconds()); test = new Duration(1L); assertEquals(Seconds.seconds(0), test.toStandardSeconds()); test = new Duration(999L); assertEquals(Seconds.seconds(0), test.toStandardSeconds()); test = new Duration(1000L); assertEquals(Seconds.seconds(1), test.toStandardSeconds()); test = new Duration(1001L); assertEquals(Seconds.seconds(1), test.toStandardSeconds()); test = new Duration(1999L); assertEquals(Seconds.seconds(1), test.toStandardSeconds()); test = new Duration(2000L); assertEquals(Seconds.seconds(2), test.toStandardSeconds()); test = new Duration(-1L); assertEquals(Seconds.seconds(0), test.toStandardSeconds()); test = new Duration(-999L); assertEquals(Seconds.seconds(0), test.toStandardSeconds()); test = new Duration(-1000L); assertEquals(Seconds.seconds(-1), test.toStandardSeconds()); } public void testToStandardSeconds_overflow() { Duration test = new Duration(((long) Integer.MAX_VALUE) * 1000L + 1000L); try { test.toStandardSeconds(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testToPeriod() { DateTimeZone zone = DateTimeZone.getDefault(); try { DateTimeZone.setDefault(DateTimeZone.forID("Europe/Paris")); long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration dur = new Duration(length); Period test = dur.toPeriod(); assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } finally { DateTimeZone.setDefault(zone); } } public void testToPeriod_fixedZone() throws Throwable { DateTimeZone zone = DateTimeZone.getDefault(); try { DateTimeZone.setDefault(DateTimeZone.forOffsetHours(2)); long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration dur = new Duration(length); Period test = dur.toPeriod(); assertEquals(0, test.getYears()); // (4 + (3 * 7) + (2 * 30) + 365) == 450 assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((450 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); } finally { DateTimeZone.setDefault(zone); } } //----------------------------------------------------------------------- public void testToPeriod_PeriodType() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); Period result = test.toPeriod(PeriodType.standard().withMillisRemoved()); assertEquals(new Period(test, PeriodType.standard().withMillisRemoved()), result); assertEquals(new Period(test.getMillis(), PeriodType.standard().withMillisRemoved()), result); } //----------------------------------------------------------------------- public void testToPeriod_Chronology() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); Period result = test.toPeriod(ISOChronology.getInstanceUTC()); assertEquals(new Period(test, ISOChronology.getInstanceUTC()), result); assertEquals(new Period(test.getMillis(), ISOChronology.getInstanceUTC()), result); } //----------------------------------------------------------------------- public void testToPeriod_PeriodType_Chronology() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); Period result = test.toPeriod(PeriodType.standard().withMillisRemoved(), ISOChronology.getInstanceUTC()); assertEquals(new Period(test, PeriodType.standard().withMillisRemoved(), ISOChronology.getInstanceUTC()), result); assertEquals(new Period(test.getMillis(), PeriodType.standard().withMillisRemoved(), ISOChronology.getInstanceUTC()), result); } //----------------------------------------------------------------------- public void testToPeriodFrom() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0); Period result = test.toPeriodFrom(dt); assertEquals(new Period(dt, test), result); } //----------------------------------------------------------------------- public void testToPeriodFrom_PeriodType() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0); Period result = test.toPeriodFrom(dt, PeriodType.standard().withMillisRemoved()); assertEquals(new Period(dt, test, PeriodType.standard().withMillisRemoved()), result); } //----------------------------------------------------------------------- public void testToPeriodTo() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0); Period result = test.toPeriodTo(dt); assertEquals(new Period(test, dt), result); } //----------------------------------------------------------------------- public void testToPeriodTo_PeriodType() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0); Period result = test.toPeriodTo(dt, PeriodType.standard().withMillisRemoved()); assertEquals(new Period(test, dt, PeriodType.standard().withMillisRemoved()), result); } //----------------------------------------------------------------------- public void testToIntervalFrom() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0); Interval result = test.toIntervalFrom(dt); assertEquals(new Interval(dt, test), result); } //----------------------------------------------------------------------- public void testToIntervalTo() { long length = (4L + (3L * 7L) + (2L * 30L) + 365L) * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; Duration test = new Duration(length); DateTime dt = new DateTime(2004, 6, 9, 0, 0, 0, 0); Interval result = test.toIntervalTo(dt); assertEquals(new Interval(test, dt), result); } //----------------------------------------------------------------------- public void testWithMillis1() { Duration test = new Duration(123L); Duration result = test.withMillis(123L); assertSame(test, result); } public void testWithMillis2() { Duration test = new Duration(123L); Duration result = test.withMillis(1234567890L); assertEquals(1234567890L, result.getMillis()); } //----------------------------------------------------------------------- public void testWithDurationAdded_long_int1() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(8000L, 1); assertEquals(8123L, result.getMillis()); } public void testWithDurationAdded_long_int2() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(8000L, 2); assertEquals(16123L, result.getMillis()); } public void testWithDurationAdded_long_int3() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(8000L, -1); assertEquals((123L - 8000L), result.getMillis()); } public void testWithDurationAdded_long_int4() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(0L, 1); assertSame(test, result); } public void testWithDurationAdded_long_int5() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(8000L, 0); assertSame(test, result); } //----------------------------------------------------------------------- public void testPlus_long1() { Duration test = new Duration(123L); Duration result = test.plus(8000L); assertEquals(8123L, result.getMillis()); } public void testPlus_long2() { Duration test = new Duration(123L); Duration result = test.plus(0L); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_long1() { Duration test = new Duration(123L); Duration result = test.minus(8000L); assertEquals(123L - 8000L, result.getMillis()); } public void testMinus_long2() { Duration test = new Duration(123L); Duration result = test.minus(0L); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithDurationAdded_RD_int1() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(new Duration(8000L), 1); assertEquals(8123L, result.getMillis()); } public void testWithDurationAdded_RD_int2() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(new Duration(8000L), 2); assertEquals(16123L, result.getMillis()); } public void testWithDurationAdded_RD_int3() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(new Duration(8000L), -1); assertEquals((123L - 8000L), result.getMillis()); } public void testWithDurationAdded_RD_int4() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(new Duration(0L), 1); assertSame(test, result); } public void testWithDurationAdded_RD_int5() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(new Duration(8000L), 0); assertSame(test, result); } public void testWithDurationAdded_RD_int6() { Duration test = new Duration(123L); Duration result = test.withDurationAdded(null, 0); assertSame(test, result); } //----------------------------------------------------------------------- public void testPlus_RD1() { Duration test = new Duration(123L); Duration result = test.plus(new Duration(8000L)); assertEquals(8123L, result.getMillis()); } public void testPlus_RD2() { Duration test = new Duration(123L); Duration result = test.plus(new Duration(0L)); assertSame(test, result); } public void testPlus_RD3() { Duration test = new Duration(123L); Duration result = test.plus(null); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RD1() { Duration test = new Duration(123L); Duration result = test.minus(new Duration(8000L)); assertEquals(123L - 8000L, result.getMillis()); } public void testMinus_RD2() { Duration test = new Duration(123L); Duration result = test.minus(new Duration(0L)); assertSame(test, result); } public void testMinus_RD3() { Duration test = new Duration(123L); Duration result = test.minus(null); assertSame(test, result); } //----------------------------------------------------------------------- public void testMutableDuration() { // no MutableDuration, so... MockMutableDuration test = new MockMutableDuration(123L); assertEquals(123L, test.getMillis()); test.setMillis(2345L); assertEquals(2345L, test.getMillis()); } static class MockMutableDuration extends BaseDuration { public MockMutableDuration(long duration) { super(duration); } public void setMillis(long duration) { super.setMillis(duration); } } } joda-time-2.3/src/test/java/org/joda/time/TestDateTimeZone.java0000644000175000017500000013535212200501234023741 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import java.text.DateFormatSymbols; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.tz.DefaultNameProvider; import org.joda.time.tz.NameProvider; import org.joda.time.tz.Provider; import org.joda.time.tz.UTCProvider; import org.joda.time.tz.ZoneInfoProvider; /** * This class is a JUnit test for DateTimeZone. * * @author Stephen Colebourne */ public class TestDateTimeZone extends TestCase { private static final boolean OLD_JDK; static { String str = System.getProperty("java.version"); boolean old = true; if (str.length() > 3 && str.charAt(0) == '1' && str.charAt(1) == '.' && (str.charAt(2) == '4' || str.charAt(2) == '5' || str.charAt(2) == '6')) { old = false; } OLD_JDK = old; } // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_SUMMER = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-01-09 private long TEST_TIME_WINTER = (y2002days + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // // 2002-04-05 Fri // private long TEST_TIME1 = // (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 12L * DateTimeConstants.MILLIS_PER_HOUR // + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // // // 2003-05-06 Tue // private long TEST_TIME2 = // (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 14L * DateTimeConstants.MILLIS_PER_HOUR // + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private static final Policy RESTRICT; private static final Policy ALLOW; static { // don't call Policy.getPolicy() RESTRICT = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } public boolean implies(ProtectionDomain domain, Permission permission) { if (permission instanceof JodaTimePermission) { return false; } return true; // return super.implies(domain, permission); } }; ALLOW = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } }; } private DateTimeZone zone; private Locale locale; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeZone.class); } public TestDateTimeZone(String name) { super(name); } protected void setUp() throws Exception { locale = Locale.getDefault(); zone = DateTimeZone.getDefault(); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { Locale.setDefault(locale); DateTimeZone.setDefault(zone); } //----------------------------------------------------------------------- public void testDefault() { assertNotNull(DateTimeZone.getDefault()); DateTimeZone.setDefault(PARIS); assertSame(PARIS, DateTimeZone.getDefault()); try { DateTimeZone.setDefault(null); fail(); } catch (IllegalArgumentException ex) {} } public void testDefaultSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeZone.setDefault(PARIS); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } } //----------------------------------------------------------------------- public void testForID_String() { assertEquals(DateTimeZone.getDefault(), DateTimeZone.forID((String) null)); DateTimeZone zone = DateTimeZone.forID("Europe/London"); assertEquals("Europe/London", zone.getID()); zone = DateTimeZone.forID("UTC"); assertSame(DateTimeZone.UTC, zone); zone = DateTimeZone.forID("+00:00"); assertSame(DateTimeZone.UTC, zone); zone = DateTimeZone.forID("+00"); assertSame(DateTimeZone.UTC, zone); zone = DateTimeZone.forID("+01:23"); assertEquals("+01:23", zone.getID()); assertEquals(DateTimeConstants.MILLIS_PER_HOUR + (23L * DateTimeConstants.MILLIS_PER_MINUTE), zone.getOffset(TEST_TIME_SUMMER)); zone = DateTimeZone.forID("-02:00"); assertEquals("-02:00", zone.getID()); assertEquals((-2L * DateTimeConstants.MILLIS_PER_HOUR), zone.getOffset(TEST_TIME_SUMMER)); zone = DateTimeZone.forID("-07:05:34.0"); assertEquals("-07:05:34", zone.getID()); assertEquals((-7L * DateTimeConstants.MILLIS_PER_HOUR) + (-5L * DateTimeConstants.MILLIS_PER_MINUTE) + (-34L * DateTimeConstants.MILLIS_PER_SECOND), zone.getOffset(TEST_TIME_SUMMER)); try { DateTimeZone.forID("SST"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.forID("europe/london"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.forID("Europe/UK"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.forID("+"); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.forID("+0"); fail(); } catch (IllegalArgumentException ex) {} } public void testForID_String_old() { Map map = new LinkedHashMap(); map.put("GMT", "UTC"); map.put("WET", "WET"); map.put("CET", "CET"); map.put("MET", "CET"); map.put("ECT", "CET"); map.put("EET", "EET"); map.put("MIT", "Pacific/Apia"); map.put("HST", "Pacific/Honolulu"); map.put("AST", "America/Anchorage"); map.put("PST", "America/Los_Angeles"); map.put("MST", "America/Denver"); map.put("PNT", "America/Phoenix"); map.put("CST", "America/Chicago"); map.put("EST", "America/New_York"); map.put("IET", "America/Indiana/Indianapolis"); map.put("PRT", "America/Puerto_Rico"); map.put("CNT", "America/St_Johns"); map.put("AGT", "America/Argentina/Buenos_Aires"); map.put("BET", "America/Sao_Paulo"); map.put("ART", "Africa/Cairo"); map.put("CAT", "Africa/Harare"); map.put("EAT", "Africa/Addis_Ababa"); map.put("NET", "Asia/Yerevan"); map.put("PLT", "Asia/Karachi"); map.put("IST", "Asia/Kolkata"); map.put("BST", "Asia/Dhaka"); map.put("VST", "Asia/Ho_Chi_Minh"); map.put("CTT", "Asia/Shanghai"); map.put("JST", "Asia/Tokyo"); map.put("ACT", "Australia/Darwin"); map.put("AET", "Australia/Sydney"); map.put("SST", "Pacific/Guadalcanal"); map.put("NST", "Pacific/Auckland"); for (String key : map.keySet()) { String value = map.get(key); TimeZone juZone = TimeZone.getTimeZone(key); DateTimeZone zone = DateTimeZone.forTimeZone(juZone); assertEquals(value, zone.getID()); // System.out.println(juZone); // System.out.println(juZone.getDisplayName()); // System.out.println(zone); // System.out.println("------"); } } //----------------------------------------------------------------------- public void testForOffsetHours_int() { assertEquals(DateTimeZone.UTC, DateTimeZone.forOffsetHours(0)); assertEquals(DateTimeZone.forID("+03:00"), DateTimeZone.forOffsetHours(3)); assertEquals(DateTimeZone.forID("-02:00"), DateTimeZone.forOffsetHours(-2)); try { DateTimeZone.forOffsetHours(999999); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testForOffsetHoursMinutes_int_int() { assertEquals(DateTimeZone.UTC, DateTimeZone.forOffsetHoursMinutes(0, 0)); assertEquals(DateTimeZone.forID("+23:59"), DateTimeZone.forOffsetHoursMinutes(23, 59)); assertEquals(DateTimeZone.forID("+02:15"), DateTimeZone.forOffsetHoursMinutes(2, 15)); assertEquals(DateTimeZone.forID("+02:00"), DateTimeZone.forOffsetHoursMinutes(2, 0)); try { DateTimeZone.forOffsetHoursMinutes(2, -15); fail(); } catch (IllegalArgumentException ex) {} assertEquals(DateTimeZone.forID("+00:15"), DateTimeZone.forOffsetHoursMinutes(0, 15)); assertEquals(DateTimeZone.forID("+00:00"), DateTimeZone.forOffsetHoursMinutes(0, 0)); assertEquals(DateTimeZone.forID("-00:15"), DateTimeZone.forOffsetHoursMinutes(0, -15)); assertEquals(DateTimeZone.forID("-02:00"), DateTimeZone.forOffsetHoursMinutes(-2, 0)); assertEquals(DateTimeZone.forID("-02:15"), DateTimeZone.forOffsetHoursMinutes(-2, -15)); assertEquals(DateTimeZone.forID("-02:15"), DateTimeZone.forOffsetHoursMinutes(-2, 15)); assertEquals(DateTimeZone.forID("-23:59"), DateTimeZone.forOffsetHoursMinutes(-23, 59)); try { DateTimeZone.forOffsetHoursMinutes(2, 60); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.forOffsetHoursMinutes(-2, 60); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.forOffsetHoursMinutes(24, 0); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.forOffsetHoursMinutes(-24, 0); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testForOffsetMillis_int() { assertSame(DateTimeZone.UTC, DateTimeZone.forOffsetMillis(0)); assertEquals(DateTimeZone.forID("+23:59:59.999"), DateTimeZone.forOffsetMillis((24 * 60 * 60 * 1000) - 1)); assertEquals(DateTimeZone.forID("+03:00"), DateTimeZone.forOffsetMillis(3 * 60 * 60 * 1000)); assertEquals(DateTimeZone.forID("-02:00"), DateTimeZone.forOffsetMillis(-2 * 60 * 60 * 1000)); assertEquals(DateTimeZone.forID("-23:59:59.999"), DateTimeZone.forOffsetMillis((-24 * 60 * 60 * 1000) + 1)); assertEquals(DateTimeZone.forID("+04:45:17.045"), DateTimeZone.forOffsetMillis( 4 * 60 * 60 * 1000 + 45 * 60 * 1000 + 17 * 1000 + 45)); } //----------------------------------------------------------------------- public void testForTimeZone_TimeZone() { assertEquals(DateTimeZone.getDefault(), DateTimeZone.forTimeZone((TimeZone) null)); DateTimeZone zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/London")); assertEquals("Europe/London", zone.getID()); assertSame(DateTimeZone.UTC, DateTimeZone.forTimeZone(TimeZone.getTimeZone("UTC"))); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("+00:00")); assertSame(DateTimeZone.UTC, zone); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+00:00")); assertSame(DateTimeZone.UTC, zone); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+00:00")); assertSame(DateTimeZone.UTC, zone); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+00")); assertSame(DateTimeZone.UTC, zone); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+01:23")); assertEquals("+01:23", zone.getID()); assertEquals(DateTimeConstants.MILLIS_PER_HOUR + (23L * DateTimeConstants.MILLIS_PER_MINUTE), zone.getOffset(TEST_TIME_SUMMER)); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+1:23")); assertEquals("+01:23", zone.getID()); assertEquals(DateTimeConstants.MILLIS_PER_HOUR + (23L * DateTimeConstants.MILLIS_PER_MINUTE), zone.getOffset(TEST_TIME_SUMMER)); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT-02:00")); assertEquals("-02:00", zone.getID()); assertEquals((-2L * DateTimeConstants.MILLIS_PER_HOUR), zone.getOffset(TEST_TIME_SUMMER)); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+2")); assertEquals("+02:00", zone.getID()); assertEquals((2L * DateTimeConstants.MILLIS_PER_HOUR), zone.getOffset(TEST_TIME_SUMMER)); zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("EST")); assertEquals("America/New_York", zone.getID()); } public void testTimeZoneConversion() { TimeZone jdkTimeZone = TimeZone.getTimeZone("GMT-10"); assertEquals("GMT-10:00", jdkTimeZone.getID()); DateTimeZone jodaTimeZone = DateTimeZone.forTimeZone(jdkTimeZone); assertEquals("-10:00", jodaTimeZone.getID()); assertEquals(jdkTimeZone.getRawOffset(), jodaTimeZone.getOffset(0L)); TimeZone convertedTimeZone = jodaTimeZone.toTimeZone(); assertEquals("GMT-10:00", jdkTimeZone.getID()); assertEquals(jdkTimeZone.getID(), convertedTimeZone.getID()); assertEquals(jdkTimeZone.getRawOffset(), convertedTimeZone.getRawOffset()); } //----------------------------------------------------------------------- public void testGetAvailableIDs() { assertTrue(DateTimeZone.getAvailableIDs().contains("UTC")); } //----------------------------------------------------------------------- public void testProvider() { try { assertNotNull(DateTimeZone.getProvider()); Provider provider = DateTimeZone.getProvider(); DateTimeZone.setProvider(null); assertEquals(provider.getClass(), DateTimeZone.getProvider().getClass()); try { DateTimeZone.setProvider(new MockNullIDSProvider()); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.setProvider(new MockEmptyIDSProvider()); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.setProvider(new MockNoUTCProvider()); fail(); } catch (IllegalArgumentException ex) {} try { DateTimeZone.setProvider(new MockBadUTCProvider()); fail(); } catch (IllegalArgumentException ex) {} Provider prov = new MockOKProvider(); DateTimeZone.setProvider(prov); assertSame(prov, DateTimeZone.getProvider()); assertEquals(2, DateTimeZone.getAvailableIDs().size()); assertTrue(DateTimeZone.getAvailableIDs().contains("UTC")); assertTrue(DateTimeZone.getAvailableIDs().contains("Europe/London")); } finally { DateTimeZone.setProvider(null); assertEquals(ZoneInfoProvider.class, DateTimeZone.getProvider().getClass()); } try { System.setProperty("org.joda.time.DateTimeZone.Provider", "org.joda.time.tz.UTCProvider"); DateTimeZone.setProvider(null); assertEquals(UTCProvider.class, DateTimeZone.getProvider().getClass()); } finally { System.getProperties().remove("org.joda.time.DateTimeZone.Provider"); DateTimeZone.setProvider(null); assertEquals(ZoneInfoProvider.class, DateTimeZone.getProvider().getClass()); } PrintStream syserr = System.err; try { System.setProperty("org.joda.time.DateTimeZone.Provider", "xxx"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); DateTimeZone.setProvider(null); assertEquals(ZoneInfoProvider.class, DateTimeZone.getProvider().getClass()); String str = new String(baos.toByteArray()); assertTrue(str.indexOf("java.lang.ClassNotFoundException") >= 0); } finally { System.setErr(syserr); System.getProperties().remove("org.joda.time.DateTimeZone.Provider"); DateTimeZone.setProvider(null); assertEquals(ZoneInfoProvider.class, DateTimeZone.getProvider().getClass()); } } public void testProviderSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeZone.setProvider(new MockOKProvider()); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } } static class MockNullIDSProvider implements Provider { public Set getAvailableIDs() { return null; } public DateTimeZone getZone(String id) { return null; } } static class MockEmptyIDSProvider implements Provider { public Set getAvailableIDs() { return new HashSet(); } public DateTimeZone getZone(String id) { return null; } } static class MockNoUTCProvider implements Provider { public Set getAvailableIDs() { Set set = new HashSet(); set.add("Europe/London"); return set; } public DateTimeZone getZone(String id) { return null; } } static class MockBadUTCProvider implements Provider { public Set getAvailableIDs() { Set set = new HashSet(); set.add("UTC"); set.add("Europe/London"); return set; } public DateTimeZone getZone(String id) { return null; } } static class MockOKProvider implements Provider { public Set getAvailableIDs() { Set set = new HashSet(); set.add("UTC"); set.add("Europe/London"); return set; } public DateTimeZone getZone(String id) { return DateTimeZone.UTC; } } //----------------------------------------------------------------------- public void testNameProvider() { try { assertNotNull(DateTimeZone.getNameProvider()); NameProvider provider = DateTimeZone.getNameProvider(); DateTimeZone.setNameProvider(null); assertEquals(provider.getClass(), DateTimeZone.getNameProvider().getClass()); provider = new MockOKButNullNameProvider(); DateTimeZone.setNameProvider(provider); assertSame(provider, DateTimeZone.getNameProvider()); assertEquals("+00:00", DateTimeZone.UTC.getShortName(TEST_TIME_SUMMER)); assertEquals("+00:00", DateTimeZone.UTC.getName(TEST_TIME_SUMMER)); } finally { DateTimeZone.setNameProvider(null); } try { System.setProperty("org.joda.time.DateTimeZone.NameProvider", "org.joda.time.tz.DefaultNameProvider"); DateTimeZone.setNameProvider(null); assertEquals(DefaultNameProvider.class, DateTimeZone.getNameProvider().getClass()); } finally { System.getProperties().remove("org.joda.time.DateTimeZone.NameProvider"); DateTimeZone.setNameProvider(null); assertEquals(DefaultNameProvider.class, DateTimeZone.getNameProvider().getClass()); } PrintStream syserr = System.err; try { System.setProperty("org.joda.time.DateTimeZone.NameProvider", "xxx"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); DateTimeZone.setNameProvider(null); assertEquals(DefaultNameProvider.class, DateTimeZone.getNameProvider().getClass()); String str = new String(baos.toByteArray()); assertTrue(str.indexOf("java.lang.ClassNotFoundException") >= 0); } finally { System.setErr(syserr); System.getProperties().remove("org.joda.time.DateTimeZone.NameProvider"); DateTimeZone.setNameProvider(null); assertEquals(DefaultNameProvider.class, DateTimeZone.getNameProvider().getClass()); } } public void testNameProviderSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeZone.setNameProvider(new MockOKButNullNameProvider()); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } } static class MockOKButNullNameProvider implements NameProvider { public String getShortName(Locale locale, String id, String nameKey) { return null; } public String getName(Locale locale, String id, String nameKey) { return null; } } //----------------------------------------------------------------------- public void testConstructor() { assertEquals(1, DateTimeZone.class.getDeclaredConstructors().length); assertTrue(Modifier.isProtected(DateTimeZone.class.getDeclaredConstructors()[0].getModifiers())); try { new DateTimeZone(null) { public String getNameKey(long instant) { return null; } public int getOffset(long instant) { return 0; } public int getStandardOffset(long instant) { return 0; } public boolean isFixed() { return false; } public long nextTransition(long instant) { return 0; } public long previousTransition(long instant) { return 0; } public boolean equals(Object object) { return false; } }; } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testGetID() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); assertEquals("Europe/Paris", zone.getID()); } public void testGetNameKey() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); assertEquals("BST", zone.getNameKey(TEST_TIME_SUMMER)); assertEquals("GMT", zone.getNameKey(TEST_TIME_WINTER)); } static final boolean JDK6; static { boolean jdk6 = true; try { DateFormatSymbols.class.getMethod("getInstance", new Class[] {Locale.class}); } catch (Exception ex) { jdk6 = false; } JDK6 = jdk6; } public void testGetShortName() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); assertEquals("BST", zone.getShortName(TEST_TIME_SUMMER)); assertEquals("GMT", zone.getShortName(TEST_TIME_WINTER)); assertEquals("BST", zone.getShortName(TEST_TIME_SUMMER, Locale.ENGLISH)); } public void testGetShortName_berlin() { DateTimeZone berlin = DateTimeZone.forID("Europe/Berlin"); assertEquals("CET", berlin.getShortName(TEST_TIME_WINTER, Locale.ENGLISH)); assertEquals("CEST", berlin.getShortName(TEST_TIME_SUMMER, Locale.ENGLISH)); if (JDK6) { assertEquals("MEZ", berlin.getShortName(TEST_TIME_WINTER, Locale.GERMAN)); assertEquals("MESZ", berlin.getShortName(TEST_TIME_SUMMER, Locale.GERMAN)); } else { assertEquals("CET", berlin.getShortName(TEST_TIME_WINTER, Locale.GERMAN)); assertEquals("CEST", berlin.getShortName(TEST_TIME_SUMMER, Locale.GERMAN)); } } public void testGetShortNameProviderName() { assertEquals(null, DateTimeZone.getNameProvider().getShortName(null, "Europe/London", "BST")); assertEquals(null, DateTimeZone.getNameProvider().getShortName(Locale.ENGLISH, null, "BST")); assertEquals(null, DateTimeZone.getNameProvider().getShortName(Locale.ENGLISH, "Europe/London", null)); assertEquals(null, DateTimeZone.getNameProvider().getShortName(null, null, null)); } public void testGetShortNameNullKey() { DateTimeZone zone = new MockDateTimeZone("Europe/London"); assertEquals("Europe/London", zone.getShortName(TEST_TIME_SUMMER, Locale.ENGLISH)); } public void testGetName() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); assertEquals("British Summer Time", zone.getName(TEST_TIME_SUMMER)); assertEquals("Greenwich Mean Time", zone.getName(TEST_TIME_WINTER)); assertEquals("British Summer Time", zone.getName(TEST_TIME_SUMMER, Locale.ENGLISH)); } public void testGetName_berlin() { DateTimeZone berlin = DateTimeZone.forID("Europe/Berlin"); assertEquals("Central European Time", berlin.getName(TEST_TIME_WINTER, Locale.ENGLISH)); assertEquals("Central European Summer Time", berlin.getName(TEST_TIME_SUMMER, Locale.ENGLISH)); if (JDK6) { assertEquals("Mitteleurop\u00e4ische Zeit", berlin.getName(TEST_TIME_WINTER, Locale.GERMAN)); assertEquals("Mitteleurop\u00e4ische Sommerzeit", berlin.getName(TEST_TIME_SUMMER, Locale.GERMAN)); } else { assertEquals("Zentraleurop\u00e4ische Zeit", berlin.getName(TEST_TIME_WINTER, Locale.GERMAN)); assertEquals("Zentraleurop\u00e4ische Sommerzeit", berlin.getName(TEST_TIME_SUMMER, Locale.GERMAN)); } } public void testGetNameProviderName() { assertEquals(null, DateTimeZone.getNameProvider().getName(null, "Europe/London", "BST")); assertEquals(null, DateTimeZone.getNameProvider().getName(Locale.ENGLISH, null, "BST")); assertEquals(null, DateTimeZone.getNameProvider().getName(Locale.ENGLISH, "Europe/London", null)); assertEquals(null, DateTimeZone.getNameProvider().getName(null, null, null)); } public void testGetNameNullKey() { DateTimeZone zone = new MockDateTimeZone("Europe/London"); assertEquals("Europe/London", zone.getName(TEST_TIME_SUMMER, Locale.ENGLISH)); } static class MockDateTimeZone extends DateTimeZone { public MockDateTimeZone(String id) { super(id); } public String getNameKey(long instant) { return null; // null } public int getOffset(long instant) { return 0; } public int getStandardOffset(long instant) { return 0; } public boolean isFixed() { return false; } public long nextTransition(long instant) { return 0; } public long previousTransition(long instant) { return 0; } public boolean equals(Object object) { return false; } } //----------------------------------------------------------------------- public void testGetOffset_long() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); assertEquals(2L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(TEST_TIME_SUMMER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(TEST_TIME_WINTER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getStandardOffset(TEST_TIME_SUMMER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getStandardOffset(TEST_TIME_WINTER)); assertEquals(2L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffsetFromLocal(TEST_TIME_SUMMER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffsetFromLocal(TEST_TIME_WINTER)); assertEquals(false, zone.isStandardOffset(TEST_TIME_SUMMER)); assertEquals(true, zone.isStandardOffset(TEST_TIME_WINTER)); } public void testGetOffset_RI() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); assertEquals(2L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(new Instant(TEST_TIME_SUMMER))); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(new Instant(TEST_TIME_WINTER))); assertEquals(zone.getOffset(DateTimeUtils.currentTimeMillis()), zone.getOffset(null)); } public void testGetOffsetFixed() { DateTimeZone zone = DateTimeZone.forID("+01:00"); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(TEST_TIME_SUMMER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(TEST_TIME_WINTER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getStandardOffset(TEST_TIME_SUMMER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getStandardOffset(TEST_TIME_WINTER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffsetFromLocal(TEST_TIME_SUMMER)); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffsetFromLocal(TEST_TIME_WINTER)); assertEquals(true, zone.isStandardOffset(TEST_TIME_SUMMER)); assertEquals(true, zone.isStandardOffset(TEST_TIME_WINTER)); } public void testGetOffsetFixed_RI() { DateTimeZone zone = DateTimeZone.forID("+01:00"); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(new Instant(TEST_TIME_SUMMER))); assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(new Instant(TEST_TIME_WINTER))); assertEquals(zone.getOffset(DateTimeUtils.currentTimeMillis()), zone.getOffset(null)); } //----------------------------------------------------------------------- public void testGetMillisKeepLocal() { long millisLondon = TEST_TIME_SUMMER; long millisParis = TEST_TIME_SUMMER - 1L * DateTimeConstants.MILLIS_PER_HOUR; assertEquals(millisLondon, LONDON.getMillisKeepLocal(LONDON, millisLondon)); assertEquals(millisParis, LONDON.getMillisKeepLocal(LONDON, millisParis)); assertEquals(millisLondon, PARIS.getMillisKeepLocal(PARIS, millisLondon)); assertEquals(millisParis, PARIS.getMillisKeepLocal(PARIS, millisParis)); assertEquals(millisParis, LONDON.getMillisKeepLocal(PARIS, millisLondon)); assertEquals(millisLondon, PARIS.getMillisKeepLocal(LONDON, millisParis)); DateTimeZone zone = DateTimeZone.getDefault(); try { DateTimeZone.setDefault(LONDON); assertEquals(millisLondon, PARIS.getMillisKeepLocal(null, millisParis)); } finally { DateTimeZone.setDefault(zone); } } //----------------------------------------------------------------------- public void testIsFixed() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); assertEquals(false, zone.isFixed()); assertEquals(true, DateTimeZone.UTC.isFixed()); } //----------------------------------------------------------------------- public void testTransitionFixed() { DateTimeZone zone = DateTimeZone.forID("+01:00"); assertEquals(TEST_TIME_SUMMER, zone.nextTransition(TEST_TIME_SUMMER)); assertEquals(TEST_TIME_WINTER, zone.nextTransition(TEST_TIME_WINTER)); assertEquals(TEST_TIME_SUMMER, zone.previousTransition(TEST_TIME_SUMMER)); assertEquals(TEST_TIME_WINTER, zone.previousTransition(TEST_TIME_WINTER)); } // //----------------------------------------------------------------------- // public void testIsLocalDateTimeOverlap_Berlin() { // DateTimeZone zone = DateTimeZone.forID("Europe/Berlin"); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 10, 28, 1, 0))); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 10, 28, 1, 59, 59, 99))); // assertEquals(true, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 10, 28, 2, 0))); // assertEquals(true, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 10, 28, 2, 30))); // assertEquals(true, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 10, 28, 2, 59, 59, 99))); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 10, 28, 3, 0))); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 10, 28, 4, 0))); // // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 3, 25, 1, 30))); // before gap // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 3, 25, 2, 30))); // gap // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 3, 25, 3, 30))); // after gap // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 12, 24, 12, 34))); // } // // //----------------------------------------------------------------------- // public void testIsLocalDateTimeOverlap_NewYork() { // DateTimeZone zone = DateTimeZone.forID("America/New_York"); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 11, 4, 0, 0))); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 11, 4, 0, 59, 59, 99))); // assertEquals(true, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 11, 4, 1, 0))); // assertEquals(true, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 11, 4, 1, 30))); // assertEquals(true, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 11, 4, 1, 59, 59, 99))); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 11, 4, 2, 0))); // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 11, 4, 3, 0))); // // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 3, 11, 1, 30))); // before gap // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 3, 11, 2, 30))); // gap // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 3, 11, 3, 30))); // after gap // assertEquals(false, zone.isLocalDateTimeOverlap(new LocalDateTime(2007, 12, 24, 12, 34))); // } //----------------------------------------------------------------------- public void testIsLocalDateTimeGap_Berlin() { DateTimeZone zone = DateTimeZone.forID("Europe/Berlin"); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 1, 0))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 1, 59, 59, 99))); assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 2, 0))); assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 2, 30))); assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 2, 59, 59, 99))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 3, 0))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 4, 0))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 10, 28, 1, 30))); // before overlap assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 10, 28, 2, 30))); // overlap assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 10, 28, 3, 30))); // after overlap assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 12, 24, 12, 34))); } //----------------------------------------------------------------------- public void testIsLocalDateTimeGap_NewYork() { DateTimeZone zone = DateTimeZone.forID("America/New_York"); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 1, 0))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 1, 59, 59, 99))); assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 0))); assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 30))); assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 59, 59, 99))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 3, 0))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 4, 0))); assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 0, 30))); // before overlap assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 1, 30))); // overlap assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 2, 30))); // after overlap assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 12, 24, 12, 34))); } //----------------------------------------------------------------------- public void testToTimeZone() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); TimeZone tz = zone.toTimeZone(); assertEquals("Europe/Paris", tz.getID()); } //----------------------------------------------------------------------- public void testEqualsHashCode() { DateTimeZone zone1 = DateTimeZone.forID("Europe/Paris"); DateTimeZone zone2 = DateTimeZone.forID("Europe/Paris"); assertEquals(true, zone1.equals(zone1)); assertEquals(true, zone1.equals(zone2)); assertEquals(true, zone2.equals(zone1)); assertEquals(true, zone2.equals(zone2)); assertEquals(true, zone1.hashCode() == zone2.hashCode()); DateTimeZone zone3 = DateTimeZone.forID("Europe/London"); assertEquals(true, zone3.equals(zone3)); assertEquals(false, zone1.equals(zone3)); assertEquals(false, zone2.equals(zone3)); assertEquals(false, zone3.equals(zone1)); assertEquals(false, zone3.equals(zone2)); assertEquals(false, zone1.hashCode() == zone3.hashCode()); assertEquals(true, zone3.hashCode() == zone3.hashCode()); DateTimeZone zone4 = DateTimeZone.forID("+01:00"); assertEquals(true, zone4.equals(zone4)); assertEquals(false, zone1.equals(zone4)); assertEquals(false, zone2.equals(zone4)); assertEquals(false, zone3.equals(zone4)); assertEquals(false, zone4.equals(zone1)); assertEquals(false, zone4.equals(zone2)); assertEquals(false, zone4.equals(zone3)); assertEquals(false, zone1.hashCode() == zone4.hashCode()); assertEquals(true, zone4.hashCode() == zone4.hashCode()); DateTimeZone zone5 = DateTimeZone.forID("+02:00"); assertEquals(true, zone5.equals(zone5)); assertEquals(false, zone1.equals(zone5)); assertEquals(false, zone2.equals(zone5)); assertEquals(false, zone3.equals(zone5)); assertEquals(false, zone4.equals(zone5)); assertEquals(false, zone5.equals(zone1)); assertEquals(false, zone5.equals(zone2)); assertEquals(false, zone5.equals(zone3)); assertEquals(false, zone5.equals(zone4)); assertEquals(false, zone1.hashCode() == zone5.hashCode()); assertEquals(true, zone5.hashCode() == zone5.hashCode()); } //----------------------------------------------------------------------- public void testToString() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); assertEquals("Europe/Paris", zone.toString()); assertEquals("UTC", DateTimeZone.UTC.toString()); } //----------------------------------------------------------------------- public void testSerialization1() throws Exception { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(zone); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeZone result = (DateTimeZone) ois.readObject(); ois.close(); assertSame(zone, result); } //----------------------------------------------------------------------- public void testSerialization2() throws Exception { DateTimeZone zone = DateTimeZone.forID("+01:00"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(zone); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeZone result = (DateTimeZone) ois.readObject(); ois.close(); assertSame(zone, result); } public void testCommentParse() throws Exception { // A bug in ZoneInfoCompiler's handling of comments broke Europe/Athens // after 1980. This test is included to make sure it doesn't break again. DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime dt = new DateTime(2005, 5, 5, 20, 10, 15, 0, zone); assertEquals(1115313015000L, dt.getMillis()); } public void testPatchedNameKeysLondon() throws Exception { // the tz database does not have unique name keys [1716305] DateTimeZone zone = DateTimeZone.forID("Europe/London"); DateTime now = new DateTime(2007, 1, 1, 0, 0, 0, 0); String str1 = zone.getName(now.getMillis()); String str2 = zone.getName(now.plusMonths(6).getMillis()); assertEquals(false, str1.equals(str2)); } public void testPatchedNameKeysSydney() throws Exception { // the tz database does not have unique name keys [1716305] DateTimeZone zone = DateTimeZone.forID("Australia/Sydney"); DateTime now = new DateTime(2007, 1, 1, 0, 0, 0, 0); String str1 = zone.getName(now.getMillis()); String str2 = zone.getName(now.plusMonths(6).getMillis()); assertEquals(false, str1.equals(str2)); } public void testPatchedNameKeysSydneyHistoric() throws Exception { // the tz database does not have unique name keys [1716305] DateTimeZone zone = DateTimeZone.forID("Australia/Sydney"); DateTime now = new DateTime(1996, 1, 1, 0, 0, 0, 0); String str1 = zone.getName(now.getMillis()); String str2 = zone.getName(now.plusMonths(6).getMillis()); assertEquals(false, str1.equals(str2)); } public void testPatchedNameKeysGazaHistoric() throws Exception { // the tz database does not have unique name keys [1716305] DateTimeZone zone = DateTimeZone.forID("Africa/Johannesburg"); DateTime now = new DateTime(1943, 1, 1, 0, 0, 0, 0); String str1 = zone.getName(now.getMillis()); String str2 = zone.getName(now.plusMonths(6).getMillis()); assertEquals(false, str1.equals(str2)); } } joda-time-2.3/src/test/java/org/joda/time/TestMutableInterval_Basics.java0000644000175000017500000005542511640075205026010 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractInterval; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for Instant. * * @author Stephen Colebourne */ public class TestMutableInterval_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutableInterval_Basics.class); } public TestMutableInterval_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGetMillis() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME1, test.getStart().getMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); assertEquals(TEST_TIME2, test.getEnd().getMillis()); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis()); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis()); } public void testGetDuration1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis()); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis()); } public void testGetDuration2() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME1); assertSame(Duration.ZERO, test.toDuration()); } public void testEqualsHashCode() { MutableInterval test1 = new MutableInterval(TEST_TIME1, TEST_TIME2); MutableInterval test2 = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); MutableInterval test3 = new MutableInterval(TEST_TIME_NOW, TEST_TIME2); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); MutableInterval test4 = new MutableInterval(TEST_TIME1, TEST_TIME2, GJChronology.getInstance()); assertEquals(true, test4.equals(test4)); assertEquals(false, test1.equals(test4)); assertEquals(false, test2.equals(test4)); assertEquals(false, test4.equals(test1)); assertEquals(false, test4.equals(test2)); assertEquals(false, test1.hashCode() == test4.hashCode()); assertEquals(false, test2.hashCode() == test4.hashCode()); MutableInterval test5 = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test1.equals(test5)); assertEquals(true, test2.equals(test5)); assertEquals(false, test3.equals(test5)); assertEquals(true, test5.equals(test1)); assertEquals(true, test5.equals(test2)); assertEquals(false, test5.equals(test3)); assertEquals(true, test1.hashCode() == test5.hashCode()); assertEquals(true, test2.hashCode() == test5.hashCode()); assertEquals(false, test3.hashCode() == test5.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInterval())); assertEquals(false, test1.equals(new DateTime(TEST_TIME1))); } class MockInterval extends AbstractInterval { public MockInterval() { super(); } public Chronology getChronology() { return ISOChronology.getInstance(); } public long getStartMillis() { return TEST_TIME1; } public long getEndMillis() { return TEST_TIME2; } } //----------------------------------------------------------------------- public void testContains_long() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test.contains(TEST_TIME1)); assertEquals(false, test.contains(TEST_TIME1 - 1)); assertEquals(true, test.contains(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2)); assertEquals(false, test.contains(TEST_TIME2)); assertEquals(true, test.contains(TEST_TIME2 - 1)); } public void testContainsNow() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); DateTimeUtils.setCurrentMillisFixed(TEST_TIME1); assertEquals(true, test.containsNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 - 1); assertEquals(false, test.containsNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2); assertEquals(true, test.containsNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2); assertEquals(false, test.containsNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 - 1); assertEquals(true, test.containsNow()); } public void testContains_RI() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test.contains(new Instant(TEST_TIME1))); assertEquals(false, test.contains(new Instant(TEST_TIME1 - 1))); assertEquals(true, test.contains(new Instant(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2))); assertEquals(false, test.contains(new Instant(TEST_TIME2))); assertEquals(true, test.contains(new Instant(TEST_TIME2 - 1))); assertEquals(true, test.contains((ReadableInstant) null)); } //----------------------------------------------------------------------- public void testContains_RInterval() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME1))); assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME1))); assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME1 + 1))); assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME1 + 1))); assertEquals(true, test.contains(new Interval(TEST_TIME1 + 1, TEST_TIME1 + 1))); assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME2))); assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2))); assertEquals(true, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2))); assertEquals(false, test.contains(new Interval(TEST_TIME2, TEST_TIME2))); assertEquals(true, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2))); assertEquals(true, test.contains(new Interval(TEST_TIME1, TEST_TIME2 - 1))); assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2 - 1))); assertEquals(true, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 - 1))); assertEquals(true, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2 - 1))); assertEquals(true, test.contains(new Interval(TEST_TIME2 - 2, TEST_TIME2 - 1))); assertEquals(false, test.contains(new Interval(TEST_TIME1, TEST_TIME2 + 1))); assertEquals(false, test.contains(new Interval(TEST_TIME1 - 1, TEST_TIME2 + 1))); assertEquals(false, test.contains(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 + 1))); assertEquals(false, test.contains(new Interval(TEST_TIME2, TEST_TIME2 + 1))); assertEquals(false, test.contains(new Interval(TEST_TIME2 - 1, TEST_TIME2 + 1))); assertEquals(false, test.contains(new Interval(TEST_TIME1 - 2, TEST_TIME1 - 1))); assertEquals(true, test.contains((ReadableInterval) null)); } public void testOverlaps_RInterval() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(false, test.overlaps(new Interval(TEST_TIME1, TEST_TIME1))); assertEquals(false, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1, TEST_TIME1 + 1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1 + 1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1 + 1, TEST_TIME1 + 1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1, TEST_TIME2))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME2))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2))); assertEquals(false, test.overlaps(new Interval(TEST_TIME2, TEST_TIME2))); assertEquals(true, test.overlaps(new Interval(TEST_TIME2 - 1, TEST_TIME2))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1, TEST_TIME2 + 1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME2 + 1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1 + (TEST_TIME2 - TEST_TIME1) / 2, TEST_TIME2 + 1))); assertEquals(false, test.overlaps(new Interval(TEST_TIME2, TEST_TIME2 + 1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME2 - 1, TEST_TIME2 + 1))); assertEquals(false, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1 - 1))); assertEquals(false, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1))); assertEquals(true, test.overlaps(new Interval(TEST_TIME1 - 1, TEST_TIME1 + 1))); assertEquals(true, test.overlaps((ReadableInterval) null)); MutableInterval empty = new MutableInterval(TEST_TIME1, TEST_TIME1); assertEquals(false, empty.overlaps(empty)); assertEquals(false, empty.overlaps(test)); assertEquals(false, test.overlaps(empty)); } //----------------------------------------------------------------------- public void testIsBefore_long() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(false, test.isBefore(TEST_TIME1 - 1)); assertEquals(false, test.isBefore(TEST_TIME1)); assertEquals(false, test.isBefore(TEST_TIME1 + 1)); assertEquals(false, test.isBefore(TEST_TIME2 - 1)); assertEquals(true, test.isBefore(TEST_TIME2)); assertEquals(true, test.isBefore(TEST_TIME2 + 1)); } public void testIsBeforeNow() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 - 1); assertEquals(false, test.isBeforeNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2); assertEquals(true, test.isBeforeNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME2 + 1); assertEquals(true, test.isBeforeNow()); } public void testIsBefore_RI() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(false, test.isBefore(new Instant(TEST_TIME1 - 1))); assertEquals(false, test.isBefore(new Instant(TEST_TIME1))); assertEquals(false, test.isBefore(new Instant(TEST_TIME1 + 1))); assertEquals(false, test.isBefore(new Instant(TEST_TIME2 - 1))); assertEquals(true, test.isBefore(new Instant(TEST_TIME2))); assertEquals(true, test.isBefore(new Instant(TEST_TIME2 + 1))); assertEquals(false, test.isBefore((ReadableInstant) null)); } public void testIsBefore_RInterval() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1 - 1))); assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1))); assertEquals(false, test.isBefore(new Interval(Long.MIN_VALUE, TEST_TIME1 + 1))); assertEquals(false, test.isBefore(new Interval(TEST_TIME2 - 1, Long.MAX_VALUE))); assertEquals(true, test.isBefore(new Interval(TEST_TIME2, Long.MAX_VALUE))); assertEquals(true, test.isBefore(new Interval(TEST_TIME2 + 1, Long.MAX_VALUE))); assertEquals(false, test.isBefore((ReadableInterval) null)); } //----------------------------------------------------------------------- public void testIsAfter_long() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test.isAfter(TEST_TIME1 - 1)); assertEquals(false, test.isAfter(TEST_TIME1)); assertEquals(false, test.isAfter(TEST_TIME1 + 1)); assertEquals(false, test.isAfter(TEST_TIME2 - 1)); assertEquals(false, test.isAfter(TEST_TIME2)); assertEquals(false, test.isAfter(TEST_TIME2 + 1)); } public void testIsAfterNow() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 - 1); assertEquals(true, test.isAfterNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME1); assertEquals(false, test.isAfterNow()); DateTimeUtils.setCurrentMillisFixed(TEST_TIME1 + 1); assertEquals(false, test.isAfterNow()); } public void testIsAfter_RI() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test.isAfter(new Instant(TEST_TIME1 - 1))); assertEquals(false, test.isAfter(new Instant(TEST_TIME1))); assertEquals(false, test.isAfter(new Instant(TEST_TIME1 + 1))); assertEquals(false, test.isAfter(new Instant(TEST_TIME2 - 1))); assertEquals(false, test.isAfter(new Instant(TEST_TIME2))); assertEquals(false, test.isAfter(new Instant(TEST_TIME2 + 1))); assertEquals(false, test.isAfter((ReadableInstant) null)); } public void testIsAfter_RInterval() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1 - 1))); assertEquals(true, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1))); assertEquals(false, test.isAfter(new Interval(Long.MIN_VALUE, TEST_TIME1 + 1))); assertEquals(false, test.isAfter(new Interval(TEST_TIME2 - 1, Long.MAX_VALUE))); assertEquals(false, test.isAfter(new Interval(TEST_TIME2, Long.MAX_VALUE))); assertEquals(false, test.isAfter(new Interval(TEST_TIME2 + 1, Long.MAX_VALUE))); assertEquals(false, test.isAfter((ReadableInterval) null)); } //----------------------------------------------------------------------- public void testToInterval1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval result = test.toInterval(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToMutableInterval1() { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); MutableInterval result = test.toMutableInterval(); assertEquals(test, result); assertNotSame(test, result); } //----------------------------------------------------------------------- public void testToPeriod() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS); MutableInterval base = new MutableInterval(dt1, dt2); Period test = base.toPeriod(); Period expected = new Period(dt1, dt2, PeriodType.standard()); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToPeriod_PeriodType1() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS); MutableInterval base = new MutableInterval(dt1, dt2); Period test = base.toPeriod(null); Period expected = new Period(dt1, dt2, PeriodType.standard()); assertEquals(expected, test); } public void testToPeriod_PeriodType2() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18); MutableInterval base = new MutableInterval(dt1, dt2); Period test = base.toPeriod(PeriodType.yearWeekDayTime()); Period expected = new Period(dt1, dt2, PeriodType.yearWeekDayTime()); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); MutableInterval result = (MutableInterval) ois.readObject(); ois.close(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToString() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, DateTimeZone.UTC); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, DateTimeZone.UTC); MutableInterval test = new MutableInterval(dt1, dt2); assertEquals("2004-06-09T07:08:09.010Z/2005-08-13T12:14:16.018Z", test.toString()); } //----------------------------------------------------------------------- public void testCopy() { MutableInterval test = new MutableInterval(123L, 456L, COPTIC_PARIS); MutableInterval cloned = test.copy(); assertEquals(test, cloned); assertNotSame(test, cloned); } public void testClone() { MutableInterval test = new MutableInterval(123L, 456L, COPTIC_PARIS); MutableInterval cloned = (MutableInterval) test.clone(); assertEquals(test, cloned); assertNotSame(test, cloned); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalDate_Basics.java0000644000175000017500000013641512200501234024526 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.StrictChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for LocalDate. * * @author Stephen Colebourne */ public class TestLocalDate_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); // private static final int OFFSET = 1; private static final GJChronology GJ_UTC = GJChronology.getInstanceUTC(); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); // private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON); // private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO); // private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS); private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); // private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); /** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */ private static long CUTOVER_GAZA = 1175378400000L; private static int OFFSET_GAZA = 7200000; // +02:00 private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // private long TEST_TIME1 = // (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 12L * DateTimeConstants.MILLIS_PER_HOUR // + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // // private long TEST_TIME2 = // (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY // + 14L * DateTimeConstants.MILLIS_PER_HOUR // + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale systemDefaultLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalDate_Basics.class); } public TestLocalDate_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); systemDefaultLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; Locale.setDefault(systemDefaultLocale); systemDefaultLocale = null; } //----------------------------------------------------------------------- public void testGet_DateTimeFieldType() { LocalDate test = new LocalDate(); assertEquals(1970, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); assertEquals(2, test.get(DateTimeFieldType.dayOfWeek())); assertEquals(160, test.get(DateTimeFieldType.dayOfYear())); assertEquals(24, test.get(DateTimeFieldType.weekOfWeekyear())); assertEquals(1970, test.get(DateTimeFieldType.weekyear())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.hourOfDay()); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { LocalDate test = new LocalDate(); assertEquals(3, test.size()); } public void testGetFieldType_int() { LocalDate test = new LocalDate(COPTIC_PARIS); assertSame(DateTimeFieldType.year(), test.getFieldType(0)); assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(1)); assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(2)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { LocalDate test = new LocalDate(COPTIC_PARIS); DateTimeFieldType[] fields = test.getFieldTypes(); assertSame(DateTimeFieldType.year(), fields[0]); assertSame(DateTimeFieldType.monthOfYear(), fields[1]); assertSame(DateTimeFieldType.dayOfMonth(), fields[2]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField_int() { LocalDate test = new LocalDate(COPTIC_PARIS); assertSame(COPTIC_UTC.year(), test.getField(0)); assertSame(COPTIC_UTC.monthOfYear(), test.getField(1)); assertSame(COPTIC_UTC.dayOfMonth(), test.getField(2)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { LocalDate test = new LocalDate(COPTIC_PARIS); DateTimeField[] fields = test.getFields(); assertSame(COPTIC_UTC.year(), fields[0]); assertSame(COPTIC_UTC.monthOfYear(), fields[1]); assertSame(COPTIC_UTC.dayOfMonth(), fields[2]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue_int() { LocalDate test = new LocalDate(); assertEquals(1970, test.getValue(0)); assertEquals(6, test.getValue(1)); assertEquals(9, test.getValue(2)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { LocalDate test = new LocalDate(); int[] values = test.getValues(); assertEquals(1970, values[0]); assertEquals(6, values[1]); assertEquals(9, values[2]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported_DateTimeFieldType() { LocalDate test = new LocalDate(COPTIC_PARIS); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfWeek())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.weekOfWeekyear())); assertEquals(true, test.isSupported(DateTimeFieldType.weekyear())); assertEquals(true, test.isSupported(DateTimeFieldType.yearOfCentury())); assertEquals(true, test.isSupported(DateTimeFieldType.yearOfEra())); assertEquals(true, test.isSupported(DateTimeFieldType.centuryOfEra())); assertEquals(true, test.isSupported(DateTimeFieldType.weekyearOfCentury())); assertEquals(true, test.isSupported(DateTimeFieldType.era())); assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay())); assertEquals(false, test.isSupported((DateTimeFieldType) null)); } public void testIsSupported_DurationFieldType() { LocalDate test = new LocalDate(1970, 6, 9); assertEquals(false, test.isSupported(DurationFieldType.eras())); assertEquals(true, test.isSupported(DurationFieldType.centuries())); assertEquals(true, test.isSupported(DurationFieldType.years())); assertEquals(true, test.isSupported(DurationFieldType.months())); assertEquals(true, test.isSupported(DurationFieldType.weekyears())); assertEquals(true, test.isSupported(DurationFieldType.weeks())); assertEquals(true, test.isSupported(DurationFieldType.days())); assertEquals(false, test.isSupported(DurationFieldType.hours())); assertEquals(false, test.isSupported((DurationFieldType) null)); } @SuppressWarnings("deprecation") public void testEqualsHashCode() { LocalDate test1 = new LocalDate(1970, 6, 9, COPTIC_PARIS); LocalDate test2 = new LocalDate(1970, 6, 9, COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); LocalDate test3 = new LocalDate(1971, 6, 9); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInstant())); assertEquals(true, test1.equals(new YearMonthDay(1970, 6, 9, COPTIC_PARIS))); assertEquals(true, test1.hashCode() == new YearMonthDay(1970, 6, 9, COPTIC_PARIS).hashCode()); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); } class MockInstant extends MockPartial { public Chronology getChronology() { return COPTIC_UTC; } public DateTimeField[] getFields() { return new DateTimeField[] { COPTIC_UTC.year(), COPTIC_UTC.monthOfYear(), COPTIC_UTC.dayOfMonth(), }; } public int[] getValues() { return new int[] {1970, 6, 9}; } } public void testEqualsHashCodeLenient() { LocalDate test1 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); LocalDate test2 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); } public void testEqualsHashCodeStrict() { LocalDate test1 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); LocalDate test2 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); } public void testEqualsHashCodeAPI() { LocalDate test = new LocalDate(1970, 6, 9, COPTIC_PARIS); int expected = 157; expected = 23 * expected + 1970; expected = 23 * expected + COPTIC_UTC.year().getType().hashCode(); expected = 23 * expected + 6; expected = 23 * expected + COPTIC_UTC.monthOfYear().getType().hashCode(); expected = 23 * expected + 9; expected = 23 * expected + COPTIC_UTC.dayOfMonth().getType().hashCode(); expected += COPTIC_UTC.hashCode(); assertEquals(expected, test.hashCode()); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testCompareTo() { LocalDate test1 = new LocalDate(2005, 6, 2); LocalDate test1a = new LocalDate(2005, 6, 2); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); LocalDate test2 = new LocalDate(2005, 7, 2); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth(), }; int[] values = new int[] {2005, 6, 2}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); assertEquals(0, test1.compareTo(new YearMonthDay(2005, 6, 2))); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} try { test1.compareTo(new TimeOfDay()); fail(); } catch (ClassCastException ex) {} Partial partial = new Partial() .with(DateTimeFieldType.centuryOfEra(), 1) .with(DateTimeFieldType.halfdayOfDay(), 0) .with(DateTimeFieldType.dayOfMonth(), 9); try { new LocalDate(1970, 6, 9).compareTo(partial); fail(); } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_LocalDate() { LocalDate test1 = new LocalDate(2005, 6, 2); LocalDate test1a = new LocalDate(2005, 6, 2); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); LocalDate test2 = new LocalDate(2005, 7, 2); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { new LocalDate(2005, 7, 2).isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_LocalDate() { LocalDate test1 = new LocalDate(2005, 6, 2); LocalDate test1a = new LocalDate(2005, 6, 2); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); LocalDate test2 = new LocalDate(2005, 7, 2); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new LocalDate(2005, 7, 2).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_LocalDate() { LocalDate test1 = new LocalDate(2005, 6, 2); LocalDate test1a = new LocalDate(2005, 6, 2); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); LocalDate test2 = new LocalDate(2005, 7, 2); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new LocalDate(2005, 7, 2).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithField_DateTimeFieldType_int_1() { LocalDate test = new LocalDate(2004, 6, 9); LocalDate result = test.withField(DateTimeFieldType.year(), 2006); assertEquals(new LocalDate(2004, 6, 9), test); assertEquals(new LocalDate(2006, 6, 9), result); } public void testWithField_DateTimeFieldType_int_2() { LocalDate test = new LocalDate(2004, 6, 9); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_DateTimeFieldType_int_3() { LocalDate test = new LocalDate(2004, 6, 9); try { test.withField(DateTimeFieldType.hourOfDay(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField_DateTimeFieldType_int_4() { LocalDate test = new LocalDate(2004, 6, 9); LocalDate result = test.withField(DateTimeFieldType.year(), 2004); assertEquals(new LocalDate(2004, 6, 9), test); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded_DurationFieldType_int_1() { LocalDate test = new LocalDate(2004, 6, 9); LocalDate result = test.withFieldAdded(DurationFieldType.years(), 6); assertEquals(new LocalDate(2004, 6, 9), test); assertEquals(new LocalDate(2010, 6, 9), result); } public void testWithFieldAdded_DurationFieldType_int_2() { LocalDate test = new LocalDate(2004, 6, 9); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_DurationFieldType_int_3() { LocalDate test = new LocalDate(2004, 6, 9); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded_DurationFieldType_int_4() { LocalDate test = new LocalDate(2004, 6, 9); LocalDate result = test.withFieldAdded(DurationFieldType.years(), 0); assertSame(test, result); } public void testWithFieldAdded_DurationFieldType_int_5() { LocalDate test = new LocalDate(2004, 6, 9); try { test.withFieldAdded(DurationFieldType.hours(), 6); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPlus_RP() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.plus(new Period(1, 2, 3, 4, 29, 6, 7, 8)); LocalDate expected = new LocalDate(2003, 7, 28, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusYears_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.plusYears(1); LocalDate expected = new LocalDate(2003, 5, 3, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusYears(0); assertSame(test, result); } public void testPlusMonths_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.plusMonths(1); LocalDate expected = new LocalDate(2002, 6, 3, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusMonths(0); assertSame(test, result); } public void testPlusWeeks_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.plusWeeks(1); LocalDate expected = new LocalDate(2002, 5, 10, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusWeeks(0); assertSame(test, result); } public void testPlusDays_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.plusDays(1); LocalDate expected = new LocalDate(2002, 5, 4, BUDDHIST_LONDON); assertEquals(expected, result); result = test.plusDays(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); // TODO breaks because it subtracts millis now, and thus goes // into the previous day LocalDate expected = new LocalDate(2001, 3, 26, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusYears_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.minusYears(1); LocalDate expected = new LocalDate(2001, 5, 3, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusYears(0); assertSame(test, result); } public void testMinusMonths_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.minusMonths(1); LocalDate expected = new LocalDate(2002, 4, 3, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusMonths(0); assertSame(test, result); } public void testMinusWeeks_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.minusWeeks(1); LocalDate expected = new LocalDate(2002, 4, 26, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusWeeks(0); assertSame(test, result); } public void testMinusDays_int() { LocalDate test = new LocalDate(2002, 5, 3, BUDDHIST_LONDON); LocalDate result = test.minusDays(1); LocalDate expected = new LocalDate(2002, 5, 2, BUDDHIST_LONDON); assertEquals(expected, result); result = test.minusDays(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testGetters() { LocalDate test = new LocalDate(1970, 6, 9, GJ_UTC); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(160, test.getDayOfYear()); assertEquals(2, test.getDayOfWeek()); assertEquals(24, test.getWeekOfWeekyear()); assertEquals(1970, test.getWeekyear()); assertEquals(70, test.getYearOfCentury()); assertEquals(20, test.getCenturyOfEra()); assertEquals(1970, test.getYearOfEra()); assertEquals(DateTimeConstants.AD, test.getEra()); } //----------------------------------------------------------------------- public void testWithers() { LocalDate test = new LocalDate(1970, 6, 9, GJ_UTC); check(test.withYear(2000), 2000, 6, 9); check(test.withMonthOfYear(2), 1970, 2, 9); check(test.withDayOfMonth(2), 1970, 6, 2); check(test.withDayOfYear(6), 1970, 1, 6); check(test.withDayOfWeek(6), 1970, 6, 13); check(test.withWeekOfWeekyear(6), 1970, 2, 3); check(test.withWeekyear(1971), 1971, 6, 15); check(test.withYearOfCentury(60), 1960, 6, 9); check(test.withCenturyOfEra(21), 2070, 6, 9); check(test.withYearOfEra(1066), 1066, 6, 9); check(test.withEra(DateTimeConstants.BC), -1970, 6, 9); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testToDateTimeAtStartOfDay() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtStartOfDay(); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test); } public void testToDateTimeAtStartOfDay_avoidDST() { LocalDate base = new LocalDate(2007, 4, 1); DateTimeZone.setDefault(MOCK_GAZA); DateTime test = base.toDateTimeAtStartOfDay(); check(base, 2007, 4, 1); assertEquals(new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA), test); } //----------------------------------------------------------------------- public void testToDateTimeAtStartOfDay_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtStartOfDay(TOKYO); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_TOKYO), test); } public void testToDateTimeAtStartOfDay_Zone_avoidDST() { LocalDate base = new LocalDate(2007, 4, 1); DateTime test = base.toDateTimeAtStartOfDay(MOCK_GAZA); check(base, 2007, 4, 1); assertEquals(new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA), test); } public void testToDateTimeAtStartOfDay_nullZone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtStartOfDay((DateTimeZone) null); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testToDateTimeAtMidnight() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtMidnight(); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testToDateTimeAtMidnight_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtMidnight(TOKYO); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_TOKYO), test); } @SuppressWarnings("deprecation") public void testToDateTimeAtMidnight_nullZone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtMidnight((DateTimeZone) null); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test); } //----------------------------------------------------------------------- public void testToDateTimeAtCurrentTime() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeAtCurrentTime(); check(base, 2005, 6, 9); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTimeAtCurrentTime_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeAtCurrentTime(TOKYO); check(base, 2005, 6, 9); DateTime expected = new DateTime(dt.getMillis(), COPTIC_TOKYO); expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } public void testToDateTimeAtCurrentTime_nullZone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeAtCurrentTime((DateTimeZone) null); check(base, 2005, 6, 9); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToLocalDateTime_LocalTime() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO); LocalDateTime test = base.toLocalDateTime(tod); check(base, 2005, 6, 9); LocalDateTime expected = new LocalDateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_UTC); assertEquals(expected, test); } public void testToLocalDateTime_nullLocalTime() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant try { base.toLocalDateTime((LocalTime) null); fail(); } catch (IllegalArgumentException ex) { // expected } } public void testToLocalDateTime_wrongChronologyLocalTime() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime tod = new LocalTime(12, 13, 14, 15, BUDDHIST_PARIS); // PARIS irrelevant try { base.toLocalDateTime(tod); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- public void testToDateTime_LocalTime() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO); DateTime test = base.toDateTime(tod); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON); assertEquals(expected, test); } public void testToDateTime_nullLocalTime() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_LONDON).getMillis(); DateTimeUtils.setCurrentMillisFixed(now); DateTime test = base.toDateTime((LocalTime) null); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTime_LocalTime_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO); DateTime test = base.toDateTime(tod, TOKYO); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO); assertEquals(expected, test); } public void testToDateTime_LocalTime_nullZone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime tod = new LocalTime(12, 13, 14, 15, COPTIC_TOKYO); DateTime test = base.toDateTime(tod, null); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON); assertEquals(expected, test); } public void testToDateTime_nullLocalTime_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_TOKYO).getMillis(); DateTimeUtils.setCurrentMillisFixed(now); DateTime test = base.toDateTime((LocalTime) null, TOKYO); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO); assertEquals(expected, test); } public void testToDateTime_wrongChronoLocalTime_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime tod = new LocalTime(12, 13, 14, 15, BUDDHIST_TOKYO); try { base.toDateTime(tod, LONDON); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testToDateMidnight() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateMidnight test = base.toDateMidnight(); check(base, 2005, 6, 9); assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test); } //----------------------------------------------------------------------- @SuppressWarnings("deprecation") public void testToDateMidnight_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateMidnight test = base.toDateMidnight(TOKYO); check(base, 2005, 6, 9); assertEquals(new DateMidnight(2005, 6, 9, COPTIC_TOKYO), test); } @SuppressWarnings("deprecation") public void testToDateMidnight_nullZone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateMidnight test = base.toDateMidnight((DateTimeZone) null); check(base, 2005, 6, 9); assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test); } //----------------------------------------------------------------------- public void testToDateTime_RI() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTime test = base.toDateTime(dt); check(base, 2005, 6, 9); DateTime expected = dt; expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } public void testToDateTime_nullRI() { LocalDate base = new LocalDate(2005, 6, 9); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 2005, 6, 9); DateTime expected = dt; expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToInterval() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(); check(base, 2005, 6, 9); DateTime start = base.toDateTimeAtStartOfDay(); DateTime end = start.plus(Period.days(1)); Interval expected = new Interval(start, end); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToInterval_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(TOKYO); check(base, 2005, 6, 9); DateTime start = base.toDateTimeAtStartOfDay(TOKYO); DateTime end = start.plus(Period.days(1)); Interval expected = new Interval(start, end); assertEquals(expected, test); } public void testToInterval_Zone_noMidnight() { LocalDate base = new LocalDate(2006, 4, 1, ISO_LONDON); // LONDON irrelevant DateTimeZone gaza = DateTimeZone.forID("Asia/Gaza"); Interval test = base.toInterval(gaza); check(base, 2006, 4, 1); DateTime start = new DateTime(2006, 4, 1, 1, 0, 0, 0, gaza); DateTime end = new DateTime(2006, 4, 2, 0, 0, 0, 0, gaza); Interval expected = new Interval(start, end); assertEquals(expected, test); } public void testToInterval_nullZone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(null); check(base, 2005, 6, 9); DateTime start = base.toDateTimeAtStartOfDay(LONDON); DateTime end = start.plus(Period.days(1)); Interval expected = new Interval(start, end); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDate_summer() { LocalDate base = new LocalDate(2005, 7, 9, COPTIC_PARIS); Date test = base.toDate(); check(base, 2005, 7, 9); GregorianCalendar gcal = new GregorianCalendar(); gcal.clear(); gcal.set(Calendar.YEAR, 2005); gcal.set(Calendar.MONTH, Calendar.JULY); gcal.set(Calendar.DAY_OF_MONTH, 9); assertEquals(gcal.getTime(), test); } public void testToDate_winter() { LocalDate base = new LocalDate(2005, 1, 9, COPTIC_PARIS); Date test = base.toDate(); check(base, 2005, 1, 9); GregorianCalendar gcal = new GregorianCalendar(); gcal.clear(); gcal.set(Calendar.YEAR, 2005); gcal.set(Calendar.MONTH, Calendar.JANUARY); gcal.set(Calendar.DAY_OF_MONTH, 9); assertEquals(gcal.getTime(), test); } public void testToDate_springDST() { LocalDate base = new LocalDate(2007, 4, 2); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(); check(base, 2007, 4, 2); assertEquals("Mon Apr 02 01:00:00 GMT+02:00 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } public void testToDate_springDST_2Hour40Savings() { LocalDate base = new LocalDate(2007, 4, 2); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000, (3600000 / 6) * 16); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(); check(base, 2007, 4, 2); assertEquals("Mon Apr 02 02:40:00 GMT+03:40 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } public void testToDate_autumnDST() { LocalDate base = new LocalDate(2007, 10, 2); SimpleTimeZone testZone = new SimpleTimeZone(3600000, "NoMidnight", Calendar.APRIL, 2, 0, 0, Calendar.OCTOBER, 2, 0, 3600000); TimeZone currentZone = TimeZone.getDefault(); try { TimeZone.setDefault(testZone); Date test = base.toDate(); check(base, 2007, 10, 2); assertEquals("Tue Oct 02 00:00:00 GMT+02:00 2007", test.toString()); } finally { TimeZone.setDefault(currentZone); } } //----------------------------------------------------------------------- public void testProperty() { LocalDate test = new LocalDate(2005, 6, 9, GJ_UTC); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear())); assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth())); assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek())); assertEquals(test.dayOfYear(), test.property(DateTimeFieldType.dayOfYear())); assertEquals(test.weekOfWeekyear(), test.property(DateTimeFieldType.weekOfWeekyear())); assertEquals(test.weekyear(), test.property(DateTimeFieldType.weekyear())); assertEquals(test.yearOfCentury(), test.property(DateTimeFieldType.yearOfCentury())); assertEquals(test.yearOfEra(), test.property(DateTimeFieldType.yearOfEra())); assertEquals(test.centuryOfEra(), test.property(DateTimeFieldType.centuryOfEra())); assertEquals(test.era(), test.property(DateTimeFieldType.era())); try { test.property(DateTimeFieldType.millisOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { LocalDate test = new LocalDate(1972, 6, 9, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); LocalDate result = (LocalDate) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); } //----------------------------------------------------------------------- public void testToString() { LocalDate test = new LocalDate(2002, 6, 9); assertEquals("2002-06-09", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { LocalDate test = new LocalDate(2002, 6, 9); assertEquals("2002 \ufffd\ufffd", test.toString("yyyy HH")); assertEquals("2002-06-09", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { LocalDate test = new LocalDate(1970, 6, 9); assertEquals("Tue 9/6", test.toString("EEE d/M", Locale.ENGLISH)); assertEquals("mar. 9/6", test.toString("EEE d/M", Locale.FRENCH)); assertEquals("1970-06-09", test.toString(null, Locale.ENGLISH)); assertEquals("Tue 9/6", test.toString("EEE d/M", null)); assertEquals("1970-06-09", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { LocalDate test = new LocalDate(2002, 6, 9); assertEquals("2002 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("2002-06-09", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private void check(LocalDate test, int hour, int min, int sec) { assertEquals(hour, test.getYear()); assertEquals(min, test.getMonthOfYear()); assertEquals(sec, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestInterval_Basics.java0000644000175000017500000017403612137467330024504 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractInterval; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.LenientChronology; /** * This class is a Junit unit test for Instant. * * @author Stephen Colebourne */ public class TestInterval_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone MOSCOW = DateTimeZone.forID("Europe/Moscow"); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private Interval interval37; private Interval interval33; long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestInterval_Basics.class); } public TestInterval_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(PARIS); TimeZone.setDefault(PARIS.toTimeZone()); Locale.setDefault(Locale.FRANCE); interval37 = new Interval(3, 7); interval33 = new Interval(3, 3); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGetMillis() { Interval test = new Interval(TEST_TIME1, TEST_TIME2); assertEquals(TEST_TIME1, test.getStartMillis()); assertEquals(TEST_TIME1, test.getStart().getMillis()); assertEquals(TEST_TIME2, test.getEndMillis()); assertEquals(TEST_TIME2, test.getEnd().getMillis()); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis()); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis()); } public void testGetDuration1() { Interval test = new Interval(TEST_TIME1, TEST_TIME2); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDurationMillis()); assertEquals(TEST_TIME2 - TEST_TIME1, test.toDuration().getMillis()); } public void testGetDuration2() { Interval test = new Interval(TEST_TIME1, TEST_TIME1); assertSame(Duration.ZERO, test.toDuration()); } public void testEqualsHashCode() { Interval test1 = new Interval(TEST_TIME1, TEST_TIME2); Interval test2 = new Interval(TEST_TIME1, TEST_TIME2); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); Interval test3 = new Interval(TEST_TIME_NOW, TEST_TIME2); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); Interval test4 = new Interval(TEST_TIME1, TEST_TIME2, GJChronology.getInstance()); assertEquals(true, test4.equals(test4)); assertEquals(false, test1.equals(test4)); assertEquals(false, test2.equals(test4)); assertEquals(false, test4.equals(test1)); assertEquals(false, test4.equals(test2)); assertEquals(false, test1.hashCode() == test4.hashCode()); assertEquals(false, test2.hashCode() == test4.hashCode()); MutableInterval test5 = new MutableInterval(TEST_TIME1, TEST_TIME2); assertEquals(true, test1.equals(test5)); assertEquals(true, test2.equals(test5)); assertEquals(false, test3.equals(test5)); assertEquals(true, test5.equals(test1)); assertEquals(true, test5.equals(test2)); assertEquals(false, test5.equals(test3)); assertEquals(true, test1.hashCode() == test5.hashCode()); assertEquals(true, test2.hashCode() == test5.hashCode()); assertEquals(false, test3.hashCode() == test5.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInterval())); assertEquals(false, test1.equals(new DateTime(TEST_TIME1))); } class MockInterval extends AbstractInterval { public MockInterval() { super(); } public Chronology getChronology() { return ISOChronology.getInstance(); } public long getStartMillis() { return TEST_TIME1; } public long getEndMillis() { return TEST_TIME2; } } public void testEqualsHashCodeLenient() { Interval test1 = new Interval( new DateTime(TEST_TIME1, LenientChronology.getInstance(COPTIC_PARIS)), new DateTime(TEST_TIME2, LenientChronology.getInstance(COPTIC_PARIS))); Interval test2 = new Interval( new DateTime(TEST_TIME1, LenientChronology.getInstance(COPTIC_PARIS)), new DateTime(TEST_TIME2, LenientChronology.getInstance(COPTIC_PARIS))); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); } public void testEqualsHashCodeStrict() { Interval test1 = new Interval( new DateTime(TEST_TIME1, LenientChronology.getInstance(COPTIC_PARIS)), new DateTime(TEST_TIME2, LenientChronology.getInstance(COPTIC_PARIS))); Interval test2 = new Interval( new DateTime(TEST_TIME1, LenientChronology.getInstance(COPTIC_PARIS)), new DateTime(TEST_TIME2, LenientChronology.getInstance(COPTIC_PARIS))); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); } //----------------------------------------------------------------------- public void test_useCase_ContainsOverlapAbutGap() { // this is a simple test to ensure that the use case of these methods is OK // when comparing any two intervals they can be in one and only one of these states // (a) have a gap between them, (b) abut or (c) overlap // contains is a subset of overlap Interval test1020 = new Interval(10, 20); // [4,8) [10,20) - gap Interval interval = new Interval(4, 8); assertNotNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNotNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [6,10) [10,20) - abuts interval = new Interval(6, 10); assertNull(test1020.gap(interval)); assertEquals(true, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNull(interval.gap(test1020)); assertEquals(true, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [8,12) [10,20) - overlaps interval = new Interval(8, 12); assertNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(true, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(true, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [10,14) [10,20) - overlaps and contains-one-way interval = new Interval(10, 14); assertNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(true, test1020.overlaps(interval)); assertEquals(true, test1020.contains(interval)); assertNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(true, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [10,20) [10,20) - overlaps and contains-both-ways assertNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(test1020)); assertEquals(true, test1020.overlaps(test1020)); assertEquals(true, test1020.contains(test1020)); // [10,20) [16,20) - overlaps and contains-one-way interval = new Interval(16, 20); assertNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(true, test1020.overlaps(interval)); assertEquals(true, test1020.contains(interval)); assertNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(true, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [10,20) [18,22) - overlaps interval = new Interval(18, 22); assertNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(true, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(true, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [10,20) [20,24) - abuts interval = new Interval(20, 24); assertNull(test1020.gap(interval)); assertEquals(true, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNull(interval.gap(test1020)); assertEquals(true, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [10,20) [22,26) - gap interval = new Interval(22, 26); assertNotNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNotNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); } //----------------------------------------------------------------------- public void test_useCase_ContainsOverlapAbutGap_zeroDuration() { // this is a simple test to ensure that the use case of these methods // is OK when considering a zero duration inerval // when comparing any two intervals they can be in one and only one of these states // (a) have a gap between them, (b) abut or (c) overlap // contains is a subset of overlap Interval test1020 = new Interval(10, 20); // [8,8) [10,20) - gap Interval interval = new Interval(8, 8); assertNotNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNotNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [10,10) [10,20) - abuts and contains-one-way interval = new Interval(10, 10); assertNull(test1020.gap(interval)); assertEquals(true, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); // abuts, so can't overlap assertEquals(true, test1020.contains(interval)); // normal contains zero-duration assertNull(interval.gap(test1020)); assertEquals(true, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); // abuts, so can't overlap assertEquals(false, interval.contains(test1020)); // zero-duration does not contain normal // [12,12) [10,20) - contains-one-way and overlaps interval = new Interval(12, 12); assertNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(true, test1020.overlaps(interval)); assertEquals(true, test1020.contains(interval)); // normal contains zero-duration assertNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(true, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // zero-duration does not contain normal // [10,20) [20,20) - abuts interval = new Interval(20, 20); assertNull(test1020.gap(interval)); assertEquals(true, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNull(interval.gap(test1020)); assertEquals(true, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); // [10,20) [22,22) - gap interval = new Interval(22, 22); assertNotNull(test1020.gap(interval)); assertEquals(false, test1020.abuts(interval)); assertEquals(false, test1020.overlaps(interval)); assertEquals(false, test1020.contains(interval)); assertNotNull(interval.gap(test1020)); assertEquals(false, interval.abuts(test1020)); assertEquals(false, interval.overlaps(test1020)); assertEquals(false, interval.contains(test1020)); } //----------------------------------------------------------------------- public void test_useCase_ContainsOverlapAbutGap_bothZeroDuration() { // this is a simple test to ensure that the use case of these methods // is OK when considering two zero duration inervals // this is the simplest case, as the two intervals either have a gap or not // if not, then they are equal and abut Interval test0808 = new Interval(8, 8); Interval test1010 = new Interval(10, 10); // [8,8) [10,10) - gap assertNotNull(test1010.gap(test0808)); assertEquals(false, test1010.abuts(test0808)); assertEquals(false, test1010.overlaps(test0808)); assertEquals(false, test1010.contains(test0808)); assertNotNull(test0808.gap(test1010)); assertEquals(false, test0808.abuts(test1010)); assertEquals(false, test0808.overlaps(test1010)); assertEquals(false, test0808.contains(test1010)); // [10,10) [10,10) - abuts assertNull(test1010.gap(test1010)); assertEquals(true, test1010.abuts(test1010)); assertEquals(false, test1010.overlaps(test1010)); assertEquals(false, test1010.contains(test1010)); } //----------------------------------------------------------------------- public void testContains_long() { assertEquals(false, interval37.contains(2)); // value before assertEquals(true, interval37.contains(3)); assertEquals(true, interval37.contains(4)); assertEquals(true, interval37.contains(5)); assertEquals(true, interval37.contains(6)); assertEquals(false, interval37.contains(7)); // value after assertEquals(false, interval37.contains(8)); // value after } public void testContains_long_zeroDuration() { assertEquals(false, interval33.contains(2)); // value before assertEquals(false, interval33.contains(3)); // zero length duration contains nothing assertEquals(false, interval33.contains(4)); // value after } //----------------------------------------------------------------------- public void testContainsNow() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.containsNow()); // value before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(true, interval37.containsNow()); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(true, interval37.containsNow()); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(true, interval37.containsNow()); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(false, interval37.containsNow()); // value after DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.containsNow()); // value after DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval33.containsNow()); // value before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval33.containsNow()); // zero length duration contains nothing DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval33.containsNow()); // value after } //----------------------------------------------------------------------- public void testContains_RI() { assertEquals(false, interval37.contains(new Instant(2))); // value before assertEquals(true, interval37.contains(new Instant(3))); assertEquals(true, interval37.contains(new Instant(4))); assertEquals(true, interval37.contains(new Instant(5))); assertEquals(true, interval37.contains(new Instant(6))); assertEquals(false, interval37.contains(new Instant(7))); // value after assertEquals(false, interval37.contains(new Instant(8))); // value after } public void testContains_RI_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.contains((ReadableInstant) null)); // value before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(true, interval37.contains((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(true, interval37.contains((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(true, interval37.contains((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(false, interval37.contains((ReadableInstant) null)); // value after DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.contains((ReadableInstant) null)); // value after } public void testContains_RI_zeroDuration() { assertEquals(false, interval33.contains(new Instant(2))); // value before assertEquals(false, interval33.contains(new Instant(3))); // zero length duration contains nothing assertEquals(false, interval33.contains(new Instant(4))); // value after } //----------------------------------------------------------------------- public void testContains_RInterval() { assertEquals(false, interval37.contains(new Interval(1, 2))); // gap before assertEquals(false, interval37.contains(new Interval(2, 2))); // gap before assertEquals(false, interval37.contains(new Interval(2, 3))); // abuts before assertEquals(true, interval37.contains(new Interval(3, 3))); assertEquals(false, interval37.contains(new Interval(2, 4))); // starts before assertEquals(true, interval37.contains(new Interval(3, 4))); assertEquals(true, interval37.contains(new Interval(4, 4))); assertEquals(false, interval37.contains(new Interval(2, 6))); // starts before assertEquals(true, interval37.contains(new Interval(3, 6))); assertEquals(true, interval37.contains(new Interval(4, 6))); assertEquals(true, interval37.contains(new Interval(5, 6))); assertEquals(true, interval37.contains(new Interval(6, 6))); assertEquals(false, interval37.contains(new Interval(2, 7))); // starts before assertEquals(true, interval37.contains(new Interval(3, 7))); assertEquals(true, interval37.contains(new Interval(4, 7))); assertEquals(true, interval37.contains(new Interval(5, 7))); assertEquals(true, interval37.contains(new Interval(6, 7))); assertEquals(false, interval37.contains(new Interval(7, 7))); // abuts after assertEquals(false, interval37.contains(new Interval(2, 8))); // ends after assertEquals(false, interval37.contains(new Interval(3, 8))); // ends after assertEquals(false, interval37.contains(new Interval(4, 8))); // ends after assertEquals(false, interval37.contains(new Interval(5, 8))); // ends after assertEquals(false, interval37.contains(new Interval(6, 8))); // ends after assertEquals(false, interval37.contains(new Interval(7, 8))); // abuts after assertEquals(false, interval37.contains(new Interval(8, 8))); // gap after assertEquals(false, interval37.contains(new Interval(8, 9))); // gap after assertEquals(false, interval37.contains(new Interval(9, 9))); // gap after } public void testContains_RInterval_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.contains((ReadableInterval) null)); // gap before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(true, interval37.contains((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(true, interval37.contains((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(true, interval37.contains((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(false, interval37.contains((ReadableInterval) null)); // abuts after DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.contains((ReadableInterval) null)); // gap after } public void testContains_RInterval_zeroDuration() { assertEquals(false, interval33.contains(interval33)); // zero length duration contains nothing assertEquals(false, interval33.contains(interval37)); // zero-duration cannot contain anything assertEquals(true, interval37.contains(interval33)); assertEquals(false, interval33.contains(new Interval(1, 2))); // zero-duration cannot contain anything assertEquals(false, interval33.contains(new Interval(8, 9))); // zero-duration cannot contain anything assertEquals(false, interval33.contains(new Interval(1, 9))); // zero-duration cannot contain anything DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval33.contains((ReadableInterval) null)); // gap before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval33.contains((ReadableInterval) null)); // zero length duration contains nothing DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval33.contains((ReadableInterval) null)); // gap after } //----------------------------------------------------------------------- public void testOverlaps_RInterval() { assertEquals(false, interval37.overlaps(new Interval(1, 2))); // gap before assertEquals(false, interval37.overlaps(new Interval(2, 2))); // gap before assertEquals(false, interval37.overlaps(new Interval(2, 3))); // abuts before assertEquals(false, interval37.overlaps(new Interval(3, 3))); // abuts before assertEquals(true, interval37.overlaps(new Interval(2, 4))); assertEquals(true, interval37.overlaps(new Interval(3, 4))); assertEquals(true, interval37.overlaps(new Interval(4, 4))); assertEquals(true, interval37.overlaps(new Interval(2, 6))); assertEquals(true, interval37.overlaps(new Interval(3, 6))); assertEquals(true, interval37.overlaps(new Interval(4, 6))); assertEquals(true, interval37.overlaps(new Interval(5, 6))); assertEquals(true, interval37.overlaps(new Interval(6, 6))); assertEquals(true, interval37.overlaps(new Interval(2, 7))); assertEquals(true, interval37.overlaps(new Interval(3, 7))); assertEquals(true, interval37.overlaps(new Interval(4, 7))); assertEquals(true, interval37.overlaps(new Interval(5, 7))); assertEquals(true, interval37.overlaps(new Interval(6, 7))); assertEquals(false, interval37.overlaps(new Interval(7, 7))); // abuts after assertEquals(true, interval37.overlaps(new Interval(2, 8))); assertEquals(true, interval37.overlaps(new Interval(3, 8))); assertEquals(true, interval37.overlaps(new Interval(4, 8))); assertEquals(true, interval37.overlaps(new Interval(5, 8))); assertEquals(true, interval37.overlaps(new Interval(6, 8))); assertEquals(false, interval37.overlaps(new Interval(7, 8))); // abuts after assertEquals(false, interval37.overlaps(new Interval(8, 8))); // gap after assertEquals(false, interval37.overlaps(new Interval(8, 9))); // gap after assertEquals(false, interval37.overlaps(new Interval(9, 9))); // gap after } public void testOverlaps_RInterval_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.overlaps((ReadableInterval) null)); // gap before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval37.overlaps((ReadableInterval) null)); // abuts before DateTimeUtils.setCurrentMillisFixed(4); assertEquals(true, interval37.overlaps((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(true, interval37.overlaps((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(false, interval37.overlaps((ReadableInterval) null)); // abuts after DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.overlaps((ReadableInterval) null)); // gap after DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval33.overlaps((ReadableInterval) null)); // abuts before and after } public void testOverlaps_RInterval_zeroDuration() { assertEquals(false, interval33.overlaps(interval33)); // abuts before and after assertEquals(false, interval33.overlaps(interval37)); // abuts before assertEquals(false, interval37.overlaps(interval33)); // abuts before assertEquals(false, interval33.overlaps(new Interval(1, 2))); assertEquals(false, interval33.overlaps(new Interval(8, 9))); assertEquals(true, interval33.overlaps(new Interval(1, 9))); } //----------------------------------------------------------------------- public void testOverlap_RInterval() { assertEquals(null, interval37.overlap(new Interval(1, 2))); // gap before assertEquals(null, interval37.overlap(new Interval(2, 2))); // gap before assertEquals(null, interval37.overlap(new Interval(2, 3))); // abuts before assertEquals(null, interval37.overlap(new Interval(3, 3))); // abuts before assertEquals(new Interval(3, 4), interval37.overlap(new Interval(2, 4))); // truncated start assertEquals(new Interval(3, 4), interval37.overlap(new Interval(3, 4))); assertEquals(new Interval(4, 4), interval37.overlap(new Interval(4, 4))); assertEquals(new Interval(3, 7), interval37.overlap(new Interval(2, 7))); // truncated start assertEquals(new Interval(3, 7), interval37.overlap(new Interval(3, 7))); assertEquals(new Interval(4, 7), interval37.overlap(new Interval(4, 7))); assertEquals(new Interval(5, 7), interval37.overlap(new Interval(5, 7))); assertEquals(new Interval(6, 7), interval37.overlap(new Interval(6, 7))); assertEquals(null, interval37.overlap(new Interval(7, 7))); // abuts after assertEquals(new Interval(3, 7), interval37.overlap(new Interval(2, 8))); // truncated start and end assertEquals(new Interval(3, 7), interval37.overlap(new Interval(3, 8))); // truncated end assertEquals(new Interval(4, 7), interval37.overlap(new Interval(4, 8))); // truncated end assertEquals(new Interval(5, 7), interval37.overlap(new Interval(5, 8))); // truncated end assertEquals(new Interval(6, 7), interval37.overlap(new Interval(6, 8))); // truncated end assertEquals(null, interval37.overlap(new Interval(7, 8))); // abuts after assertEquals(null, interval37.overlap(new Interval(8, 8))); // gap after } public void testOverlap_RInterval_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(null, interval37.overlap((ReadableInterval) null)); // gap before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(null, interval37.overlap((ReadableInterval) null)); // abuts before DateTimeUtils.setCurrentMillisFixed(4); assertEquals(new Interval(4, 4), interval37.overlap((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(new Interval(6, 6), interval37.overlap((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(null, interval37.overlap((ReadableInterval) null)); // abuts after DateTimeUtils.setCurrentMillisFixed(8); assertEquals(null, interval37.overlap((ReadableInterval) null)); // gap after DateTimeUtils.setCurrentMillisFixed(3); assertEquals(null, interval33.overlap((ReadableInterval) null)); // abuts before and after } public void testOverlap_RInterval_zone() { Interval testA = new Interval(new DateTime(3, LONDON), new DateTime(7, LONDON)); assertEquals(ISOChronology.getInstance(LONDON), testA.getChronology()); Interval testB = new Interval(new DateTime(4, MOSCOW), new DateTime(8, MOSCOW)); assertEquals(ISOChronology.getInstance(MOSCOW), testB.getChronology()); Interval resultAB = testA.overlap(testB); assertEquals(ISOChronology.getInstance(LONDON), resultAB.getChronology()); Interval resultBA = testB.overlap(testA); assertEquals(ISOChronology.getInstance(MOSCOW), resultBA.getChronology()); } public void testOverlap_RInterval_zoneUTC() { Interval testA = new Interval(new Instant(3), new Instant(7)); assertEquals(ISOChronology.getInstanceUTC(), testA.getChronology()); Interval testB = new Interval(new Instant(4), new Instant(8)); assertEquals(ISOChronology.getInstanceUTC(), testB.getChronology()); Interval result = testA.overlap(testB); assertEquals(ISOChronology.getInstanceUTC(), result.getChronology()); } //----------------------------------------------------------------------- public void testGap_RInterval() { assertEquals(new Interval(1, 3), interval37.gap(new Interval(0, 1))); assertEquals(new Interval(1, 3), interval37.gap(new Interval(1, 1))); assertEquals(null, interval37.gap(new Interval(2, 3))); // abuts before assertEquals(null, interval37.gap(new Interval(3, 3))); // abuts before assertEquals(null, interval37.gap(new Interval(4, 6))); // overlaps assertEquals(null, interval37.gap(new Interval(3, 7))); // overlaps assertEquals(null, interval37.gap(new Interval(6, 7))); // overlaps assertEquals(null, interval37.gap(new Interval(7, 7))); // abuts after assertEquals(null, interval37.gap(new Interval(6, 8))); // overlaps assertEquals(null, interval37.gap(new Interval(7, 8))); // abuts after assertEquals(new Interval(7, 8), interval37.gap(new Interval(8, 8))); assertEquals(null, interval37.gap(new Interval(6, 9))); // overlaps assertEquals(null, interval37.gap(new Interval(7, 9))); // abuts after assertEquals(new Interval(7, 8), interval37.gap(new Interval(8, 9))); assertEquals(new Interval(7, 9), interval37.gap(new Interval(9, 9))); } public void testGap_RInterval_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(new Interval(2, 3), interval37.gap((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(3); assertEquals(null, interval37.gap((ReadableInterval) null)); // abuts before DateTimeUtils.setCurrentMillisFixed(4); assertEquals(null, interval37.gap((ReadableInterval) null)); // overlaps DateTimeUtils.setCurrentMillisFixed(6); assertEquals(null, interval37.gap((ReadableInterval) null)); // overlaps DateTimeUtils.setCurrentMillisFixed(7); assertEquals(null, interval37.gap((ReadableInterval) null)); // abuts after DateTimeUtils.setCurrentMillisFixed(8); assertEquals(new Interval(7, 8), interval37.gap((ReadableInterval) null)); } public void testGap_RInterval_zone() { Interval testA = new Interval(new DateTime(3, LONDON), new DateTime(7, LONDON)); assertEquals(ISOChronology.getInstance(LONDON), testA.getChronology()); Interval testB = new Interval(new DateTime(1, MOSCOW), new DateTime(2, MOSCOW)); assertEquals(ISOChronology.getInstance(MOSCOW), testB.getChronology()); Interval resultAB = testA.gap(testB); assertEquals(ISOChronology.getInstance(LONDON), resultAB.getChronology()); Interval resultBA = testB.gap(testA); assertEquals(ISOChronology.getInstance(MOSCOW), resultBA.getChronology()); } public void testGap_RInterval_zoneUTC() { Interval testA = new Interval(new Instant(3), new Instant(7)); assertEquals(ISOChronology.getInstanceUTC(), testA.getChronology()); Interval testB = new Interval(new Instant(1), new Instant(2)); assertEquals(ISOChronology.getInstanceUTC(), testB.getChronology()); Interval result = testA.gap(testB); assertEquals(ISOChronology.getInstanceUTC(), result.getChronology()); } //----------------------------------------------------------------------- public void testAbuts_RInterval() { assertEquals(false, interval37.abuts(new Interval(1, 2))); // gap before assertEquals(false, interval37.abuts(new Interval(2, 2))); // gap before assertEquals(true, interval37.abuts(new Interval(2, 3))); assertEquals(true, interval37.abuts(new Interval(3, 3))); assertEquals(false, interval37.abuts(new Interval(2, 4))); // overlaps assertEquals(false, interval37.abuts(new Interval(3, 4))); // overlaps assertEquals(false, interval37.abuts(new Interval(4, 4))); // overlaps assertEquals(false, interval37.abuts(new Interval(2, 6))); // overlaps assertEquals(false, interval37.abuts(new Interval(3, 6))); // overlaps assertEquals(false, interval37.abuts(new Interval(4, 6))); // overlaps assertEquals(false, interval37.abuts(new Interval(5, 6))); // overlaps assertEquals(false, interval37.abuts(new Interval(6, 6))); // overlaps assertEquals(false, interval37.abuts(new Interval(2, 7))); // overlaps assertEquals(false, interval37.abuts(new Interval(3, 7))); // overlaps assertEquals(false, interval37.abuts(new Interval(4, 7))); // overlaps assertEquals(false, interval37.abuts(new Interval(5, 7))); // overlaps assertEquals(false, interval37.abuts(new Interval(6, 7))); // overlaps assertEquals(true, interval37.abuts(new Interval(7, 7))); assertEquals(false, interval37.abuts(new Interval(2, 8))); // overlaps assertEquals(false, interval37.abuts(new Interval(3, 8))); // overlaps assertEquals(false, interval37.abuts(new Interval(4, 8))); // overlaps assertEquals(false, interval37.abuts(new Interval(5, 8))); // overlaps assertEquals(false, interval37.abuts(new Interval(6, 8))); // overlaps assertEquals(true, interval37.abuts(new Interval(7, 8))); assertEquals(false, interval37.abuts(new Interval(8, 8))); // gap after assertEquals(false, interval37.abuts(new Interval(8, 9))); // gap after assertEquals(false, interval37.abuts(new Interval(9, 9))); // gap after } public void testAbuts_RInterval_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.abuts((ReadableInterval) null)); // gap before DateTimeUtils.setCurrentMillisFixed(3); assertEquals(true, interval37.abuts((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval37.abuts((ReadableInterval) null)); // overlaps DateTimeUtils.setCurrentMillisFixed(6); assertEquals(false, interval37.abuts((ReadableInterval) null)); // overlaps DateTimeUtils.setCurrentMillisFixed(7); assertEquals(true, interval37.abuts((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.abuts((ReadableInterval) null)); // gap after } //----------------------------------------------------------------------- public void testIsEqual_RI() { assertEquals(false, interval37.isEqual(interval33)); assertEquals(true, interval37.isEqual(interval37)); } //----------------------------------------------------------------------- public void testIsBefore_long() { assertEquals(false, interval37.isBefore(2)); assertEquals(false, interval37.isBefore(3)); assertEquals(false, interval37.isBefore(4)); assertEquals(false, interval37.isBefore(5)); assertEquals(false, interval37.isBefore(6)); assertEquals(true, interval37.isBefore(7)); assertEquals(true, interval37.isBefore(8)); } public void testIsBeforeNow() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.isBeforeNow()); DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval37.isBeforeNow()); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval37.isBeforeNow()); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(false, interval37.isBeforeNow()); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(true, interval37.isBeforeNow()); DateTimeUtils.setCurrentMillisFixed(8); assertEquals(true, interval37.isBeforeNow()); } public void testIsBefore_RI() { assertEquals(false, interval37.isBefore(new Instant(2))); assertEquals(false, interval37.isBefore(new Instant(3))); assertEquals(false, interval37.isBefore(new Instant(4))); assertEquals(false, interval37.isBefore(new Instant(5))); assertEquals(false, interval37.isBefore(new Instant(6))); assertEquals(true, interval37.isBefore(new Instant(7))); assertEquals(true, interval37.isBefore(new Instant(8))); } public void testIsBefore_RI_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.isBefore((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval37.isBefore((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval37.isBefore((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(false, interval37.isBefore((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(true, interval37.isBefore((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(8); assertEquals(true, interval37.isBefore((ReadableInstant) null)); } public void testIsBefore_RInterval() { assertEquals(false, interval37.isBefore(new Interval(Long.MIN_VALUE, 2))); assertEquals(false, interval37.isBefore(new Interval(Long.MIN_VALUE, 3))); assertEquals(false, interval37.isBefore(new Interval(Long.MIN_VALUE, 4))); assertEquals(false, interval37.isBefore(new Interval(6, Long.MAX_VALUE))); assertEquals(true, interval37.isBefore(new Interval(7, Long.MAX_VALUE))); assertEquals(true, interval37.isBefore(new Interval(8, Long.MAX_VALUE))); } public void testIsBefore_RInterval_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(false, interval37.isBefore((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval37.isBefore((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval37.isBefore((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(false, interval37.isBefore((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(true, interval37.isBefore((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(8); assertEquals(true, interval37.isBefore((ReadableInterval) null)); } //----------------------------------------------------------------------- public void testIsAfter_long() { assertEquals(true, interval37.isAfter(2)); assertEquals(false, interval37.isAfter(3)); assertEquals(false, interval37.isAfter(4)); assertEquals(false, interval37.isAfter(5)); assertEquals(false, interval37.isAfter(6)); assertEquals(false, interval37.isAfter(7)); assertEquals(false, interval37.isAfter(8)); } public void testIsAfterNow() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(true, interval37.isAfterNow()); DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval37.isAfterNow()); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval37.isAfterNow()); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(false, interval37.isAfterNow()); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(false, interval37.isAfterNow()); DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.isAfterNow()); } public void testIsAfter_RI() { assertEquals(true, interval37.isAfter(new Instant(2))); assertEquals(false, interval37.isAfter(new Instant(3))); assertEquals(false, interval37.isAfter(new Instant(4))); assertEquals(false, interval37.isAfter(new Instant(5))); assertEquals(false, interval37.isAfter(new Instant(6))); assertEquals(false, interval37.isAfter(new Instant(7))); assertEquals(false, interval37.isAfter(new Instant(8))); } public void testIsAfter_RI_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(true, interval37.isAfter((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(3); assertEquals(false, interval37.isAfter((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval37.isAfter((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(false, interval37.isAfter((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(false, interval37.isAfter((ReadableInstant) null)); DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.isAfter((ReadableInstant) null)); } public void testIsAfter_RInterval() { assertEquals(true, interval37.isAfter(new Interval(Long.MIN_VALUE, 2))); assertEquals(true, interval37.isAfter(new Interval(Long.MIN_VALUE, 3))); assertEquals(false, interval37.isAfter(new Interval(Long.MIN_VALUE, 4))); assertEquals(false, interval37.isAfter(new Interval(6, Long.MAX_VALUE))); assertEquals(false, interval37.isAfter(new Interval(7, Long.MAX_VALUE))); assertEquals(false, interval37.isAfter(new Interval(8, Long.MAX_VALUE))); } public void testIsAfter_RInterval_null() { DateTimeUtils.setCurrentMillisFixed(2); assertEquals(true, interval37.isAfter((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(3); assertEquals(true, interval37.isAfter((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(4); assertEquals(false, interval37.isAfter((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(6); assertEquals(false, interval37.isAfter((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(7); assertEquals(false, interval37.isAfter((ReadableInterval) null)); DateTimeUtils.setCurrentMillisFixed(8); assertEquals(false, interval37.isAfter((ReadableInterval) null)); } //----------------------------------------------------------------------- public void testToInterval1() { Interval test = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval result = test.toInterval(); assertSame(test, result); } //----------------------------------------------------------------------- public void testToMutableInterval1() { Interval test = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); MutableInterval result = test.toMutableInterval(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToPeriod() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS); Interval base = new Interval(dt1, dt2); Period test = base.toPeriod(); Period expected = new Period(dt1, dt2, PeriodType.standard()); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToPeriod_PeriodType1() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, COPTIC_PARIS); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, COPTIC_PARIS); Interval base = new Interval(dt1, dt2); Period test = base.toPeriod(null); Period expected = new Period(dt1, dt2, PeriodType.standard()); assertEquals(expected, test); } public void testToPeriod_PeriodType2() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18); Interval base = new Interval(dt1, dt2); Period test = base.toPeriod(PeriodType.yearWeekDayTime()); Period expected = new Period(dt1, dt2, PeriodType.yearWeekDayTime()); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Interval test = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Interval result = (Interval) ois.readObject(); ois.close(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToString() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, DateTimeZone.UTC); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, DateTimeZone.UTC); Interval test = new Interval(dt1, dt2); assertEquals("2004-06-09T07:08:09.010Z/2005-08-13T12:14:16.018Z", test.toString()); } public void testToString_reparse() { DateTime dt1 = new DateTime(2004, 6, 9, 7, 8, 9, 10, DateTimeZone.getDefault()); DateTime dt2 = new DateTime(2005, 8, 13, 12, 14, 16, 18, DateTimeZone.getDefault()); Interval test = new Interval(dt1, dt2); assertEquals(test, new Interval(test.toString())); } //----------------------------------------------------------------------- public void testWithChronology1() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withChronology(BuddhistChronology.getInstance()); assertEquals(new Interval(TEST_TIME1, TEST_TIME2, BuddhistChronology.getInstance()), test); } public void testWithChronology2() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withChronology(null); assertEquals(new Interval(TEST_TIME1, TEST_TIME2, ISOChronology.getInstance()), test); } public void testWithChronology3() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withChronology(COPTIC_PARIS); assertSame(base, test); } //----------------------------------------------------------------------- public void testWithStartMillis_long1() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withStartMillis(TEST_TIME1 - 1); assertEquals(new Interval(TEST_TIME1 - 1, TEST_TIME2, COPTIC_PARIS), test); } public void testWithStartMillis_long2() { Interval test = new Interval(TEST_TIME1, TEST_TIME2); try { test.withStartMillis(TEST_TIME2 + 1); fail(); } catch (IllegalArgumentException ex) {} } public void testWithStartMillis_long3() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withStartMillis(TEST_TIME1); assertSame(base, test); } //----------------------------------------------------------------------- public void testWithStartInstant_RI1() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withStart(new Instant(TEST_TIME1 - 1)); assertEquals(new Interval(TEST_TIME1 - 1, TEST_TIME2, COPTIC_PARIS), test); } public void testWithStartInstant_RI2() { Interval test = new Interval(TEST_TIME1, TEST_TIME2); try { test.withStart(new Instant(TEST_TIME2 + 1)); fail(); } catch (IllegalArgumentException ex) {} } public void testWithStartInstant_RI3() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withStart(null); assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS), test); } //----------------------------------------------------------------------- public void testWithEndMillis_long1() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withEndMillis(TEST_TIME2 - 1); assertEquals(new Interval(TEST_TIME1, TEST_TIME2 - 1, COPTIC_PARIS), test); } public void testWithEndMillis_long2() { Interval test = new Interval(TEST_TIME1, TEST_TIME2); try { test.withEndMillis(TEST_TIME1 - 1); fail(); } catch (IllegalArgumentException ex) {} } public void testWithEndMillis_long3() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withEndMillis(TEST_TIME2); assertSame(base, test); } //----------------------------------------------------------------------- public void testWithEndInstant_RI1() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withEnd(new Instant(TEST_TIME2 - 1)); assertEquals(new Interval(TEST_TIME1, TEST_TIME2 - 1, COPTIC_PARIS), test); } public void testWithEndInstant_RI2() { Interval test = new Interval(TEST_TIME1, TEST_TIME2); try { test.withEnd(new Instant(TEST_TIME1 - 1)); fail(); } catch (IllegalArgumentException ex) {} } public void testWithEndInstant_RI3() { Interval base = new Interval(TEST_TIME1, TEST_TIME2, COPTIC_PARIS); Interval test = base.withEnd(null); assertEquals(new Interval(TEST_TIME1, TEST_TIME_NOW, COPTIC_PARIS), test); } //----------------------------------------------------------------------- public void testWithDurationAfterStart1() throws Throwable { Duration dur = new Duration(TEST_TIME2 - TEST_TIME_NOW); Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS); Interval test = base.withDurationAfterStart(dur); assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS), test); } public void testWithDurationAfterStart2() throws Throwable { Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS); Interval test = base.withDurationAfterStart(null); assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS), test); } public void testWithDurationAfterStart3() throws Throwable { Duration dur = new Duration(-1); Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW); try { base.withDurationAfterStart(dur); fail(); } catch (IllegalArgumentException ex) {} } public void testWithDurationAfterStart4() throws Throwable { Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS); Interval test = base.withDurationAfterStart(base.toDuration()); assertSame(base, test); } //----------------------------------------------------------------------- public void testWithDurationBeforeEnd1() throws Throwable { Duration dur = new Duration(TEST_TIME_NOW - TEST_TIME1); Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS); Interval test = base.withDurationBeforeEnd(dur); assertEquals(new Interval(TEST_TIME1, TEST_TIME_NOW, COPTIC_PARIS), test); } public void testWithDurationBeforeEnd2() throws Throwable { Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS); Interval test = base.withDurationBeforeEnd(null); assertEquals(new Interval(TEST_TIME2, TEST_TIME2, COPTIC_PARIS), test); } public void testWithDurationBeforeEnd3() throws Throwable { Duration dur = new Duration(-1); Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW); try { base.withDurationBeforeEnd(dur); fail(); } catch (IllegalArgumentException ex) {} } public void testWithDurationBeforeEnd4() throws Throwable { Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS); Interval test = base.withDurationBeforeEnd(base.toDuration()); assertSame(base, test); } //----------------------------------------------------------------------- public void testWithPeriodAfterStart1() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW, COPTIC_PARIS); Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); Interval base = new Interval(dt, dt); Interval test = base.withPeriodAfterStart(dur); assertEquals(new Interval(dt, dur), test); } public void testWithPeriodAfterStart2() throws Throwable { Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS); Interval test = base.withPeriodAfterStart(null); assertEquals(new Interval(TEST_TIME_NOW, TEST_TIME_NOW, COPTIC_PARIS), test); } public void testWithPeriodAfterStart3() throws Throwable { Period per = new Period(0, 0, 0, 0, 0, 0, 0, -1); Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW); try { base.withPeriodAfterStart(per); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithPeriodBeforeEnd1() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW, COPTIC_PARIS); Period dur = new Period(0, 6, 0, 0, 1, 0, 0, 0); Interval base = new Interval(dt, dt); Interval test = base.withPeriodBeforeEnd(dur); assertEquals(new Interval(dur, dt), test); } public void testWithPeriodBeforeEnd2() throws Throwable { Interval base = new Interval(TEST_TIME_NOW, TEST_TIME2, COPTIC_PARIS); Interval test = base.withPeriodBeforeEnd(null); assertEquals(new Interval(TEST_TIME2, TEST_TIME2, COPTIC_PARIS), test); } public void testWithPeriodBeforeEnd3() throws Throwable { Period per = new Period(0, 0, 0, 0, 0, 0, 0, -1); Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW); try { base.withPeriodBeforeEnd(per); fail(); } catch (IllegalArgumentException ex) {} } } joda-time-2.3/src/test/java/org/joda/time/TestYearMonthDay_Basics.java0000644000175000017500000010420712200501234025234 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * This class is a Junit unit test for YearMonthDay. * * @author Stephen Colebourne */ @SuppressWarnings("deprecation") public class TestYearMonthDay_Basics extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON); private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO); private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC(); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO); private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC(); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestYearMonthDay_Basics.class); } public TestYearMonthDay_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testGet() { YearMonthDay test = new YearMonthDay(); assertEquals(1970, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.hourOfDay()); fail(); } catch (IllegalArgumentException ex) {} } public void testSize() { YearMonthDay test = new YearMonthDay(); assertEquals(3, test.size()); } public void testGetFieldType() { YearMonthDay test = new YearMonthDay(COPTIC_PARIS); assertSame(DateTimeFieldType.year(), test.getFieldType(0)); assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(1)); assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(2)); try { test.getFieldType(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getFieldType(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetFieldTypes() { YearMonthDay test = new YearMonthDay(COPTIC_PARIS); DateTimeFieldType[] fields = test.getFieldTypes(); assertSame(DateTimeFieldType.year(), fields[0]); assertSame(DateTimeFieldType.monthOfYear(), fields[1]); assertSame(DateTimeFieldType.dayOfMonth(), fields[2]); assertNotSame(test.getFieldTypes(), test.getFieldTypes()); } public void testGetField() { YearMonthDay test = new YearMonthDay(COPTIC_PARIS); assertSame(COPTIC_UTC.year(), test.getField(0)); assertSame(COPTIC_UTC.monthOfYear(), test.getField(1)); assertSame(COPTIC_UTC.dayOfMonth(), test.getField(2)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetFields() { YearMonthDay test = new YearMonthDay(COPTIC_PARIS); DateTimeField[] fields = test.getFields(); assertSame(COPTIC_UTC.year(), fields[0]); assertSame(COPTIC_UTC.monthOfYear(), fields[1]); assertSame(COPTIC_UTC.dayOfMonth(), fields[2]); assertNotSame(test.getFields(), test.getFields()); } public void testGetValue() { YearMonthDay test = new YearMonthDay(); assertEquals(1970, test.getValue(0)); assertEquals(6, test.getValue(1)); assertEquals(9, test.getValue(2)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(3); } catch (IndexOutOfBoundsException ex) {} } public void testGetValues() { YearMonthDay test = new YearMonthDay(); int[] values = test.getValues(); assertEquals(1970, values[0]); assertEquals(6, values[1]); assertEquals(9, values[2]); assertNotSame(test.getValues(), test.getValues()); } public void testIsSupported() { YearMonthDay test = new YearMonthDay(COPTIC_PARIS); assertEquals(true, test.isSupported(DateTimeFieldType.year())); assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear())); assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth())); assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay())); } public void testEqualsHashCode() { YearMonthDay test1 = new YearMonthDay(1970, 6, 9, COPTIC_PARIS); YearMonthDay test2 = new YearMonthDay(1970, 6, 9, COPTIC_PARIS); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); YearMonthDay test3 = new YearMonthDay(1971, 6, 9); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInstant())); assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE)); } class MockInstant extends MockPartial { public Chronology getChronology() { return COPTIC_UTC; } public DateTimeField[] getFields() { return new DateTimeField[] { COPTIC_UTC.year(), COPTIC_UTC.monthOfYear(), COPTIC_UTC.dayOfMonth(), }; } public int[] getValues() { return new int[] {1970, 6, 9}; } } //----------------------------------------------------------------------- public void testCompareTo() { YearMonthDay test1 = new YearMonthDay(2005, 6, 2); YearMonthDay test1a = new YearMonthDay(2005, 6, 2); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); YearMonthDay test2 = new YearMonthDay(2005, 7, 2); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); YearMonthDay test3 = new YearMonthDay(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth(), }; int[] values = new int[] {2005, 6, 2}; Partial p = new Partial(types, values); assertEquals(0, test1.compareTo(p)); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} try { test1.compareTo(new TimeOfDay()); fail(); } catch (ClassCastException ex) {} Partial partial = new Partial() .with(DateTimeFieldType.centuryOfEra(), 1) .with(DateTimeFieldType.halfdayOfDay(), 0) .with(DateTimeFieldType.dayOfMonth(), 9); try { new YearMonthDay(1970, 6, 9).compareTo(partial); fail(); } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_YMD() { YearMonthDay test1 = new YearMonthDay(2005, 6, 2); YearMonthDay test1a = new YearMonthDay(2005, 6, 2); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); YearMonthDay test2 = new YearMonthDay(2005, 7, 2); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); YearMonthDay test3 = new YearMonthDay(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); try { new YearMonthDay(2005, 7, 2).isEqual(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsBefore_YMD() { YearMonthDay test1 = new YearMonthDay(2005, 6, 2); YearMonthDay test1a = new YearMonthDay(2005, 6, 2); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); YearMonthDay test2 = new YearMonthDay(2005, 7, 2); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); YearMonthDay test3 = new YearMonthDay(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new YearMonthDay(2005, 7, 2).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsAfter_YMD() { YearMonthDay test1 = new YearMonthDay(2005, 6, 2); YearMonthDay test1a = new YearMonthDay(2005, 6, 2); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); YearMonthDay test2 = new YearMonthDay(2005, 7, 2); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); YearMonthDay test3 = new YearMonthDay(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new YearMonthDay(2005, 7, 2).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testWithChronologyRetainFields_Chrono() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); YearMonthDay test = base.withChronologyRetainFields(BUDDHIST_TOKYO); check(base, 2005, 6, 9); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 2005, 6, 9); assertEquals(BUDDHIST_UTC, test.getChronology()); } public void testWithChronologyRetainFields_sameChrono() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); YearMonthDay test = base.withChronologyRetainFields(COPTIC_TOKYO); assertSame(base, test); } public void testWithChronologyRetainFields_nullChrono() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); YearMonthDay test = base.withChronologyRetainFields(null); check(base, 2005, 6, 9); assertEquals(COPTIC_UTC, base.getChronology()); check(test, 2005, 6, 9); assertEquals(ISO_UTC, test.getChronology()); } public void testWithChronologyRetainFields_invalidInNewChrono() { YearMonthDay base = new YearMonthDay(2005, 1, 31, ISO_UTC); try { base.withChronologyRetainFields(COPTIC_UTC); fail(); } catch (IllegalArgumentException ex) { // expected } } //----------------------------------------------------------------------- public void testWithField1() { YearMonthDay test = new YearMonthDay(2004, 6, 9); YearMonthDay result = test.withField(DateTimeFieldType.year(), 2006); assertEquals(new YearMonthDay(2004, 6, 9), test); assertEquals(new YearMonthDay(2006, 6, 9), result); } public void testWithField2() { YearMonthDay test = new YearMonthDay(2004, 6, 9); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField3() { YearMonthDay test = new YearMonthDay(2004, 6, 9); try { test.withField(DateTimeFieldType.hourOfDay(), 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithField4() { YearMonthDay test = new YearMonthDay(2004, 6, 9); YearMonthDay result = test.withField(DateTimeFieldType.year(), 2004); assertEquals(new YearMonthDay(2004, 6, 9), test); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithFieldAdded1() { YearMonthDay test = new YearMonthDay(2004, 6, 9); YearMonthDay result = test.withFieldAdded(DurationFieldType.years(), 6); assertEquals(new YearMonthDay(2004, 6, 9), test); assertEquals(new YearMonthDay(2010, 6, 9), result); } public void testWithFieldAdded2() { YearMonthDay test = new YearMonthDay(2004, 6, 9); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded3() { YearMonthDay test = new YearMonthDay(2004, 6, 9); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} } public void testWithFieldAdded4() { YearMonthDay test = new YearMonthDay(2004, 6, 9); YearMonthDay result = test.withFieldAdded(DurationFieldType.years(), 0); assertSame(test, result); } public void testWithFieldAdded5() { YearMonthDay test = new YearMonthDay(2004, 6, 9); try { test.withFieldAdded(DurationFieldType.hours(), 6); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPlus_RP() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8)); YearMonthDay expected = new YearMonthDay(2003, 7, 7, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plus((ReadablePeriod) null); assertSame(test, result); } public void testPlusYears_int() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.plusYears(1); YearMonthDay expected = new YearMonthDay(2003, 5, 3, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusYears(0); assertSame(test, result); } public void testPlusMonths_int() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.plusMonths(1); YearMonthDay expected = new YearMonthDay(2002, 6, 3, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusMonths(0); assertSame(test, result); } public void testPlusDays_int() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.plusDays(1); YearMonthDay expected = new YearMonthDay(2002, 5, 4, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.plusDays(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_RP() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1)); YearMonthDay expected = new YearMonthDay(2001, 4, 2, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minus((ReadablePeriod) null); assertSame(test, result); } public void testMinusYears_int() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.minusYears(1); YearMonthDay expected = new YearMonthDay(2001, 5, 3, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusYears(0); assertSame(test, result); } public void testMinusMonths_int() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.minusMonths(1); YearMonthDay expected = new YearMonthDay(2002, 4, 3, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusMonths(0); assertSame(test, result); } public void testMinusDays_int() { YearMonthDay test = new YearMonthDay(2002, 5, 3, BuddhistChronology.getInstance()); YearMonthDay result = test.minusDays(1); YearMonthDay expected = new YearMonthDay(2002, 5, 2, BuddhistChronology.getInstance()); assertEquals(expected, result); result = test.minusDays(0); assertSame(test, result); } //----------------------------------------------------------------------- public void testToLocalDate() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_UTC); LocalDate test = base.toLocalDate(); assertEquals(new LocalDate(2005, 6, 9, COPTIC_UTC), test); } //----------------------------------------------------------------------- public void testToDateTimeAtMidnight() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtMidnight(); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test); } //----------------------------------------------------------------------- public void testToDateTimeAtMidnight_Zone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtMidnight(TOKYO); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_TOKYO), test); } public void testToDateTimeAtMidnight_nullZone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); DateTime test = base.toDateTimeAtMidnight((DateTimeZone) null); check(base, 2005, 6, 9); assertEquals(new DateTime(2005, 6, 9, 0, 0, 0, 0, COPTIC_LONDON), test); } //----------------------------------------------------------------------- public void testToDateTimeAtCurrentTime() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeAtCurrentTime(); check(base, 2005, 6, 9); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTimeAtCurrentTime_Zone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeAtCurrentTime(TOKYO); check(base, 2005, 6, 9); DateTime expected = new DateTime(dt.getMillis(), COPTIC_TOKYO); expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } public void testToDateTimeAtCurrentTime_nullZone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant DateTime dt = new DateTime(2004, 6, 9, 6, 7, 8, 9); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTimeAtCurrentTime((DateTimeZone) null); check(base, 2005, 6, 9); DateTime expected = new DateTime(dt.getMillis(), COPTIC_LONDON); expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTime_TOD() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant TimeOfDay tod = new TimeOfDay(12, 13, 14, 15, BUDDHIST_TOKYO); DateTime test = base.toDateTime(tod); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON); assertEquals(expected, test); } public void testToDateTime_nullTOD() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_LONDON).getMillis(); DateTimeUtils.setCurrentMillisFixed(now); DateTime test = base.toDateTime((TimeOfDay) null); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateTime_TOD_Zone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant TimeOfDay tod = new TimeOfDay(12, 13, 14, 15, BUDDHIST_TOKYO); DateTime test = base.toDateTime(tod, TOKYO); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO); assertEquals(expected, test); } public void testToDateTime_TOD_nullZone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant TimeOfDay tod = new TimeOfDay(12, 13, 14, 15, BUDDHIST_TOKYO); DateTime test = base.toDateTime(tod, null); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_LONDON); assertEquals(expected, test); } public void testToDateTime_nullTOD_Zone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant long now = new DateTime(2004, 5, 8, 12, 13, 14, 15, COPTIC_TOKYO).getMillis(); DateTimeUtils.setCurrentMillisFixed(now); DateTime test = base.toDateTime((TimeOfDay) null, TOKYO); check(base, 2005, 6, 9); DateTime expected = new DateTime(2005, 6, 9, 12, 13, 14, 15, COPTIC_TOKYO); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToDateMidnight() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); DateMidnight test = base.toDateMidnight(); check(base, 2005, 6, 9); assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test); } //----------------------------------------------------------------------- public void testToDateMidnight_Zone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); DateMidnight test = base.toDateMidnight(TOKYO); check(base, 2005, 6, 9); assertEquals(new DateMidnight(2005, 6, 9, COPTIC_TOKYO), test); } public void testToDateMidnight_nullZone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); DateMidnight test = base.toDateMidnight((DateTimeZone) null); check(base, 2005, 6, 9); assertEquals(new DateMidnight(2005, 6, 9, COPTIC_LONDON), test); } //----------------------------------------------------------------------- public void testToDateTime_RI() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTime test = base.toDateTime(dt); check(base, 2005, 6, 9); DateTime expected = dt; expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } public void testToDateTime_nullRI() { YearMonthDay base = new YearMonthDay(2005, 6, 9); DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7); DateTimeUtils.setCurrentMillisFixed(dt.getMillis()); DateTime test = base.toDateTime((ReadableInstant) null); check(base, 2005, 6, 9); DateTime expected = dt; expected = expected.year().setCopy(2005); expected = expected.monthOfYear().setCopy(6); expected = expected.dayOfMonth().setCopy(9); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToInterval() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(); check(base, 2005, 6, 9); DateTime start = base.toDateTime(TimeOfDay.MIDNIGHT); DateTime end = start.plus(Period.days(1)); Interval expected = new Interval(start, end); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testToInterval_Zone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(TOKYO); check(base, 2005, 6, 9); DateTime start = base.toDateTime(TimeOfDay.MIDNIGHT, TOKYO); DateTime end = start.plus(Period.days(1)); Interval expected = new Interval(start, end); assertEquals(expected, test); } public void testToInterval_nullZone() { YearMonthDay base = new YearMonthDay(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant Interval test = base.toInterval(null); check(base, 2005, 6, 9); DateTime start = base.toDateTime(TimeOfDay.MIDNIGHT, LONDON); DateTime end = start.plus(Period.days(1)); Interval expected = new Interval(start, end); assertEquals(expected, test); } //----------------------------------------------------------------------- public void testWithers() { YearMonthDay test = new YearMonthDay(1970, 6, 9); check(test.withYear(2000), 2000, 6, 9); check(test.withMonthOfYear(2), 1970, 2, 9); check(test.withDayOfMonth(2), 1970, 6, 2); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testProperty() { YearMonthDay test = new YearMonthDay(2005, 6, 9); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear())); assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth())); try { test.property(DateTimeFieldType.millisOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testSerialization() throws Exception { YearMonthDay test = new YearMonthDay(1972, 6, 9, COPTIC_PARIS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); YearMonthDay result = (YearMonthDay) ois.readObject(); ois.close(); assertEquals(test, result); assertTrue(Arrays.equals(test.getValues(), result.getValues())); assertTrue(Arrays.equals(test.getFields(), result.getFields())); assertEquals(test.getChronology(), result.getChronology()); } //----------------------------------------------------------------------- public void testToString() { YearMonthDay test = new YearMonthDay(2002, 6, 9); assertEquals("2002-06-09", test.toString()); } //----------------------------------------------------------------------- public void testToString_String() { YearMonthDay test = new YearMonthDay(2002, 6, 9); assertEquals("2002 \ufffd\ufffd", test.toString("yyyy HH")); assertEquals("2002-06-09", test.toString((String) null)); } //----------------------------------------------------------------------- public void testToString_String_Locale() { YearMonthDay test = new YearMonthDay(2002, 6, 9); assertEquals("\ufffd 9/6", test.toString("EEE d/M", Locale.ENGLISH)); assertEquals("\ufffd 9/6", test.toString("EEE d/M", Locale.FRENCH)); assertEquals("2002-06-09", test.toString(null, Locale.ENGLISH)); assertEquals("\ufffd 9/6", test.toString("EEE d/M", null)); assertEquals("2002-06-09", test.toString(null, null)); } //----------------------------------------------------------------------- public void testToString_DTFormatter() { YearMonthDay test = new YearMonthDay(2002, 6, 9); assertEquals("2002 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("yyyy HH"))); assertEquals("2002-06-09", test.toString((DateTimeFormatter) null)); } //----------------------------------------------------------------------- private void check(YearMonthDay test, int hour, int min, int sec) { assertEquals(hour, test.getYear()); assertEquals(min, test.getMonthOfYear()); assertEquals(sec, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestMutableDateTime_Properties.java0000644000175000017500000012220011564251364026641 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for DateTime. * * @author Stephen Colebourne * @author Mike Schrag */ public class TestMutableDateTime_Properties extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) //private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 Fri private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 Tue private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale locale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMutableDateTime_Properties.class); } public TestMutableDateTime_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); locale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); Locale.setDefault(locale); zone = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testPropertyGetEra() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().era(), test.era().getField()); assertEquals("era", test.era().getName()); assertEquals("Property[era]", test.era().toString()); assertSame(test, test.era().getMutableDateTime()); assertEquals(1, test.era().get()); assertEquals("AD", test.era().getAsText()); assertEquals("ap. J.-C.", test.era().getAsText(Locale.FRENCH)); assertEquals("AD", test.era().getAsShortText()); assertEquals("ap. J.-C.", test.era().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().eras(), test.era().getDurationField()); assertEquals(null, test.era().getRangeDurationField()); assertEquals(2, test.era().getMaximumTextLength(null)); assertEquals(9, test.era().getMaximumTextLength(Locale.FRENCH)); assertEquals(2, test.era().getMaximumShortTextLength(null)); assertEquals(9, test.era().getMaximumShortTextLength(Locale.FRENCH)); } //----------------------------------------------------------------------- public void testPropertyGetYearOfEra() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().yearOfEra(), test.yearOfEra().getField()); assertEquals("yearOfEra", test.yearOfEra().getName()); assertEquals("Property[yearOfEra]", test.yearOfEra().toString()); assertEquals(2004, test.yearOfEra().get()); assertEquals("2004", test.yearOfEra().getAsText()); assertEquals("2004", test.yearOfEra().getAsText(Locale.FRENCH)); assertEquals("2004", test.yearOfEra().getAsShortText()); assertEquals("2004", test.yearOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfEra().getDurationField()); assertEquals(null, test.yearOfEra().getRangeDurationField()); assertEquals(9, test.yearOfEra().getMaximumTextLength(null)); assertEquals(9, test.yearOfEra().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetCenturyOfEra() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().centuryOfEra(), test.centuryOfEra().getField()); assertEquals("centuryOfEra", test.centuryOfEra().getName()); assertEquals("Property[centuryOfEra]", test.centuryOfEra().toString()); assertEquals(20, test.centuryOfEra().get()); assertEquals("20", test.centuryOfEra().getAsText()); assertEquals("20", test.centuryOfEra().getAsText(Locale.FRENCH)); assertEquals("20", test.centuryOfEra().getAsShortText()); assertEquals("20", test.centuryOfEra().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().centuries(), test.centuryOfEra().getDurationField()); assertEquals(null, test.centuryOfEra().getRangeDurationField()); assertEquals(7, test.centuryOfEra().getMaximumTextLength(null)); assertEquals(7, test.centuryOfEra().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetYearOfCentury() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().yearOfCentury(), test.yearOfCentury().getField()); assertEquals("yearOfCentury", test.yearOfCentury().getName()); assertEquals("Property[yearOfCentury]", test.yearOfCentury().toString()); assertEquals(4, test.yearOfCentury().get()); assertEquals("4", test.yearOfCentury().getAsText()); assertEquals("4", test.yearOfCentury().getAsText(Locale.FRENCH)); assertEquals("4", test.yearOfCentury().getAsShortText()); assertEquals("4", test.yearOfCentury().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.yearOfCentury().getDurationField()); assertEquals(test.getChronology().centuries(), test.yearOfCentury().getRangeDurationField()); assertEquals(2, test.yearOfCentury().getMaximumTextLength(null)); assertEquals(2, test.yearOfCentury().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetWeekyear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().weekyear(), test.weekyear().getField()); assertEquals("weekyear", test.weekyear().getName()); assertEquals("Property[weekyear]", test.weekyear().toString()); assertEquals(2004, test.weekyear().get()); assertEquals("2004", test.weekyear().getAsText()); assertEquals("2004", test.weekyear().getAsText(Locale.FRENCH)); assertEquals("2004", test.weekyear().getAsShortText()); assertEquals("2004", test.weekyear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().weekyears(), test.weekyear().getDurationField()); assertEquals(null, test.weekyear().getRangeDurationField()); assertEquals(9, test.weekyear().getMaximumTextLength(null)); assertEquals(9, test.weekyear().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertEquals(2004, test.year().get()); assertEquals("2004", test.year().getAsText()); assertEquals("2004", test.year().getAsText(Locale.FRENCH)); assertEquals("2004", test.year().getAsShortText()); assertEquals("2004", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292278993, test.year().getMaximumValue()); assertEquals(292278993, test.year().getMaximumValueOverall()); } public void testPropertyAddYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.year().add(9); assertEquals("2013-06-09T00:00:00.000+01:00", test.toString()); } public void testPropertyAddWrapFieldYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.year().addWrapField(9); assertEquals("2013-06-09T00:00:00.000+01:00", test.toString()); } public void testPropertySetYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.year().set(1960); assertEquals("1960-06-09T00:00:00.000+01:00", test.toString()); } public void testPropertySetTextYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.year().set("1960"); assertEquals("1960-06-09T00:00:00.000+01:00", test.toString()); } //----------------------------------------------------------------------- public void testPropertyGetMonthOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertEquals(6, test.monthOfYear().get()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new MutableDateTime(2004, 7, 9, 0, 0, 0, 0); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyAddMonthOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.monthOfYear().add(6); assertEquals("2004-12-09T00:00:00.000Z", test.toString()); } public void testPropertyAddWrapFieldMonthOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.monthOfYear().addWrapField(8); assertEquals("2004-02-09T00:00:00.000Z", test.toString()); } public void testPropertySetMonthOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.monthOfYear().set(12); assertEquals("2004-12-09T00:00:00.000Z", test.toString()); } public void testPropertySetTextMonthOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.monthOfYear().set("12"); assertEquals("2004-12-09T00:00:00.000Z", test.toString()); test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.monthOfYear().set("December"); assertEquals("2004-12-09T00:00:00.000Z", test.toString()); test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.monthOfYear().set("Dec"); assertEquals("2004-12-09T00:00:00.000Z", test.toString()); } //----------------------------------------------------------------------- public void testPropertyGetDayOfMonth() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertEquals(9, test.dayOfMonth().get()); assertEquals("9", test.dayOfMonth().getAsText()); assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("9", test.dayOfMonth().getAsShortText()); assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); assertEquals(false, test.dayOfMonth().isLeap()); assertEquals(0, test.dayOfMonth().getLeapAmount()); assertEquals(null, test.dayOfMonth().getLeapDurationField()); } public void testPropertyAddDayOfMonth() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfMonth().add(9); assertEquals("2004-06-18T00:00:00.000+01:00", test.toString()); } public void testPropertyAddWrapFieldDayOfMonth() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfMonth().addWrapField(22); assertEquals("2004-06-01T00:00:00.000+01:00", test.toString()); } public void testPropertySetDayOfMonth() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfMonth().set(12); assertEquals("2004-06-12T00:00:00.000+01:00", test.toString()); } public void testPropertySetTextDayOfMonth() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfMonth().set("12"); assertEquals("2004-06-12T00:00:00.000+01:00", test.toString()); } //----------------------------------------------------------------------- public void testPropertyGetDayOfYear() { // 31+29+31+30+31+9 = 161 MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfYear(), test.dayOfYear().getField()); assertEquals("dayOfYear", test.dayOfYear().getName()); assertEquals("Property[dayOfYear]", test.dayOfYear().toString()); assertEquals(161, test.dayOfYear().get()); assertEquals("161", test.dayOfYear().getAsText()); assertEquals("161", test.dayOfYear().getAsText(Locale.FRENCH)); assertEquals("161", test.dayOfYear().getAsShortText()); assertEquals("161", test.dayOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.dayOfYear().getRangeDurationField()); assertEquals(3, test.dayOfYear().getMaximumTextLength(null)); assertEquals(3, test.dayOfYear().getMaximumShortTextLength(null)); assertEquals(false, test.dayOfYear().isLeap()); assertEquals(0, test.dayOfYear().getLeapAmount()); assertEquals(null, test.dayOfYear().getLeapDurationField()); } public void testPropertyAddDayOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfYear().add(9); assertEquals("2004-06-18T00:00:00.000+01:00", test.toString()); } public void testPropertyAddWrapFieldDayOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfYear().addWrapField(206); assertEquals("2004-01-01T00:00:00.000Z", test.toString()); } public void testPropertySetDayOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfYear().set(12); assertEquals("2004-01-12T00:00:00.000Z", test.toString()); } public void testPropertySetTextDayOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfYear().set("12"); assertEquals("2004-01-12T00:00:00.000Z", test.toString()); } //----------------------------------------------------------------------- public void testPropertyGetWeekOfWeekyear() { // 2002-01-01 = Thu // 2002-12-31 = Thu (+364 days) // 2003-12-30 = Thu (+364 days) // 2004-01-03 = Mon W1 // 2004-01-31 = Mon (+28 days) W5 // 2004-02-28 = Mon (+28 days) W9 // 2004-03-27 = Mon (+28 days) W13 // 2004-04-24 = Mon (+28 days) W17 // 2004-05-23 = Mon (+28 days) W21 // 2004-06-05 = Mon (+14 days) W23 // 2004-06-09 = Fri // 2004-12-25 = Mon W52 // 2005-01-01 = Mon W1 MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().weekOfWeekyear(), test.weekOfWeekyear().getField()); assertEquals("weekOfWeekyear", test.weekOfWeekyear().getName()); assertEquals("Property[weekOfWeekyear]", test.weekOfWeekyear().toString()); assertEquals(24, test.weekOfWeekyear().get()); assertEquals("24", test.weekOfWeekyear().getAsText()); assertEquals("24", test.weekOfWeekyear().getAsText(Locale.FRENCH)); assertEquals("24", test.weekOfWeekyear().getAsShortText()); assertEquals("24", test.weekOfWeekyear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().weeks(), test.weekOfWeekyear().getDurationField()); assertEquals(test.getChronology().weekyears(), test.weekOfWeekyear().getRangeDurationField()); assertEquals(2, test.weekOfWeekyear().getMaximumTextLength(null)); assertEquals(2, test.weekOfWeekyear().getMaximumShortTextLength(null)); assertEquals(false, test.weekOfWeekyear().isLeap()); assertEquals(0, test.weekOfWeekyear().getLeapAmount()); assertEquals(null, test.weekOfWeekyear().getLeapDurationField()); } public void testPropertyAddWeekOfWeekyear() { MutableDateTime test = new MutableDateTime(2004, 6, 7, 0, 0, 0, 0); test.weekOfWeekyear().add(1); assertEquals("2004-06-14T00:00:00.000+01:00", test.toString()); } public void testPropertyAddWrapFieldWeekOfWeekyear() { MutableDateTime test = new MutableDateTime(2004, 6, 7, 0, 0, 0, 0); test.weekOfWeekyear().addWrapField(30); assertEquals("2003-12-29T00:00:00.000Z", test.toString()); } public void testPropertySetWeekOfWeekyear() { MutableDateTime test = new MutableDateTime(2004, 6, 7, 0, 0, 0, 0); test.weekOfWeekyear().set(4); assertEquals("2004-01-19T00:00:00.000Z", test.toString()); } public void testPropertySetTextWeekOfWeekyear() { MutableDateTime test = new MutableDateTime(2004, 6, 7, 0, 0, 0, 0); test.weekOfWeekyear().set("4"); assertEquals("2004-01-19T00:00:00.000Z", test.toString()); } //----------------------------------------------------------------------- public void testPropertyGetDayOfWeek() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); assertSame(test.getChronology().dayOfWeek(), test.dayOfWeek().getField()); assertEquals("dayOfWeek", test.dayOfWeek().getName()); assertEquals("Property[dayOfWeek]", test.dayOfWeek().toString()); assertEquals(3, test.dayOfWeek().get()); assertEquals("Wednesday", test.dayOfWeek().getAsText()); assertEquals("mercredi", test.dayOfWeek().getAsText(Locale.FRENCH)); assertEquals("Wed", test.dayOfWeek().getAsShortText()); assertEquals("mer.", test.dayOfWeek().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfWeek().getDurationField()); assertEquals(test.getChronology().weeks(), test.dayOfWeek().getRangeDurationField()); assertEquals(9, test.dayOfWeek().getMaximumTextLength(null)); assertEquals(8, test.dayOfWeek().getMaximumTextLength(Locale.FRENCH)); assertEquals(3, test.dayOfWeek().getMaximumShortTextLength(null)); assertEquals(4, test.dayOfWeek().getMaximumShortTextLength(Locale.FRENCH)); assertEquals(1, test.dayOfWeek().getMinimumValue()); assertEquals(1, test.dayOfWeek().getMinimumValueOverall()); assertEquals(7, test.dayOfWeek().getMaximumValue()); assertEquals(7, test.dayOfWeek().getMaximumValueOverall()); assertEquals(false, test.dayOfWeek().isLeap()); assertEquals(0, test.dayOfWeek().getLeapAmount()); assertEquals(null, test.dayOfWeek().getLeapDurationField()); } public void testPropertyAddDayOfWeek() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfWeek().add(1); assertEquals("2004-06-10T00:00:00.000+01:00", test.toString()); } public void testPropertyAddLongDayOfWeek() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfWeek().add(1L); assertEquals("2004-06-10T00:00:00.000+01:00", test.toString()); } public void testPropertyAddWrapFieldDayOfWeek() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); // Wed test.dayOfWeek().addWrapField(5); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); } public void testPropertySetDayOfWeek() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfWeek().set(4); assertEquals("2004-06-10T00:00:00.000+01:00", test.toString()); } public void testPropertySetTextDayOfWeek() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfWeek().set("4"); assertEquals("2004-06-10T00:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfWeek().set("Mon"); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfWeek().set("Tuesday"); assertEquals("2004-06-08T00:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 0, 0, 0, 0); test.dayOfWeek().set("lundi", Locale.FRENCH); assertEquals("2004-06-07T00:00:00.000+01:00", test.toString()); } //----------------------------------------------------------------------- public void testPropertyGetHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().hourOfDay(), test.hourOfDay().getField()); assertEquals("hourOfDay", test.hourOfDay().getName()); assertEquals("Property[hourOfDay]", test.hourOfDay().toString()); assertEquals(13, test.hourOfDay().get()); assertEquals("13", test.hourOfDay().getAsText()); assertEquals("13", test.hourOfDay().getAsText(Locale.FRENCH)); assertEquals("13", test.hourOfDay().getAsShortText()); assertEquals("13", test.hourOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().hours(), test.hourOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.hourOfDay().getRangeDurationField()); assertEquals(2, test.hourOfDay().getMaximumTextLength(null)); assertEquals(2, test.hourOfDay().getMaximumShortTextLength(null)); } public void testPropertyRoundFloorHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 0); test.hourOfDay().roundFloor(); assertEquals("2004-06-09T13:00:00.000+01:00", test.toString()); } public void testPropertyRoundCeilingHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 0); test.hourOfDay().roundCeiling(); assertEquals("2004-06-09T14:00:00.000+01:00", test.toString()); } public void testPropertyRoundHalfFloorHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 0); test.hourOfDay().roundHalfFloor(); assertEquals("2004-06-09T13:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 1); test.hourOfDay().roundHalfFloor(); assertEquals("2004-06-09T14:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 13, 29, 59, 999); test.hourOfDay().roundHalfFloor(); assertEquals("2004-06-09T13:00:00.000+01:00", test.toString()); } public void testPropertyRoundHalfCeilingHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 0); test.hourOfDay().roundHalfCeiling(); assertEquals("2004-06-09T14:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 1); test.hourOfDay().roundHalfCeiling(); assertEquals("2004-06-09T14:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 13, 29, 59, 999); test.hourOfDay().roundHalfCeiling(); assertEquals("2004-06-09T13:00:00.000+01:00", test.toString()); } public void testPropertyRoundHalfEvenHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 0); test.hourOfDay().roundHalfEven(); assertEquals("2004-06-09T14:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 14, 30, 0, 0); test.hourOfDay().roundHalfEven(); assertEquals("2004-06-09T14:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 1); test.hourOfDay().roundHalfEven(); assertEquals("2004-06-09T14:00:00.000+01:00", test.toString()); test = new MutableDateTime(2004, 6, 9, 13, 29, 59, 999); test.hourOfDay().roundHalfEven(); assertEquals("2004-06-09T13:00:00.000+01:00", test.toString()); } public void testPropertyRemainderHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 30, 0, 0); assertEquals(30L * DateTimeConstants.MILLIS_PER_MINUTE, test.hourOfDay().remainder()); } //----------------------------------------------------------------------- public void testPropertyGetMinuteOfHour() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().minuteOfHour(), test.minuteOfHour().getField()); assertEquals("minuteOfHour", test.minuteOfHour().getName()); assertEquals("Property[minuteOfHour]", test.minuteOfHour().toString()); assertEquals(23, test.minuteOfHour().get()); assertEquals("23", test.minuteOfHour().getAsText()); assertEquals("23", test.minuteOfHour().getAsText(Locale.FRENCH)); assertEquals("23", test.minuteOfHour().getAsShortText()); assertEquals("23", test.minuteOfHour().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.minuteOfHour().getDurationField()); assertEquals(test.getChronology().hours(), test.minuteOfHour().getRangeDurationField()); assertEquals(2, test.minuteOfHour().getMaximumTextLength(null)); assertEquals(2, test.minuteOfHour().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetMinuteOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().minuteOfDay(), test.minuteOfDay().getField()); assertEquals("minuteOfDay", test.minuteOfDay().getName()); assertEquals("Property[minuteOfDay]", test.minuteOfDay().toString()); assertEquals(803, test.minuteOfDay().get()); assertEquals("803", test.minuteOfDay().getAsText()); assertEquals("803", test.minuteOfDay().getAsText(Locale.FRENCH)); assertEquals("803", test.minuteOfDay().getAsShortText()); assertEquals("803", test.minuteOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.minuteOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.minuteOfDay().getRangeDurationField()); assertEquals(4, test.minuteOfDay().getMaximumTextLength(null)); assertEquals(4, test.minuteOfDay().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetSecondOfMinute() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().secondOfMinute(), test.secondOfMinute().getField()); assertEquals("secondOfMinute", test.secondOfMinute().getName()); assertEquals("Property[secondOfMinute]", test.secondOfMinute().toString()); assertEquals(43, test.secondOfMinute().get()); assertEquals("43", test.secondOfMinute().getAsText()); assertEquals("43", test.secondOfMinute().getAsText(Locale.FRENCH)); assertEquals("43", test.secondOfMinute().getAsShortText()); assertEquals("43", test.secondOfMinute().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().seconds(), test.secondOfMinute().getDurationField()); assertEquals(test.getChronology().minutes(), test.secondOfMinute().getRangeDurationField()); assertEquals(2, test.secondOfMinute().getMaximumTextLength(null)); assertEquals(2, test.secondOfMinute().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetSecondOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().secondOfDay(), test.secondOfDay().getField()); assertEquals("secondOfDay", test.secondOfDay().getName()); assertEquals("Property[secondOfDay]", test.secondOfDay().toString()); assertEquals(48223, test.secondOfDay().get()); assertEquals("48223", test.secondOfDay().getAsText()); assertEquals("48223", test.secondOfDay().getAsText(Locale.FRENCH)); assertEquals("48223", test.secondOfDay().getAsShortText()); assertEquals("48223", test.secondOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().seconds(), test.secondOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.secondOfDay().getRangeDurationField()); assertEquals(5, test.secondOfDay().getMaximumTextLength(null)); assertEquals(5, test.secondOfDay().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetMillisOfSecond() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().millisOfSecond(), test.millisOfSecond().getField()); assertEquals("millisOfSecond", test.millisOfSecond().getName()); assertEquals("Property[millisOfSecond]", test.millisOfSecond().toString()); assertEquals(53, test.millisOfSecond().get()); assertEquals("53", test.millisOfSecond().getAsText()); assertEquals("53", test.millisOfSecond().getAsText(Locale.FRENCH)); assertEquals("53", test.millisOfSecond().getAsShortText()); assertEquals("53", test.millisOfSecond().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().millis(), test.millisOfSecond().getDurationField()); assertEquals(test.getChronology().seconds(), test.millisOfSecond().getRangeDurationField()); assertEquals(3, test.millisOfSecond().getMaximumTextLength(null)); assertEquals(3, test.millisOfSecond().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyGetMillisOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); assertSame(test.getChronology().millisOfDay(), test.millisOfDay().getField()); assertEquals("millisOfDay", test.millisOfDay().getName()); assertEquals("Property[millisOfDay]", test.millisOfDay().toString()); assertEquals(48223053, test.millisOfDay().get()); assertEquals("48223053", test.millisOfDay().getAsText()); assertEquals("48223053", test.millisOfDay().getAsText(Locale.FRENCH)); assertEquals("48223053", test.millisOfDay().getAsShortText()); assertEquals("48223053", test.millisOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().millis(), test.millisOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.millisOfDay().getRangeDurationField()); assertEquals(8, test.millisOfDay().getMaximumTextLength(null)); assertEquals(8, test.millisOfDay().getMaximumShortTextLength(null)); } //----------------------------------------------------------------------- public void testPropertyToIntervalYearOfEra() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.yearOfEra().toInterval(); assertEquals(new MutableDateTime(2004, 1, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2005, 1, 1, 0, 0, 0, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); } public void testPropertyToIntervalYearOfCentury() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.yearOfCentury().toInterval(); assertEquals(new MutableDateTime(2004, 1, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2005, 1, 1, 0, 0, 0, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); } public void testPropertyToIntervalYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.year().toInterval(); assertEquals(new MutableDateTime(2004, 1, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2005, 1, 1, 0, 0, 0, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); } public void testPropertyToIntervalMonthOfYear() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.monthOfYear().toInterval(); assertEquals(new MutableDateTime(2004, 6, 1, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2004, 7, 1, 0, 0, 0, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); } public void testPropertyToIntervalDayOfMonth() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.dayOfMonth().toInterval(); assertEquals(new MutableDateTime(2004, 6, 9, 0, 0, 0, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2004, 6, 10, 0, 0, 0, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); MutableDateTime febTest = new MutableDateTime(2004, 2, 29, 13, 23, 43, 53); Interval febTestInterval = febTest.dayOfMonth().toInterval(); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0), febTestInterval.getStart()); assertEquals(new MutableDateTime(2004, 3, 1, 0, 0, 0, 0), febTestInterval.getEnd()); assertEquals(new MutableDateTime(2004, 2, 29, 13, 23, 43, 53), febTest); } public void testPropertyToIntervalHourOfDay() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.hourOfDay().toInterval(); assertEquals(new MutableDateTime(2004, 6, 9, 13, 0, 0, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2004, 6, 9, 14, 0, 0, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); MutableDateTime midnightTest = new MutableDateTime(2004, 6, 9, 23, 23, 43, 53); Interval midnightTestInterval = midnightTest.hourOfDay().toInterval(); assertEquals(new MutableDateTime(2004, 6, 9, 23, 0, 0, 0), midnightTestInterval.getStart()); assertEquals(new MutableDateTime(2004, 6, 10, 0, 0, 0, 0), midnightTestInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 23, 23, 43, 53), midnightTest); } public void testPropertyToIntervalMinuteOfHour() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.minuteOfHour().toInterval(); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 0, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 24, 0, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); } public void testPropertyToIntervalSecondOfMinute() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.secondOfMinute().toInterval(); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 0), testInterval.getStart()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 44, 0), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); } public void testPropertyToIntervalMillisOfSecond() { MutableDateTime test = new MutableDateTime(2004, 6, 9, 13, 23, 43, 53); Interval testInterval = test.millisOfSecond().toInterval(); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), testInterval.getStart()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 54), testInterval.getEnd()); assertEquals(new MutableDateTime(2004, 6, 9, 13, 23, 43, 53), test); } } joda-time-2.3/src/test/java/org/joda/time/TestLocalDate_Properties.java0000644000175000017500000005552411564251364025501 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.StrictChronology; /** * This class is a Junit unit test for YearMonthDay. * * @author Stephen Colebourne */ public class TestLocalDate_Properties extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale systemDefaultLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestLocalDate_Properties.class); } public TestLocalDate_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); systemDefaultLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; Locale.setDefault(systemDefaultLocale); systemDefaultLocale = null; } //----------------------------------------------------------------------- public void testPropertyGetYear() { LocalDate test = new LocalDate(1972, 6, 9); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertSame(test, test.year().getLocalDate()); assertEquals(1972, test.year().get()); assertEquals("1972", test.year().getAsString()); assertEquals("1972", test.year().getAsText()); assertEquals("1972", test.year().getAsText(Locale.FRENCH)); assertEquals("1972", test.year().getAsShortText()); assertEquals("1972", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesYear() { LocalDate test = new LocalDate(1972, 6, 9); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292278993, test.year().getMaximumValue()); assertEquals(292278993, test.year().getMaximumValueOverall()); } public void testPropertyAddToCopyYear() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.year().addToCopy(9); check(test, 1972, 6, 9); check(copy, 1981, 6, 9); copy = test.year().addToCopy(0); check(copy, 1972, 6, 9); copy = test.year().addToCopy(292278993 - 1972); check(copy, 292278993, 6, 9); try { test.year().addToCopy(292278993 - 1972 + 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9); copy = test.year().addToCopy(-1972); check(copy, 0, 6, 9); copy = test.year().addToCopy(-1973); check(copy, -1, 6, 9); try { test.year().addToCopy(-292275054 - 1972 - 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9); } public void testPropertyAddWrapFieldToCopyYear() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.year().addWrapFieldToCopy(9); check(test, 1972, 6, 9); check(copy, 1981, 6, 9); copy = test.year().addWrapFieldToCopy(0); check(copy, 1972, 6, 9); copy = test.year().addWrapFieldToCopy(292278993 - 1972 + 1); check(copy, -292275054, 6, 9); copy = test.year().addWrapFieldToCopy(-292275054 - 1972 - 1); check(copy, 292278993, 6, 9); } public void testPropertySetCopyYear() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.year().setCopy(12); check(test, 1972, 6, 9); check(copy, 12, 6, 9); } public void testPropertySetCopyTextYear() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.year().setCopy("12"); check(test, 1972, 6, 9); check(copy, 12, 6, 9); } public void testPropertyCompareToYear() { LocalDate test1 = new LocalDate(TEST_TIME1); LocalDate test2 = new LocalDate(TEST_TIME2); assertEquals(true, test1.year().compareTo(test2) < 0); assertEquals(true, test2.year().compareTo(test1) > 0); assertEquals(true, test1.year().compareTo(test1) == 0); try { test1.year().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.year().compareTo(dt2) < 0); assertEquals(true, test2.year().compareTo(dt1) > 0); assertEquals(true, test1.year().compareTo(dt1) == 0); try { test1.year().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMonth() { LocalDate test = new LocalDate(1972, 6, 9); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getLocalDate()); assertEquals(6, test.monthOfYear().get()); assertEquals("6", test.monthOfYear().getAsString()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new LocalDate(1972, 7, 9); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); } public void testPropertyGetMaxMinValuesMonth() { LocalDate test = new LocalDate(1972, 6, 9); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyAddToCopyMonth() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.monthOfYear().addToCopy(6); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); copy = test.monthOfYear().addToCopy(7); check(copy, 1973, 1, 9); copy = test.monthOfYear().addToCopy(-5); check(copy, 1972, 1, 9); copy = test.monthOfYear().addToCopy(-6); check(copy, 1971, 12, 9); test = new LocalDate(1972, 1, 31); copy = test.monthOfYear().addToCopy(1); check(copy, 1972, 2, 29); copy = test.monthOfYear().addToCopy(2); check(copy, 1972, 3, 31); copy = test.monthOfYear().addToCopy(3); check(copy, 1972, 4, 30); test = new LocalDate(1971, 1, 31); copy = test.monthOfYear().addToCopy(1); check(copy, 1971, 2, 28); } public void testPropertyAddWrapFieldToCopyMonth() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.monthOfYear().addWrapFieldToCopy(4); check(test, 1972, 6, 9); check(copy, 1972, 10, 9); copy = test.monthOfYear().addWrapFieldToCopy(8); check(copy, 1972, 2, 9); copy = test.monthOfYear().addWrapFieldToCopy(-8); check(copy, 1972, 10, 9); test = new LocalDate(1972, 1, 31); copy = test.monthOfYear().addWrapFieldToCopy(1); check(copy, 1972, 2, 29); copy = test.monthOfYear().addWrapFieldToCopy(2); check(copy, 1972, 3, 31); copy = test.monthOfYear().addWrapFieldToCopy(3); check(copy, 1972, 4, 30); test = new LocalDate(1971, 1, 31); copy = test.monthOfYear().addWrapFieldToCopy(1); check(copy, 1971, 2, 28); } public void testPropertySetCopyMonth() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.monthOfYear().setCopy(12); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); test = new LocalDate(1972, 1, 31); copy = test.monthOfYear().setCopy(2); check(copy, 1972, 2, 29); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetCopyTextMonth() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.monthOfYear().setCopy("12"); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); copy = test.monthOfYear().setCopy("December"); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); copy = test.monthOfYear().setCopy("Dec"); check(test, 1972, 6, 9); check(copy, 1972, 12, 9); } public void testPropertyCompareToMonth() { LocalDate test1 = new LocalDate(TEST_TIME1); LocalDate test2 = new LocalDate(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetDay() { LocalDate test = new LocalDate(1972, 6, 9); assertSame(test.getChronology().dayOfMonth(), test.dayOfMonth().getField()); assertEquals("dayOfMonth", test.dayOfMonth().getName()); assertEquals("Property[dayOfMonth]", test.dayOfMonth().toString()); assertSame(test, test.dayOfMonth().getLocalDate()); assertEquals(9, test.dayOfMonth().get()); assertEquals("9", test.dayOfMonth().getAsString()); assertEquals("9", test.dayOfMonth().getAsText()); assertEquals("9", test.dayOfMonth().getAsText(Locale.FRENCH)); assertEquals("9", test.dayOfMonth().getAsShortText()); assertEquals("9", test.dayOfMonth().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().days(), test.dayOfMonth().getDurationField()); assertEquals(test.getChronology().months(), test.dayOfMonth().getRangeDurationField()); assertEquals(2, test.dayOfMonth().getMaximumTextLength(null)); assertEquals(2, test.dayOfMonth().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesDay() { LocalDate test = new LocalDate(1972, 6, 9); assertEquals(1, test.dayOfMonth().getMinimumValue()); assertEquals(1, test.dayOfMonth().getMinimumValueOverall()); assertEquals(30, test.dayOfMonth().getMaximumValue()); assertEquals(31, test.dayOfMonth().getMaximumValueOverall()); test = new LocalDate(1972, 7, 9); assertEquals(31, test.dayOfMonth().getMaximumValue()); test = new LocalDate(1972, 2, 9); assertEquals(29, test.dayOfMonth().getMaximumValue()); test = new LocalDate(1971, 2, 9); assertEquals(28, test.dayOfMonth().getMaximumValue()); } public void testPropertyAddToCopyDay() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.dayOfMonth().addToCopy(9); check(test, 1972, 6, 9); check(copy, 1972, 6, 18); copy = test.dayOfMonth().addToCopy(21); check(copy, 1972, 6, 30); copy = test.dayOfMonth().addToCopy(22); check(copy, 1972, 7, 1); copy = test.dayOfMonth().addToCopy(22 + 30); check(copy, 1972, 7, 31); copy = test.dayOfMonth().addToCopy(22 + 31); check(copy, 1972, 8, 1); copy = test.dayOfMonth().addToCopy(21 + 31 + 31 + 30 + 31 + 30 + 31); check(copy, 1972, 12, 31); copy = test.dayOfMonth().addToCopy(22 + 31 + 31 + 30 + 31 + 30 + 31); check(copy, 1973, 1, 1); copy = test.dayOfMonth().addToCopy(-8); check(copy, 1972, 6, 1); copy = test.dayOfMonth().addToCopy(-9); check(copy, 1972, 5, 31); copy = test.dayOfMonth().addToCopy(-8 - 31 - 30 - 31 - 29 - 31); check(copy, 1972, 1, 1); copy = test.dayOfMonth().addToCopy(-9 - 31 - 30 - 31 - 29 - 31); check(copy, 1971, 12, 31); } public void testPropertyAddWrapFieldToCopyDay() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.dayOfMonth().addWrapFieldToCopy(21); check(test, 1972, 6, 9); check(copy, 1972, 6, 30); copy = test.dayOfMonth().addWrapFieldToCopy(22); check(copy, 1972, 6, 1); copy = test.dayOfMonth().addWrapFieldToCopy(-12); check(copy, 1972, 6, 27); test = new LocalDate(1972, 7, 9); copy = test.dayOfMonth().addWrapFieldToCopy(21); check(copy, 1972, 7, 30); copy = test.dayOfMonth().addWrapFieldToCopy(22); check(copy, 1972, 7, 31); copy = test.dayOfMonth().addWrapFieldToCopy(23); check(copy, 1972, 7, 1); copy = test.dayOfMonth().addWrapFieldToCopy(-12); check(copy, 1972, 7, 28); } public void testPropertySetCopyDay() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.dayOfMonth().setCopy(12); check(test, 1972, 6, 9); check(copy, 1972, 6, 12); try { test.dayOfMonth().setCopy(31); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfMonth().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetCopyTextDay() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.dayOfMonth().setCopy("12"); check(test, 1972, 6, 9); check(copy, 1972, 6, 12); } public void testPropertyWithMaximumValueDayOfMonth() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.dayOfMonth().withMaximumValue(); check(test, 1972, 6, 9); check(copy, 1972, 6, 30); } public void testPropertyWithMinimumValueDayOfMonth() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.dayOfMonth().withMinimumValue(); check(test, 1972, 6, 9); check(copy, 1972, 6, 1); } public void testPropertyCompareToDay() { LocalDate test1 = new LocalDate(TEST_TIME1); LocalDate test2 = new LocalDate(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0); try { test1.dayOfMonth().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0); assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0); assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0); try { test1.dayOfMonth().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertyEquals() { LocalDate test1 = new LocalDate(2005, 11, 8); LocalDate test2 = new LocalDate(2005, 11, 9); LocalDate test3 = new LocalDate(2005, 11, 8, CopticChronology.getInstanceUTC()); assertEquals(false, test1.dayOfMonth().equals(test1.year())); assertEquals(false, test1.dayOfMonth().equals(test1.monthOfYear())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(test2.year())); assertEquals(false, test1.dayOfMonth().equals(test2.monthOfYear())); assertEquals(false, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(false, test1.monthOfYear().equals(test1.year())); assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test1.dayOfMonth())); assertEquals(false, test1.monthOfYear().equals(test2.year())); assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test2.dayOfMonth())); assertEquals(false, test1.dayOfMonth().equals(null)); assertEquals(false, test1.dayOfMonth().equals("any")); // chrono assertEquals(false, test1.dayOfMonth().equals(test3.dayOfMonth())); } public void testPropertyHashCode() { LocalDate test1 = new LocalDate(2005, 11, 8); LocalDate test2 = new LocalDate(2005, 11, 9); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(false, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); } public void testPropertyEqualsHashCodeLenient() { LocalDate test1 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); LocalDate test2 = new LocalDate(1970, 6, 9, LenientChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } public void testPropertyEqualsHashCodeStrict() { LocalDate test1 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); LocalDate test2 = new LocalDate(1970, 6, 9, StrictChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test1.dayOfMonth().equals(test1.dayOfMonth())); assertEquals(true, test2.dayOfMonth().equals(test2.dayOfMonth())); assertEquals(true, test1.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); assertEquals(true, test1.dayOfMonth().hashCode() == test1.dayOfMonth().hashCode()); assertEquals(true, test2.dayOfMonth().hashCode() == test2.dayOfMonth().hashCode()); } //----------------------------------------------------------------------- private void check(LocalDate test, int year, int month, int day) { assertEquals(year, test.getYear()); assertEquals(month, test.getMonthOfYear()); assertEquals(day, test.getDayOfMonth()); } } joda-time-2.3/src/test/java/org/joda/time/TestDateTimeZoneCutover.java0000644000175000017500000021132312072543746025327 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.tz.DateTimeZoneBuilder; /** * This class is a JUnit test for DateTimeZone. * * @author Stephen Colebourne */ public class TestDateTimeZoneCutover extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeZoneCutover.class); } public TestDateTimeZoneCutover(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- // The behaviour of getOffsetFromLocal is defined in its javadoc // However, this definition doesn't work for all DateTimeField operations /** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */ private static long CUTOVER_GAZA = 1175378400000L; private static int OFFSET_GAZA = 7200000; // +02:00 private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600); //----------------------------------------------------------------------- public void test_MockGazaIsCorrect() { DateTime pre = new DateTime(CUTOVER_GAZA - 1L, MOCK_GAZA); assertEquals("2007-03-31T23:59:59.999+02:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_GAZA + 1L, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Gaza() { doTest_getOffsetFromLocal_Gaza(-1, 23, 0, "2007-03-31T23:00:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(-1, 23, 30, "2007-03-31T23:30:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 2, 0, "2007-04-01T02:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 3, 0, "2007-04-01T03:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 4, 0, "2007-04-01T04:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 5, 0, "2007-04-01T05:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 6, 0, "2007-04-01T06:00:00.000+03:00"); } private void doTest_getOffsetFromLocal_Gaza(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_GAZA.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_GAZA); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_roundCeiling_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T20:00:00.000+02:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_setHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_DateTime_minusHour_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000+02:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000+02:00", minus9.toString()); } public void test_DateTime_plusHour_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T16:00:00.000+02:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000+02:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000+02:00", minus2.toString()); } public void test_DateTime_plusDay_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:00:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:30:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000+03:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Gaza() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-30T00:00:00.000+03:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_MutableDateTime_withZoneRetainFields_Gaza() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", dt.toString()); } public void test_LocalDate_new_Gaza() { LocalDate date1 = new LocalDate(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_GAZA - 1, MOCK_GAZA); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Gaza() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_GAZA); fail(); } catch (IllegalInstantException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Gaza() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_GAZA); fail(); } catch (IllegalInstantException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Gaza() { new DateTime(2007, 3, 31, 19, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 21, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 22, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_GAZA); } public void test_DateTime_parse_Gaza() { try { new DateTime("2007-04-01T00:00", MOCK_GAZA); fail(); } catch (IllegalInstantException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- /** Mock zone simulating America/Grand_Turk cutover at midnight 2007-04-01 */ private static long CUTOVER_TURK = 1175403600000L; private static int OFFSET_TURK = -18000000; // -05:00 private static final DateTimeZone MOCK_TURK = new MockZone(CUTOVER_TURK, OFFSET_TURK, 3600); //----------------------------------------------------------------------- public void test_MockTurkIsCorrect() { DateTime pre = new DateTime(CUTOVER_TURK - 1L, MOCK_TURK); assertEquals("2007-03-31T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_TURK + 1L, MOCK_TURK); assertEquals("2007-04-01T01:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_Turk() { doTest_getOffsetFromLocal_Turk(-1, 23, 0, "2007-03-31T23:00:00.000-05:00"); doTest_getOffsetFromLocal_Turk(-1, 23, 30, "2007-03-31T23:30:00.000-05:00"); doTest_getOffsetFromLocal_Turk(0, 0, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 0, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 2, 0, "2007-04-01T02:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 3, 0, "2007-04-01T03:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 4, 0, "2007-04-01T04:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 5, 0, "2007-04-01T05:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 6, 0, "2007-04-01T06:00:00.000-04:00"); } private void doTest_getOffsetFromLocal_Turk(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_TURK.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_TURK); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloorNotDST_Turk() { DateTime dt = new DateTime(2007, 4, 2, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-02T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_Turk() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T20:00:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_setHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_DateTime_minusHour_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000-04:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000-05:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000-05:00", minus9.toString()); } public void test_DateTime_plusHour_Turk() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T16:00:00.000-05:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000-05:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000-04:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000-04:00", plus9.toString()); } public void test_DateTime_minusDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000-05:00", minus2.toString()); } public void test_DateTime_plusDay_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:30:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000-04:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Turk() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-30T00:00:00.000-04:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Turk() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_MutableDateTime_setZoneRetainFields_Turk() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", dt.toString()); } public void test_LocalDate_new_Turk() { LocalDate date1 = new LocalDate(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_TURK - 1, MOCK_TURK); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Turk() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_TURK); fail(); } catch (IllegalInstantException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Turk() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_TURK); fail(); } catch (IllegalInstantException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Turk() { new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 4, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 5, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 6, 0, 0, 0, MOCK_TURK); } public void test_DateTime_parse_Turk() { try { new DateTime("2007-04-01T00:00", MOCK_TURK); fail(); } catch (IllegalInstantException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 03:00 on 2007-03-11 */ private static long CUTOVER_NEW_YORK_SPRING = 1173596400000L; // 2007-03-11T03:00:00.000-04:00 private static final DateTimeZone ZONE_NEW_YORK = DateTimeZone.forID("America/New_York"); // DateTime x = new DateTime(2007, 1, 1, 0, 0, 0, 0, ZONE_NEW_YORK); // System.out.println(ZONE_NEW_YORK.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_NEW_YORK.nextTransition(x.getMillis()), ZONE_NEW_YORK); // System.out.println(y); //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Spring() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_SPRING - 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T01:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_SPRING, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_SPRING + 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Spring() { doTest_getOffsetFromLocal(3, 11, 1, 0, "2007-03-11T01:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 1,30, "2007-03-11T01:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 4, 0, "2007-03-11T04:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 5, 0, "2007-03-11T05:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 6, 0, "2007-03-11T06:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 7, 0, "2007-03-11T07:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 8, 0, "2007-03-11T08:00:00.000-04:00", ZONE_NEW_YORK); } public void test_DateTime_setHourAcross_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-11T04:00:00.000-04:00", res.toString()); } public void test_DateTime_setHourForward_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T03:30:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T04:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T03:31:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 01:00 on 2007-11-04 */ private static long CUTOVER_NEW_YORK_AUTUMN = 1194156000000L; // 2007-11-04T01:00:00.000-05:00 //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_AUTUMN - 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:59:59.999-04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_AUTUMN, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.000-05:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_AUTUMN + 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.001-05:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Autumn() { doTest_getOffsetFromLocal(11, 4, 0, 0, "2007-11-04T00:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 0,30, "2007-11-04T00:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1, 0, "2007-11-04T01:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1,30, "2007-11-04T01:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2, 0, "2007-11-04T02:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2,30, "2007-11-04T02:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3, 0, "2007-11-04T03:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3,30, "2007-11-04T03:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 4, 0, "2007-11-04T04:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 5, 0, "2007-11-04T05:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 6, 0, "2007-11-04T06:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 7, 0, "2007-11-04T07:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 8, 0, "2007-11-04T08:00:00.000-05:00", ZONE_NEW_YORK); } public void test_DateTime_constructor_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); } public void test_DateTime_plusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 3, 18, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-03T18:00:00.000-04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-11-04T00:00:00.000-04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-11-04T01:00:00.000-04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-11-04T01:00:00.000-05:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-11-04T02:00:00.000-05:00", plus9.toString()); } public void test_DateTime_minusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T08:00:00.000-05:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-11-04T02:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-11-04T01:00:00.000-05:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-11-04T01:00:00.000-04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-11-04T00:00:00.000-04:00", minus9.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T02:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- /** Europe/Moscow cutover from 01:59 to 03:00 on 2007-03-25 */ private static long CUTOVER_MOSCOW_SPRING = 1174777200000L; // 2007-03-25T03:00:00.000+04:00 private static final DateTimeZone ZONE_MOSCOW = DateTimeZone.forID("Europe/Moscow"); //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Spring() { // DateTime x = new DateTime(2007, 7, 1, 0, 0, 0, 0, ZONE_MOSCOW); // System.out.println(ZONE_MOSCOW.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_MOSCOW.nextTransition(x.getMillis()), ZONE_MOSCOW); // System.out.println(y); DateTime pre = new DateTime(CUTOVER_MOSCOW_SPRING - 1L, ZONE_MOSCOW); assertEquals("2007-03-25T01:59:59.999+03:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_SPRING, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.000+04:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_SPRING + 1L, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.001+04:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Spring() { doTest_getOffsetFromLocal(3, 25, 1, 0, "2007-03-25T01:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 1,30, "2007-03-25T01:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 4, 0, "2007-03-25T04:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 5, 0, "2007-03-25T05:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 6, 0, "2007-03-25T06:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 7, 0, "2007-03-25T07:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 8, 0, "2007-03-25T08:00:00.000+04:00", ZONE_MOSCOW); } public void test_DateTime_setHourAcross_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-25T04:00:00.000+04:00", res.toString()); } public void test_DateTime_setHourForward_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 8, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T08:00:00.000+04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- /** America/New_York cutover from 02:59 to 02:00 on 2007-10-28 */ private static long CUTOVER_MOSCOW_AUTUMN = 1193526000000L; // 2007-10-28T02:00:00.000+03:00 //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_MOSCOW_AUTUMN - 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:59:59.999+04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_AUTUMN, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_AUTUMN + 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Autumn() { doTest_getOffsetFromLocal(10, 28, 0, 0, "2007-10-28T00:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 0,30, "2007-10-28T00:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1, 0, "2007-10-28T01:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1,30, "2007-10-28T01:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2, 0, "2007-10-28T02:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30, "2007-10-28T02:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30,59,999, "2007-10-28T02:30:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,998, "2007-10-28T02:59:59.998+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,999, "2007-10-28T02:59:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3, 0, "2007-10-28T03:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3,30, "2007-10-28T03:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 4, 0, "2007-10-28T04:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 5, 0, "2007-10-28T05:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 6, 0, "2007-10-28T06:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 7, 0, "2007-10-28T07:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 8, 0, "2007-10-28T08:00:00.000+03:00", ZONE_MOSCOW); } public void test_getOffsetFromLocal_Moscow_Autumn_overlap_mins() { for (int min = 0; min < 60; min++) { if (min < 10) { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:0" + min + ":00.000+04:00", ZONE_MOSCOW); } else { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:" + min + ":00.000+04:00", ZONE_MOSCOW); } } } public void test_DateTime_constructor_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 2, 30, ZONE_MOSCOW); assertEquals("2007-10-28T02:30:00.000+04:00", dt.toString()); } public void test_DateTime_plusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 27, 19, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-27T19:00:00.000+04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-10-28T01:00:00.000+04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-10-28T02:00:00.000+04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-10-28T02:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-10-28T03:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 9, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-28T09:00:00.000+03:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-10-28T03:00:00.000+03:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-10-28T02:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-10-28T02:00:00.000+04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-10-28T01:00:00.000+04:00", minus9.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/Guatemala cutover from 23:59 to 23:00 on 2006-09-30 */ private static long CUTOVER_GUATEMALA_AUTUMN = 1159678800000L; // 2006-09-30T23:00:00.000-06:00 private static final DateTimeZone ZONE_GUATEMALA = DateTimeZone.forID("America/Guatemala"); //----------------------------------------------------------------------- public void test_GuatemataIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_GUATEMALA_AUTUMN - 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GUATEMALA_AUTUMN, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.000-06:00", at.toString()); DateTime post = new DateTime(CUTOVER_GUATEMALA_AUTUMN + 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.001-06:00", post.toString()); } public void test_getOffsetFromLocal_Guatemata_Autumn() { doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0, 0, "2006-10-01T00:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0,30, "2006-10-01T00:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1, 0, "2006-10-01T01:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1,30, "2006-10-01T01:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2, 0, "2006-10-01T02:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2,30, "2006-10-01T02:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3, 0, "2006-10-01T03:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3,30, "2006-10-01T03:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4, 0, "2006-10-01T04:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4,30, "2006-10-01T04:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5, 0, "2006-10-01T05:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5,30, "2006-10-01T05:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6, 0, "2006-10-01T06:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6,30, "2006-10-01T06:30:00.000-06:00", ZONE_GUATEMALA); } public void test_DateTime_plusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 9, 30, 20, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-09-30T20:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusHours(1); assertEquals("2006-09-30T21:00:00.000-05:00", plus1.toString()); DateTime plus2 = dt.plusHours(2); assertEquals("2006-09-30T22:00:00.000-05:00", plus2.toString()); DateTime plus3 = dt.plusHours(3); assertEquals("2006-09-30T23:00:00.000-05:00", plus3.toString()); DateTime plus4 = dt.plusHours(4); assertEquals("2006-09-30T23:00:00.000-06:00", plus4.toString()); DateTime plus5 = dt.plusHours(5); assertEquals("2006-10-01T00:00:00.000-06:00", plus5.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2006-10-01T01:00:00.000-06:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2006-10-01T02:00:00.000-06:00", plus7.toString()); } public void test_DateTime_minusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 10, 1, 2, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-10-01T02:00:00.000-06:00", dt.toString()); DateTime minus1 = dt.minusHours(1); assertEquals("2006-10-01T01:00:00.000-06:00", minus1.toString()); DateTime minus2 = dt.minusHours(2); assertEquals("2006-10-01T00:00:00.000-06:00", minus2.toString()); DateTime minus3 = dt.minusHours(3); assertEquals("2006-09-30T23:00:00.000-06:00", minus3.toString()); DateTime minus4 = dt.minusHours(4); assertEquals("2006-09-30T23:00:00.000-05:00", minus4.toString()); DateTime minus5 = dt.minusHours(5); assertEquals("2006-09-30T22:00:00.000-05:00", minus5.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2006-09-30T21:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2006-09-30T20:00:00.000-05:00", minus7.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_DateTime_JustAfterLastEverOverlap() { // based on America/Argentina/Catamarca in file 2009s DateTimeZone zone = new DateTimeZoneBuilder() .setStandardOffset(-3 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("SUMMER", 1 * DateTimeConstants.MILLIS_PER_HOUR, 2000, 2008, 'w', 4, 10, 0, true, 23 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("WINTER", 0, 2000, 2008, 'w', 8, 10, 0, true, 0 * DateTimeConstants.MILLIS_PER_HOUR) .toDateTimeZone("Zone", false); LocalDate date = new LocalDate(2008, 8, 10); assertEquals("2008-08-10", date.toString()); DateTime dt = date.toDateTimeAtStartOfDay(zone); assertEquals("2008-08-10T00:00:00.000-03:00", dt.toString()); } // public void test_toDateMidnight_SaoPaolo() { // // RFE: 1684259 // DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); // LocalDate baseDate = new LocalDate(2006, 11, 5); // DateMidnight dm = baseDate.toDateMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dm.toString()); // DateTime dt = baseDate.toDateTimeAtMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dt.toString()); // } //----------------------------------------------------------------------- private static final DateTimeZone ZONE_PARIS = DateTimeZone.forID("Europe/Paris"); public void testWithMinuteOfHourInDstChange_mockZone() { DateTime cutover = new DateTime(2010, 10, 31, 1, 15, DateTimeZone.forOffsetHoursMinutes(0, 30)); assertEquals("2010-10-31T01:15:00.000+00:30", cutover.toString()); DateTimeZone halfHourZone = new MockZone(cutover.getMillis(), 3600000, -1800); DateTime pre = new DateTime(2010, 10, 31, 1, 0, halfHourZone); assertEquals("2010-10-31T01:00:00.000+01:00", pre.toString()); DateTime post = new DateTime(2010, 10, 31, 1, 59, halfHourZone); assertEquals("2010-10-31T01:59:00.000+00:30", post.toString()); DateTime testPre1 = pre.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+01:00", testPre1.toString()); // retain offset DateTime testPre2 = pre.withMinuteOfHour(50); assertEquals("2010-10-31T01:50:00.000+00:30", testPre2.toString()); DateTime testPost1 = post.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+00:30", testPost1.toString()); // retain offset DateTime testPost2 = post.withMinuteOfHour(10); assertEquals("2010-10-31T01:10:00.000+01:00", testPost2.toString()); } public void testWithHourOfDayInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withHourOfDay(2); assertEquals("2010-10-31T02:30:10.123+02:00", test.toString()); } public void testWithMinuteOfHourInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMinuteOfHour(0); assertEquals("2010-10-31T02:00:10.123+02:00", test.toString()); } public void testWithSecondOfMinuteInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withSecondOfMinute(0); assertEquals("2010-10-31T02:30:00.123+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_summer() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_winter() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+01:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+01:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+01:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_summer() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-04:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-04:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-04:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_winter() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-05:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-05:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-05:00", test.toString()); } public void testPlusMinutesInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMinutes(1); assertEquals("2010-10-31T02:31:10.123+02:00", test.toString()); } public void testPlusSecondsInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusSeconds(1); assertEquals("2010-10-31T02:30:11.123+02:00", test.toString()); } public void testPlusMillisInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMillis(1); assertEquals("2010-10-31T02:30:10.124+02:00", test.toString()); } public void testBug2182444_usCentral() { Chronology chronUSCentral = GregorianChronology.getInstance(DateTimeZone.forID("US/Central")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime usCentralStandardInUTC = new DateTime(2008, 11, 2, 7, 0, 0, 0, chronUTC); DateTime usCentralDaylightInUTC = new DateTime(2008, 11, 2, 6, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronUSCentral.getZone().isStandardOffset(usCentralStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronUSCentral.getZone().isStandardOffset(usCentralDaylightInUTC.getMillis())); DateTime usCentralStandardInUSCentral = usCentralStandardInUTC.toDateTime(chronUSCentral); DateTime usCentralDaylightInUSCentral = usCentralDaylightInUTC.toDateTime(chronUSCentral); assertEquals(1, usCentralStandardInUSCentral.getHourOfDay()); assertEquals(usCentralStandardInUSCentral.getHourOfDay(), usCentralDaylightInUSCentral.getHourOfDay()); assertTrue(usCentralStandardInUSCentral.getMillis() != usCentralDaylightInUSCentral.getMillis()); assertEquals(usCentralStandardInUSCentral, usCentralStandardInUSCentral.withHourOfDay(1)); assertEquals(usCentralStandardInUSCentral.getMillis() + 3, usCentralStandardInUSCentral.withMillisOfSecond(3).getMillis()); assertEquals(usCentralDaylightInUSCentral, usCentralDaylightInUSCentral.withHourOfDay(1)); assertEquals(usCentralDaylightInUSCentral.getMillis() + 3, usCentralDaylightInUSCentral.withMillisOfSecond(3).getMillis()); } public void testBug2182444_ausNSW() { Chronology chronAusNSW = GregorianChronology.getInstance(DateTimeZone.forID("Australia/NSW")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime australiaNSWStandardInUTC = new DateTime(2008, 4, 5, 16, 0, 0, 0, chronUTC); DateTime australiaNSWDaylightInUTC = new DateTime(2008, 4, 5, 15, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronAusNSW.getZone().isStandardOffset(australiaNSWStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronAusNSW.getZone().isStandardOffset(australiaNSWDaylightInUTC.getMillis())); DateTime australiaNSWStandardInAustraliaNSW = australiaNSWStandardInUTC.toDateTime(chronAusNSW); DateTime australiaNSWDaylightInAusraliaNSW = australiaNSWDaylightInUTC.toDateTime(chronAusNSW); assertEquals(2, australiaNSWStandardInAustraliaNSW.getHourOfDay()); assertEquals(australiaNSWStandardInAustraliaNSW.getHourOfDay(), australiaNSWDaylightInAusraliaNSW.getHourOfDay()); assertTrue(australiaNSWStandardInAustraliaNSW.getMillis() != australiaNSWDaylightInAusraliaNSW.getMillis()); assertEquals(australiaNSWStandardInAustraliaNSW, australiaNSWStandardInAustraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWStandardInAustraliaNSW.getMillis() + 3, australiaNSWStandardInAustraliaNSW.withMillisOfSecond(3).getMillis()); assertEquals(australiaNSWDaylightInAusraliaNSW, australiaNSWDaylightInAusraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWDaylightInAusraliaNSW.getMillis() + 3, australiaNSWDaylightInAusraliaNSW.withMillisOfSecond(3).getMillis()); } public void testPeriod() { DateTime a = new DateTime("2010-10-31T02:00:00.000+02:00", ZONE_PARIS); DateTime b = new DateTime("2010-10-31T02:01:00.000+02:00", ZONE_PARIS); Period period = new Period(a, b, PeriodType.standard()); assertEquals("PT1M", period.toString()); } public void testForum4013394_retainOffsetWhenRetainFields_sameOffsetsDifferentZones() { final DateTimeZone fromDTZ = DateTimeZone.forID("Europe/London"); final DateTimeZone toDTZ = DateTimeZone.forID("Europe/Lisbon"); DateTime baseBefore = new DateTime(2007, 10, 28, 1, 15, fromDTZ).minusHours(1); DateTime baseAfter = new DateTime(2007, 10, 28, 1, 15, fromDTZ); DateTime testBefore = baseBefore.withZoneRetainFields(toDTZ); DateTime testAfter = baseAfter.withZoneRetainFields(toDTZ); // toString ignores time-zone but includes offset assertEquals(baseBefore.toString(), testBefore.toString()); assertEquals(baseAfter.toString(), testAfter.toString()); } //------------------------------------------------------------------------- public void testBug3192457_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2007, 10, 28, 3, 15, zone); DateTime baseBefore = base.minusHours(2); DateTime baseAfter = base.minusHours(1); assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); } public void testBug3476684_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); DateTime base = new DateTime(2012, 2, 25, 22, 15, zone); DateTime baseBefore = base.plusHours(1); // 23:15 (first) DateTime baseAfter = base.plusHours(2); // 23:15 (second) assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); } public void testBug3476684_adjustOffset_springGap() { final DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); DateTime base = new DateTime(2011, 10, 15, 22, 15, zone); DateTime baseBefore = base.plusHours(1); // 23:15 DateTime baseAfter = base.plusHours(2); // 01:15 assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseBefore, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseAfter, baseAfter.withEarlierOffsetAtOverlap()); } // ensure Summer time picked //----------------------------------------------------------------------- public void testDateTimeCreation_athens() { DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime base = new DateTime(2011, 10, 30, 3, 15, zone); assertEquals("2011-10-30T03:15:00.000+03:00", base.toString()); assertEquals("2011-10-30T03:15:00.000+02:00", base.plusHours(1).toString()); } public void testDateTimeCreation_paris() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2011, 10, 30, 2, 15, zone); assertEquals("2011-10-30T02:15:00.000+02:00", base.toString()); assertEquals("2011-10-30T02:15:00.000+01:00", base.plusHours(1).toString()); } public void testDateTimeCreation_london() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); DateTime base = new DateTime(2011, 10, 30, 1, 15, zone); assertEquals("2011-10-30T01:15:00.000+01:00", base.toString()); assertEquals("2011-10-30T01:15:00.000Z", base.plusHours(1).toString()); } public void testDateTimeCreation_newYork() { DateTimeZone zone = DateTimeZone.forID("America/New_York"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-04:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-05:00", base.plusHours(1).toString()); } public void testDateTimeCreation_losAngeles() { DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-07:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-08:00", base.plusHours(1).toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, sec, milli, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(year, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { DateTime dt = new DateTime(year, month, day, hour, min, sec, milli, DateTimeZone.UTC); int offset = zone.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, zone); assertEquals(res.toString(), expected, res.toString()); } } joda-time-2.3/src/test/java/org/joda/time/TestMinutes.java0000644000175000017500000003472712200501234023041 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for Minutes. * * @author Stephen Colebourne */ public class TestMinutes extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestMinutes.class); } public TestMinutes(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void testConstants() { assertEquals(0, Minutes.ZERO.getMinutes()); assertEquals(1, Minutes.ONE.getMinutes()); assertEquals(2, Minutes.TWO.getMinutes()); assertEquals(3, Minutes.THREE.getMinutes()); assertEquals(Integer.MAX_VALUE, Minutes.MAX_VALUE.getMinutes()); assertEquals(Integer.MIN_VALUE, Minutes.MIN_VALUE.getMinutes()); } //----------------------------------------------------------------------- public void testFactory_minutes_int() { assertSame(Minutes.ZERO, Minutes.minutes(0)); assertSame(Minutes.ONE, Minutes.minutes(1)); assertSame(Minutes.TWO, Minutes.minutes(2)); assertSame(Minutes.THREE, Minutes.minutes(3)); assertSame(Minutes.MAX_VALUE, Minutes.minutes(Integer.MAX_VALUE)); assertSame(Minutes.MIN_VALUE, Minutes.minutes(Integer.MIN_VALUE)); assertEquals(-1, Minutes.minutes(-1).getMinutes()); assertEquals(4, Minutes.minutes(4).getMinutes()); } //----------------------------------------------------------------------- public void testFactory_minutesBetween_RInstant() { DateTime start = new DateTime(2006, 6, 9, 12, 3, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 9, 12, 6, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 9, 12, 9, 0, 0, PARIS); assertEquals(3, Minutes.minutesBetween(start, end1).getMinutes()); assertEquals(0, Minutes.minutesBetween(start, start).getMinutes()); assertEquals(0, Minutes.minutesBetween(end1, end1).getMinutes()); assertEquals(-3, Minutes.minutesBetween(end1, start).getMinutes()); assertEquals(6, Minutes.minutesBetween(start, end2).getMinutes()); } public void testFactory_minutesBetween_RPartial() { LocalTime start = new LocalTime(12, 3); LocalTime end1 = new LocalTime(12, 6); @SuppressWarnings("deprecation") TimeOfDay end2 = new TimeOfDay(12, 9); assertEquals(3, Minutes.minutesBetween(start, end1).getMinutes()); assertEquals(0, Minutes.minutesBetween(start, start).getMinutes()); assertEquals(0, Minutes.minutesBetween(end1, end1).getMinutes()); assertEquals(-3, Minutes.minutesBetween(end1, start).getMinutes()); assertEquals(6, Minutes.minutesBetween(start, end2).getMinutes()); } public void testFactory_minutesIn_RInterval() { DateTime start = new DateTime(2006, 6, 9, 12, 3, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 9, 12, 6, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 9, 12, 9, 0, 0, PARIS); assertEquals(0, Minutes.minutesIn((ReadableInterval) null).getMinutes()); assertEquals(3, Minutes.minutesIn(new Interval(start, end1)).getMinutes()); assertEquals(0, Minutes.minutesIn(new Interval(start, start)).getMinutes()); assertEquals(0, Minutes.minutesIn(new Interval(end1, end1)).getMinutes()); assertEquals(6, Minutes.minutesIn(new Interval(start, end2)).getMinutes()); } public void testFactory_standardMinutesIn_RPeriod() { assertEquals(0, Minutes.standardMinutesIn((ReadablePeriod) null).getMinutes()); assertEquals(0, Minutes.standardMinutesIn(Period.ZERO).getMinutes()); assertEquals(1, Minutes.standardMinutesIn(new Period(0, 0, 0, 0, 0, 1, 0, 0)).getMinutes()); assertEquals(123, Minutes.standardMinutesIn(Period.minutes(123)).getMinutes()); assertEquals(-987, Minutes.standardMinutesIn(Period.minutes(-987)).getMinutes()); assertEquals(1, Minutes.standardMinutesIn(Period.seconds(119)).getMinutes()); assertEquals(2, Minutes.standardMinutesIn(Period.seconds(120)).getMinutes()); assertEquals(2, Minutes.standardMinutesIn(Period.seconds(121)).getMinutes()); assertEquals(120, Minutes.standardMinutesIn(Period.hours(2)).getMinutes()); try { Minutes.standardMinutesIn(Period.months(1)); fail(); } catch (IllegalArgumentException ex) { // expeceted } } public void testFactory_parseMinutes_String() { assertEquals(0, Minutes.parseMinutes((String) null).getMinutes()); assertEquals(0, Minutes.parseMinutes("PT0M").getMinutes()); assertEquals(1, Minutes.parseMinutes("PT1M").getMinutes()); assertEquals(-3, Minutes.parseMinutes("PT-3M").getMinutes()); assertEquals(2, Minutes.parseMinutes("P0Y0M0DT2M").getMinutes()); assertEquals(2, Minutes.parseMinutes("PT0H2M").getMinutes()); try { Minutes.parseMinutes("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Minutes.parseMinutes("P1DT1M"); fail(); } catch (IllegalArgumentException ex) { // expeceted } } //----------------------------------------------------------------------- public void testGetMethods() { Minutes test = Minutes.minutes(20); assertEquals(20, test.getMinutes()); } public void testGetFieldType() { Minutes test = Minutes.minutes(20); assertEquals(DurationFieldType.minutes(), test.getFieldType()); } public void testGetPeriodType() { Minutes test = Minutes.minutes(20); assertEquals(PeriodType.minutes(), test.getPeriodType()); } //----------------------------------------------------------------------- public void testIsGreaterThan() { assertEquals(true, Minutes.THREE.isGreaterThan(Minutes.TWO)); assertEquals(false, Minutes.THREE.isGreaterThan(Minutes.THREE)); assertEquals(false, Minutes.TWO.isGreaterThan(Minutes.THREE)); assertEquals(true, Minutes.ONE.isGreaterThan(null)); assertEquals(false, Minutes.minutes(-1).isGreaterThan(null)); } public void testIsLessThan() { assertEquals(false, Minutes.THREE.isLessThan(Minutes.TWO)); assertEquals(false, Minutes.THREE.isLessThan(Minutes.THREE)); assertEquals(true, Minutes.TWO.isLessThan(Minutes.THREE)); assertEquals(false, Minutes.ONE.isLessThan(null)); assertEquals(true, Minutes.minutes(-1).isLessThan(null)); } //----------------------------------------------------------------------- public void testToString() { Minutes test = Minutes.minutes(20); assertEquals("PT20M", test.toString()); test = Minutes.minutes(-20); assertEquals("PT-20M", test.toString()); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Minutes test = Minutes.THREE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Minutes result = (Minutes) ois.readObject(); ois.close(); assertSame(test, result); } //----------------------------------------------------------------------- public void testToStandardWeeks() { Minutes test = Minutes.minutes(60 * 24 * 7 * 2); Weeks expected = Weeks.weeks(2); assertEquals(expected, test.toStandardWeeks()); } public void testToStandardDays() { Minutes test = Minutes.minutes(60 * 24 * 2); Days expected = Days.days(2); assertEquals(expected, test.toStandardDays()); } public void testToStandardHours() { Minutes test = Minutes.minutes(3 * 60); Hours expected = Hours.hours(3); assertEquals(expected, test.toStandardHours()); } public void testToStandardSeconds() { Minutes test = Minutes.minutes(3); Seconds expected = Seconds.seconds(3 * 60); assertEquals(expected, test.toStandardSeconds()); try { Minutes.MAX_VALUE.toStandardSeconds(); fail(); } catch (ArithmeticException ex) { // expected } } public void testToStandardDuration() { Minutes test = Minutes.minutes(20); Duration expected = new Duration(20L * DateTimeConstants.MILLIS_PER_MINUTE); assertEquals(expected, test.toStandardDuration()); expected = new Duration(((long) Integer.MAX_VALUE) * DateTimeConstants.MILLIS_PER_MINUTE); assertEquals(expected, Minutes.MAX_VALUE.toStandardDuration()); } //----------------------------------------------------------------------- public void testPlus_int() { Minutes test2 = Minutes.minutes(2); Minutes result = test2.plus(3); assertEquals(2, test2.getMinutes()); assertEquals(5, result.getMinutes()); assertEquals(1, Minutes.ONE.plus(0).getMinutes()); try { Minutes.MAX_VALUE.plus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testPlus_Minutes() { Minutes test2 = Minutes.minutes(2); Minutes test3 = Minutes.minutes(3); Minutes result = test2.plus(test3); assertEquals(2, test2.getMinutes()); assertEquals(3, test3.getMinutes()); assertEquals(5, result.getMinutes()); assertEquals(1, Minutes.ONE.plus(Minutes.ZERO).getMinutes()); assertEquals(1, Minutes.ONE.plus((Minutes) null).getMinutes()); try { Minutes.MAX_VALUE.plus(Minutes.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_int() { Minutes test2 = Minutes.minutes(2); Minutes result = test2.minus(3); assertEquals(2, test2.getMinutes()); assertEquals(-1, result.getMinutes()); assertEquals(1, Minutes.ONE.minus(0).getMinutes()); try { Minutes.MIN_VALUE.minus(1); fail(); } catch (ArithmeticException ex) { // expected } } public void testMinus_Minutes() { Minutes test2 = Minutes.minutes(2); Minutes test3 = Minutes.minutes(3); Minutes result = test2.minus(test3); assertEquals(2, test2.getMinutes()); assertEquals(3, test3.getMinutes()); assertEquals(-1, result.getMinutes()); assertEquals(1, Minutes.ONE.minus(Minutes.ZERO).getMinutes()); assertEquals(1, Minutes.ONE.minus((Minutes) null).getMinutes()); try { Minutes.MIN_VALUE.minus(Minutes.ONE); fail(); } catch (ArithmeticException ex) { // expected } } public void testMultipliedBy_int() { Minutes test = Minutes.minutes(2); assertEquals(6, test.multipliedBy(3).getMinutes()); assertEquals(2, test.getMinutes()); assertEquals(-6, test.multipliedBy(-3).getMinutes()); assertSame(test, test.multipliedBy(1)); Minutes halfMax = Minutes.minutes(Integer.MAX_VALUE / 2 + 1); try { halfMax.multipliedBy(2); fail(); } catch (ArithmeticException ex) { // expected } } public void testDividedBy_int() { Minutes test = Minutes.minutes(12); assertEquals(6, test.dividedBy(2).getMinutes()); assertEquals(12, test.getMinutes()); assertEquals(4, test.dividedBy(3).getMinutes()); assertEquals(3, test.dividedBy(4).getMinutes()); assertEquals(2, test.dividedBy(5).getMinutes()); assertEquals(2, test.dividedBy(6).getMinutes()); assertSame(test, test.dividedBy(1)); try { Minutes.ONE.dividedBy(0); fail(); } catch (ArithmeticException ex) { // expected } } public void testNegated() { Minutes test = Minutes.minutes(12); assertEquals(-12, test.negated().getMinutes()); assertEquals(12, test.getMinutes()); try { Minutes.MIN_VALUE.negated(); fail(); } catch (ArithmeticException ex) { // expected } } //----------------------------------------------------------------------- public void testAddToLocalDate() { Minutes test = Minutes.minutes(26); LocalDateTime date = new LocalDateTime(2006, 6, 1, 0, 0, 0, 0); LocalDateTime expected = new LocalDateTime(2006, 6, 1, 0, 26, 0, 0); assertEquals(expected, date.plus(test)); } } joda-time-2.3/src/test/java/org/joda/time/TestTimeOfDay_Properties.java0000644000175000017500000007232612200501234025447 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; /** * This class is a Junit unit test for TimeOfDay. * * @author Stephen Colebourne */ @SuppressWarnings("deprecation") public class TestTimeOfDay_Properties extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private long TEST_TIME_NOW = 10L * DateTimeConstants.MILLIS_PER_HOUR + 20L * DateTimeConstants.MILLIS_PER_MINUTE + 30L * DateTimeConstants.MILLIS_PER_SECOND + 40L; private long TEST_TIME1 = 1L * DateTimeConstants.MILLIS_PER_HOUR + 2L * DateTimeConstants.MILLIS_PER_MINUTE + 3L * DateTimeConstants.MILLIS_PER_SECOND + 4L; private long TEST_TIME2 = 1L * DateTimeConstants.MILLIS_PER_DAY + 5L * DateTimeConstants.MILLIS_PER_HOUR + 6L * DateTimeConstants.MILLIS_PER_MINUTE + 7L * DateTimeConstants.MILLIS_PER_SECOND + 8L; private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestTimeOfDay_Properties.class); } public TestTimeOfDay_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(LONDON); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; } //----------------------------------------------------------------------- public void testPropertyGetHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertSame(test.getChronology().hourOfDay(), test.hourOfDay().getField()); assertEquals("hourOfDay", test.hourOfDay().getName()); assertEquals("Property[hourOfDay]", test.hourOfDay().toString()); assertSame(test, test.hourOfDay().getReadablePartial()); assertSame(test, test.hourOfDay().getTimeOfDay()); assertEquals(10, test.hourOfDay().get()); assertEquals("10", test.hourOfDay().getAsString()); assertEquals("10", test.hourOfDay().getAsText()); assertEquals("10", test.hourOfDay().getAsText(Locale.FRENCH)); assertEquals("10", test.hourOfDay().getAsShortText()); assertEquals("10", test.hourOfDay().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().hours(), test.hourOfDay().getDurationField()); assertEquals(test.getChronology().days(), test.hourOfDay().getRangeDurationField()); assertEquals(2, test.hourOfDay().getMaximumTextLength(null)); assertEquals(2, test.hourOfDay().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals(0, test.hourOfDay().getMinimumValue()); assertEquals(0, test.hourOfDay().getMinimumValueOverall()); assertEquals(23, test.hourOfDay().getMaximumValue()); assertEquals(23, test.hourOfDay().getMaximumValueOverall()); } public void testPropertyAddHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().addToCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addToCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addToCopy(13); check(copy, 23, 20, 30, 40); copy = test.hourOfDay().addToCopy(14); check(copy, 0, 20, 30, 40); copy = test.hourOfDay().addToCopy(-10); check(copy, 0, 20, 30, 40); copy = test.hourOfDay().addToCopy(-11); check(copy, 23, 20, 30, 40); } public void testPropertyAddNoWrapHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(13); check(copy, 23, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(14); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(-10); check(copy, 0, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(-11); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyAddWrapFieldHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(18); check(copy, 4, 20, 30, 40); copy = test.hourOfDay().addWrapFieldToCopy(-15); check(copy, 19, 20, 30, 40); } public void testPropertySetHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 12, 20, 30, 40); try { test.hourOfDay().setCopy(24); fail(); } catch (IllegalArgumentException ex) {} try { test.hourOfDay().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 12, 20, 30, 40); } public void testPropertyWithMaximumValueHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().withMaximumValue(); check(test, 10, 20, 30, 40); check(copy, 23, 20, 30, 40); } public void testPropertyWithMinimumValueHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().withMinimumValue(); check(test, 10, 20, 30, 40); check(copy, 0, 20, 30, 40); } public void testPropertyCompareToHour() { TimeOfDay test1 = new TimeOfDay(TEST_TIME1); TimeOfDay test2 = new TimeOfDay(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(test2) < 0); assertEquals(true, test2.hourOfDay().compareTo(test1) > 0); assertEquals(true, test1.hourOfDay().compareTo(test1) == 0); try { test1.hourOfDay().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(dt2) < 0); assertEquals(true, test2.hourOfDay().compareTo(dt1) > 0); assertEquals(true, test1.hourOfDay().compareTo(dt1) == 0); try { test1.hourOfDay().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertSame(test.getChronology().minuteOfHour(), test.minuteOfHour().getField()); assertEquals("minuteOfHour", test.minuteOfHour().getName()); assertEquals("Property[minuteOfHour]", test.minuteOfHour().toString()); assertSame(test, test.minuteOfHour().getReadablePartial()); assertSame(test, test.minuteOfHour().getTimeOfDay()); assertEquals(20, test.minuteOfHour().get()); assertEquals("20", test.minuteOfHour().getAsString()); assertEquals("20", test.minuteOfHour().getAsText()); assertEquals("20", test.minuteOfHour().getAsText(Locale.FRENCH)); assertEquals("20", test.minuteOfHour().getAsShortText()); assertEquals("20", test.minuteOfHour().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().minutes(), test.minuteOfHour().getDurationField()); assertEquals(test.getChronology().hours(), test.minuteOfHour().getRangeDurationField()); assertEquals(2, test.minuteOfHour().getMaximumTextLength(null)); assertEquals(2, test.minuteOfHour().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals(0, test.minuteOfHour().getMinimumValue()); assertEquals(0, test.minuteOfHour().getMinimumValueOverall()); assertEquals(59, test.minuteOfHour().getMaximumValue()); assertEquals(59, test.minuteOfHour().getMaximumValueOverall()); } public void testPropertyAddMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.minuteOfHour().addToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.minuteOfHour().addToCopy(39); check(copy, 10, 59, 30, 40); copy = test.minuteOfHour().addToCopy(40); check(copy, 11, 0, 30, 40); copy = test.minuteOfHour().addToCopy(1 * 60 + 45); check(copy, 12, 5, 30, 40); copy = test.minuteOfHour().addToCopy(13 * 60 + 39); check(copy, 23, 59, 30, 40); copy = test.minuteOfHour().addToCopy(13 * 60 + 40); check(copy, 0, 0, 30, 40); copy = test.minuteOfHour().addToCopy(-9); check(copy, 10, 11, 30, 40); copy = test.minuteOfHour().addToCopy(-19); check(copy, 10, 1, 30, 40); copy = test.minuteOfHour().addToCopy(-20); check(copy, 10, 0, 30, 40); copy = test.minuteOfHour().addToCopy(-21); check(copy, 9, 59, 30, 40); copy = test.minuteOfHour().addToCopy(-(10 * 60 + 20)); check(copy, 0, 0, 30, 40); copy = test.minuteOfHour().addToCopy(-(10 * 60 + 21)); check(copy, 23, 59, 30, 40); } public void testPropertyAddNoWrapMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.minuteOfHour().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(39); check(copy, 10, 59, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(40); check(copy, 11, 0, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(1 * 60 + 45); check(copy, 12, 5, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(13 * 60 + 39); check(copy, 23, 59, 30, 40); try { test.minuteOfHour().addNoWrapToCopy(13 * 60 + 40); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-9); check(copy, 10, 11, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-19); check(copy, 10, 1, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-20); check(copy, 10, 0, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-21); check(copy, 9, 59, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 20)); check(copy, 0, 0, 30, 40); try { test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 21)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyAddWrapFieldMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.minuteOfHour().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.minuteOfHour().addWrapFieldToCopy(49); check(copy, 10, 9, 30, 40); copy = test.minuteOfHour().addWrapFieldToCopy(-47); check(copy, 10, 33, 30, 40); } public void testPropertySetMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.minuteOfHour().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 12, 30, 40); try { test.minuteOfHour().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.minuteOfHour().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.minuteOfHour().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 10, 12, 30, 40); } public void testPropertyCompareToMinute() { TimeOfDay test1 = new TimeOfDay(TEST_TIME1); TimeOfDay test2 = new TimeOfDay(TEST_TIME2); assertEquals(true, test1.minuteOfHour().compareTo(test2) < 0); assertEquals(true, test2.minuteOfHour().compareTo(test1) > 0); assertEquals(true, test1.minuteOfHour().compareTo(test1) == 0); try { test1.minuteOfHour().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.minuteOfHour().compareTo(dt2) < 0); assertEquals(true, test2.minuteOfHour().compareTo(dt1) > 0); assertEquals(true, test1.minuteOfHour().compareTo(dt1) == 0); try { test1.minuteOfHour().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertSame(test.getChronology().secondOfMinute(), test.secondOfMinute().getField()); assertEquals("secondOfMinute", test.secondOfMinute().getName()); assertEquals("Property[secondOfMinute]", test.secondOfMinute().toString()); assertSame(test, test.secondOfMinute().getReadablePartial()); assertSame(test, test.secondOfMinute().getTimeOfDay()); assertEquals(30, test.secondOfMinute().get()); assertEquals("30", test.secondOfMinute().getAsString()); assertEquals("30", test.secondOfMinute().getAsText()); assertEquals("30", test.secondOfMinute().getAsText(Locale.FRENCH)); assertEquals("30", test.secondOfMinute().getAsShortText()); assertEquals("30", test.secondOfMinute().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().seconds(), test.secondOfMinute().getDurationField()); assertEquals(test.getChronology().minutes(), test.secondOfMinute().getRangeDurationField()); assertEquals(2, test.secondOfMinute().getMaximumTextLength(null)); assertEquals(2, test.secondOfMinute().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals(0, test.secondOfMinute().getMinimumValue()); assertEquals(0, test.secondOfMinute().getMinimumValueOverall()); assertEquals(59, test.secondOfMinute().getMaximumValue()); assertEquals(59, test.secondOfMinute().getMaximumValueOverall()); } public void testPropertyAddSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.secondOfMinute().addToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 39, 40); copy = test.secondOfMinute().addToCopy(29); check(copy, 10, 20, 59, 40); copy = test.secondOfMinute().addToCopy(30); check(copy, 10, 21, 0, 40); copy = test.secondOfMinute().addToCopy(39 * 60 + 29); check(copy, 10, 59, 59, 40); copy = test.secondOfMinute().addToCopy(39 * 60 + 30); check(copy, 11, 0, 0, 40); copy = test.secondOfMinute().addToCopy(13 * 60 * 60 + 39 * 60 + 30); check(copy, 0, 0, 0, 40); copy = test.secondOfMinute().addToCopy(-9); check(copy, 10, 20, 21, 40); copy = test.secondOfMinute().addToCopy(-30); check(copy, 10, 20, 0, 40); copy = test.secondOfMinute().addToCopy(-31); check(copy, 10, 19, 59, 40); copy = test.secondOfMinute().addToCopy(-(10 * 60 * 60 + 20 * 60 + 30)); check(copy, 0, 0, 0, 40); copy = test.secondOfMinute().addToCopy(-(10 * 60 * 60 + 20 * 60 + 31)); check(copy, 23, 59, 59, 40); } public void testPropertyAddNoWrapSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.secondOfMinute().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 39, 40); copy = test.secondOfMinute().addNoWrapToCopy(29); check(copy, 10, 20, 59, 40); copy = test.secondOfMinute().addNoWrapToCopy(30); check(copy, 10, 21, 0, 40); copy = test.secondOfMinute().addNoWrapToCopy(39 * 60 + 29); check(copy, 10, 59, 59, 40); copy = test.secondOfMinute().addNoWrapToCopy(39 * 60 + 30); check(copy, 11, 0, 0, 40); try { test.secondOfMinute().addNoWrapToCopy(13 * 60 * 60 + 39 * 60 + 30); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.secondOfMinute().addNoWrapToCopy(-9); check(copy, 10, 20, 21, 40); copy = test.secondOfMinute().addNoWrapToCopy(-30); check(copy, 10, 20, 0, 40); copy = test.secondOfMinute().addNoWrapToCopy(-31); check(copy, 10, 19, 59, 40); copy = test.secondOfMinute().addNoWrapToCopy(-(10 * 60 * 60 + 20 * 60 + 30)); check(copy, 0, 0, 0, 40); try { test.secondOfMinute().addNoWrapToCopy(-(10 * 60 * 60 + 20 * 60 + 31)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyAddWrapFieldSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.secondOfMinute().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 39, 40); copy = test.secondOfMinute().addWrapFieldToCopy(49); check(copy, 10, 20, 19, 40); copy = test.secondOfMinute().addWrapFieldToCopy(-47); check(copy, 10, 20, 43, 40); } public void testPropertySetSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.secondOfMinute().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 20, 12, 40); try { test.secondOfMinute().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.secondOfMinute().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.secondOfMinute().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 10, 20, 12, 40); } public void testPropertyCompareToSecond() { TimeOfDay test1 = new TimeOfDay(TEST_TIME1); TimeOfDay test2 = new TimeOfDay(TEST_TIME2); assertEquals(true, test1.secondOfMinute().compareTo(test2) < 0); assertEquals(true, test2.secondOfMinute().compareTo(test1) > 0); assertEquals(true, test1.secondOfMinute().compareTo(test1) == 0); try { test1.secondOfMinute().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.secondOfMinute().compareTo(dt2) < 0); assertEquals(true, test2.secondOfMinute().compareTo(dt1) > 0); assertEquals(true, test1.secondOfMinute().compareTo(dt1) == 0); try { test1.secondOfMinute().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMilli() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertSame(test.getChronology().millisOfSecond(), test.millisOfSecond().getField()); assertEquals("millisOfSecond", test.millisOfSecond().getName()); assertEquals("Property[millisOfSecond]", test.millisOfSecond().toString()); assertSame(test, test.millisOfSecond().getReadablePartial()); assertSame(test, test.millisOfSecond().getTimeOfDay()); assertEquals(40, test.millisOfSecond().get()); assertEquals("40", test.millisOfSecond().getAsString()); assertEquals("40", test.millisOfSecond().getAsText()); assertEquals("40", test.millisOfSecond().getAsText(Locale.FRENCH)); assertEquals("40", test.millisOfSecond().getAsShortText()); assertEquals("40", test.millisOfSecond().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().millis(), test.millisOfSecond().getDurationField()); assertEquals(test.getChronology().seconds(), test.millisOfSecond().getRangeDurationField()); assertEquals(3, test.millisOfSecond().getMaximumTextLength(null)); assertEquals(3, test.millisOfSecond().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesMilli() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); assertEquals(0, test.millisOfSecond().getMinimumValue()); assertEquals(0, test.millisOfSecond().getMinimumValueOverall()); assertEquals(999, test.millisOfSecond().getMaximumValue()); assertEquals(999, test.millisOfSecond().getMaximumValueOverall()); } public void testPropertyAddMilli() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.millisOfSecond().addToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 49); copy = test.millisOfSecond().addToCopy(959); check(copy, 10, 20, 30, 999); copy = test.millisOfSecond().addToCopy(960); check(copy, 10, 20, 31, 0); copy = test.millisOfSecond().addToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 959); check(copy, 23, 59, 59, 999); copy = test.millisOfSecond().addToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 960); check(copy, 0, 0, 0, 0); copy = test.millisOfSecond().addToCopy(-9); check(copy, 10, 20, 30, 31); copy = test.millisOfSecond().addToCopy(-40); check(copy, 10, 20, 30, 0); copy = test.millisOfSecond().addToCopy(-41); check(copy, 10, 20, 29, 999); copy = test.millisOfSecond().addToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 40)); check(copy, 0, 0, 0, 0); copy = test.millisOfSecond().addToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 41)); check(copy, 23, 59, 59, 999); } public void testPropertyAddNoWrapMilli() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.millisOfSecond().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 49); copy = test.millisOfSecond().addNoWrapToCopy(959); check(copy, 10, 20, 30, 999); copy = test.millisOfSecond().addNoWrapToCopy(960); check(copy, 10, 20, 31, 0); copy = test.millisOfSecond().addNoWrapToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 959); check(copy, 23, 59, 59, 999); try { test.millisOfSecond().addNoWrapToCopy(13 * 60 * 60 * 1000 + 39 * 60 * 1000 + 29 * 1000 + 960); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.millisOfSecond().addNoWrapToCopy(-9); check(copy, 10, 20, 30, 31); copy = test.millisOfSecond().addNoWrapToCopy(-40); check(copy, 10, 20, 30, 0); copy = test.millisOfSecond().addNoWrapToCopy(-41); check(copy, 10, 20, 29, 999); copy = test.millisOfSecond().addNoWrapToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 40)); check(copy, 0, 0, 0, 0); try { test.millisOfSecond().addNoWrapToCopy(-(10 * 60 * 60 * 1000 + 20 * 60 * 1000 + 30 * 1000 + 41)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); } public void testPropertyAddWrapFieldMilli() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.millisOfSecond().addWrapFieldToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 49); copy = test.millisOfSecond().addWrapFieldToCopy(995); check(copy, 10, 20, 30, 35); copy = test.millisOfSecond().addWrapFieldToCopy(-47); check(copy, 10, 20, 30, 993); } public void testPropertySetMilli() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.millisOfSecond().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 12); try { test.millisOfSecond().setCopy(1000); fail(); } catch (IllegalArgumentException ex) {} try { test.millisOfSecond().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMilli() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.millisOfSecond().setCopy("12"); check(test, 10, 20, 30, 40); check(copy, 10, 20, 30, 12); } public void testPropertyCompareToMilli() { TimeOfDay test1 = new TimeOfDay(TEST_TIME1); TimeOfDay test2 = new TimeOfDay(TEST_TIME2); assertEquals(true, test1.millisOfSecond().compareTo(test2) < 0); assertEquals(true, test2.millisOfSecond().compareTo(test1) > 0); assertEquals(true, test1.millisOfSecond().compareTo(test1) == 0); try { test1.millisOfSecond().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.millisOfSecond().compareTo(dt2) < 0); assertEquals(true, test2.millisOfSecond().compareTo(dt1) > 0); assertEquals(true, test1.millisOfSecond().compareTo(dt1) == 0); try { test1.millisOfSecond().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- private void check(TimeOfDay test, int hour, int min, int sec, int milli) { assertEquals(hour, test.getHourOfDay()); assertEquals(min, test.getMinuteOfHour()); assertEquals(sec, test.getSecondOfMinute()); assertEquals(milli, test.getMillisOfSecond()); } } joda-time-2.3/src/test/java/org/joda/time/ClassLoadTest.java0000644000175000017500000000410211564251363023263 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.time.base.AbstractDateTime; import org.joda.time.base.AbstractInstant; /** * This class displays what the ClassLoader is up to. * Run using JVM -verbose:class. * * @author Stephen Colebourne */ public class ClassLoadTest { // run using JVM -verbose:class public static void main(String[] args) { System.out.println("-----------------------------------------------"); System.out.println("-----------AbstractInstant---------------------"); Class cls = AbstractInstant.class; System.out.println("-----------ReadableDateTime--------------------"); cls = ReadableDateTime.class; System.out.println("-----------AbstractDateTime--------------------"); cls = AbstractDateTime.class; System.out.println("-----------DateTime----------------------------"); cls = DateTime.class; System.out.println("-----------DateTimeZone------------------------"); cls = DateTimeZone.class; System.out.println("-----------new DateTime()----------------------"); DateTime dt = new DateTime(); System.out.println("-----------new DateTime(ReadableInstant)-------"); dt = new DateTime(dt); System.out.println("-----------new DateTime(Long)------------------"); dt = new DateTime(new Long(0)); System.out.println("-----------------------------------------------"); } } joda-time-2.3/src/test/java/org/joda/time/tz/0000755000175000017500000000000012205344143020343 5ustar ebourgebourgjoda-time-2.3/src/test/java/org/joda/time/tz/TestCompiler.java0000644000175000017500000002130612134252167023627 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.StringTokenizer; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.tz.ZoneInfoCompiler.DateTimeOfYear; /** * Test cases for ZoneInfoCompiler. * * @author Brian S O'Neill */ public class TestCompiler extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestCompiler.class); } static final String AMERICA_LOS_ANGELES_FILE = "# Rules for building just America/Los_Angeles time zone.\n" + "\n" + "Rule US 1918 1919 - Mar lastSun 2:00 1:00 D\n" + "Rule US 1918 1919 - Oct lastSun 2:00 0 S\n" + "Rule US 1942 only - Feb 9 2:00 1:00 W # War\n" + "Rule US 1945 only - Aug 14 23:00u 1:00 P # Peace\n" + "Rule US 1945 only - Sep 30 2:00 0 S\n" + "Rule US 1967 max - Oct lastSun 2:00 0 S\n" + "Rule US 1967 1973 - Apr lastSun 2:00 1:00 D\n" + "Rule US 1974 only - Jan 6 2:00 1:00 D\n" + "Rule US 1975 only - Feb 23 2:00 1:00 D\n" + "Rule US 1976 1986 - Apr lastSun 2:00 1:00 D\n" + "Rule US 1987 max - Apr Sun>=1 2:00 1:00 D\n" + "\n" + "Rule CA 1948 only - Mar 14 2:00 1:00 D\n" + "Rule CA 1949 only - Jan 1 2:00 0 S\n" + "Rule CA 1950 1966 - Apr lastSun 2:00 1:00 D\n" + "Rule CA 1950 1961 - Sep lastSun 2:00 0 S\n" + "Rule CA 1962 1966 - Oct lastSun 2:00 0 S\n" + "\n" + "Zone America/Los_Angeles -7:52:58 - LMT 1883 Nov 18 12:00\n" + " -8:00 US P%sT 1946\n" + " -8:00 CA P%sT 1967\n" + " -8:00 US P%sT"; private DateTimeZone originalDateTimeZone = null; public TestCompiler(String name) { super(name); } protected void setUp() throws Exception { originalDateTimeZone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); } protected void tearDown() throws Exception { DateTimeZone.setDefault(originalDateTimeZone); } //----------------------------------------------------------------------- public void testDateTimeZoneBuilder() throws Exception { // test multithreading, issue #18 getTestDataTimeZoneBuilder().toDateTimeZone("TestDTZ1", true); final DateTimeZone[] zone = new DateTimeZone[1]; Thread t = new Thread(new Runnable() { public void run() { zone[0] = getTestDataTimeZoneBuilder().toDateTimeZone("TestDTZ2", true); } }); t.start(); t.join(); assertNotNull(zone[0]); } private DateTimeZoneBuilder getTestDataTimeZoneBuilder() { return new DateTimeZoneBuilder() .addCutover(1601, 'w', 1, 1, 1, false, 7200000) .setStandardOffset(3600000) .addRecurringSavings("", 3600000, 1601, Integer.MAX_VALUE, 'w', 3, -1, 1, false, 7200000) .addRecurringSavings("", 0, 1601, Integer.MAX_VALUE, 'w', 10, -1, 1, false, 10800000); } //----------------------------------------------------------------------- public void testCompile() throws Exception { Provider provider = compileAndLoad(AMERICA_LOS_ANGELES_FILE); DateTimeZone tz = provider.getZone("America/Los_Angeles"); assertEquals("America/Los_Angeles", tz.getID()); assertEquals(false, tz.isFixed()); TestBuilder.testForwardTransitions(tz, TestBuilder.AMERICA_LOS_ANGELES_DATA); TestBuilder.testReverseTransitions(tz, TestBuilder.AMERICA_LOS_ANGELES_DATA); } private Provider compileAndLoad(String data) throws Exception { File tempDir = createDataFile(data); File destDir = makeTempDir(); ZoneInfoCompiler.main(new String[] { "-src", tempDir.getAbsolutePath(), "-dst", destDir.getAbsolutePath(), "tzdata" }); // Mark all files to be deleted on exit. deleteOnExit(destDir); return new ZoneInfoProvider(destDir); } private File createDataFile(String data) throws IOException { File tempDir = makeTempDir(); File tempFile = new File(tempDir, "tzdata"); tempFile.deleteOnExit(); InputStream in = new ByteArrayInputStream(data.getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tempFile); byte[] buf = new byte[1000]; int amt; while ((amt = in.read(buf)) > 0) { out.write(buf, 0, amt); } out.close(); in.close(); return tempDir; } private File makeTempDir() { File tempDir = new File(System.getProperty("java.io.tmpdir")); tempDir = new File(tempDir, "joda-test-" + (new java.util.Random().nextInt() & 0xffffff)); tempDir.mkdirs(); tempDir.deleteOnExit(); return tempDir; } private void deleteOnExit(File tempFile) { tempFile.deleteOnExit(); if (tempFile.isDirectory()) { File[] files = tempFile.listFiles(); for (int i=0; i=1 24:00"); DateTimeOfYear test = new DateTimeOfYear(st); assertEquals(4, test.iMonthOfYear); // Apr assertEquals(2, test.iDayOfMonth); // 2nd assertEquals(1, test.iDayOfWeek); // Mon assertEquals(0, test.iMillisOfDay); // 00:00 assertEquals(true, test.iAdvanceDayOfWeek); } public void test_2400_last() { StringTokenizer st = new StringTokenizer("Mar lastSun 24:00"); DateTimeOfYear test = new DateTimeOfYear(st); assertEquals(4, test.iMonthOfYear); // Apr assertEquals(1, test.iDayOfMonth); // 1st assertEquals(1, test.iDayOfWeek); // Mon assertEquals(0, test.iMillisOfDay); // 00:00 assertEquals(false, test.iAdvanceDayOfWeek); } public void test_Amman_2003() { DateTimeZone zone = DateTimeZone.forID("Asia/Amman"); DateTime dt = new DateTime(2003, 3, 1, 0, 0, zone); long next = zone.nextTransition(dt.getMillis()); assertEquals(next, new DateTime(2003, 3, 28, 0, 0, DateTimeZone.forOffsetHours(2)).getMillis()); } public void test_Amman_2004() { DateTimeZone zone = DateTimeZone.forID("Asia/Amman"); DateTime dt = new DateTime(2004, 3, 1, 0, 0, zone); long next = zone.nextTransition(dt.getMillis()); assertEquals(next, new DateTime(2004, 3, 26, 0, 0, DateTimeZone.forOffsetHours(2)).getMillis()); } public void test_Amman_2005() { DateTimeZone zone = DateTimeZone.forID("Asia/Amman"); DateTime dt = new DateTime(2005, 3, 1, 0, 0, zone); long next = zone.nextTransition(dt.getMillis()); assertEquals(next, new DateTime(2005, 4, 1, 0, 0, DateTimeZone.forOffsetHours(2)).getMillis()); } public void test_Amman_2006() { DateTimeZone zone = DateTimeZone.forID("Asia/Amman"); DateTime dt = new DateTime(2006, 3, 1, 0, 0, zone); long next = zone.nextTransition(dt.getMillis()); assertEquals(next, new DateTime(2006, 3, 31, 0, 0, DateTimeZone.forOffsetHours(2)).getMillis()); } } joda-time-2.3/src/test/java/org/joda/time/tz/TestAll.java0000644000175000017500000000303411712473256022570 0ustar ebourgebourg/* * Copyright 2001-2012 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Entry point for all tests in this package. * * @version $Revision$ $Date$ * * @author Stephen Colebourne */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestUTCProvider.suite()); suite.addTest(TestBuilder.suite()); suite.addTest(TestCompiler.suite()); suite.addTest(TestCachedDateTimeZone.suite()); suite.addTest(TestFixedDateTimeZone.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } joda-time-2.3/src/test/java/org/joda/time/tz/TestFixedDateTimeZone.java0000644000175000017500000001006111564251364025365 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.util.Date; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeZone; /** * Test cases for FixedDateTimeZone. * * @author Stephen Colebourne */ public class TestFixedDateTimeZone extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestFixedDateTimeZone.class); } private DateTimeZone originalDateTimeZone = null; public TestFixedDateTimeZone(String name) { super(name); } protected void setUp() throws Exception { originalDateTimeZone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); } protected void tearDown() throws Exception { DateTimeZone.setDefault(originalDateTimeZone); } public void testEquals() throws Exception { FixedDateTimeZone zone1 = new FixedDateTimeZone("A", "B", 1, 5); FixedDateTimeZone zone1b = new FixedDateTimeZone("A", "B", 1, 5); FixedDateTimeZone zone2 = new FixedDateTimeZone("A", "C", 1, 5); FixedDateTimeZone zone3 = new FixedDateTimeZone("A", "B", 2, 5); FixedDateTimeZone zone4 = new FixedDateTimeZone("A", "B", 1, 6); assertEquals(true, zone1.equals(zone1)); assertEquals(true, zone1.equals(zone1b)); assertEquals(true, zone1.equals(zone2)); // second arg ignored assertEquals(false, zone1.equals(zone3)); assertEquals(false, zone1.equals(zone4)); } public void testHashCode() throws Exception { FixedDateTimeZone zone1 = new FixedDateTimeZone("A", "B", 1, 5); FixedDateTimeZone zone1b = new FixedDateTimeZone("A", "B", 1, 5); FixedDateTimeZone zone2 = new FixedDateTimeZone("A", "C", 1, 5); FixedDateTimeZone zone3 = new FixedDateTimeZone("A", "B", 2, 5); FixedDateTimeZone zone4 = new FixedDateTimeZone("A", "B", 1, 6); assertEquals(true, zone1.hashCode() == zone1.hashCode()); assertEquals(true, zone1.hashCode() == zone1b.hashCode()); assertEquals(true, zone1.hashCode() == zone2.hashCode()); // second arg ignored assertEquals(false, zone1.hashCode() == zone3.hashCode()); assertEquals(false, zone1.hashCode() == zone4.hashCode()); } public void testToTimeZone1() throws Exception { FixedDateTimeZone zone = new FixedDateTimeZone("+00:01", "+00:01", 60000, 60000); java.util.TimeZone tz = zone.toTimeZone(); assertEquals(60000, tz.getRawOffset()); assertEquals(60000, getOffset(tz, 1167638400000L)); assertEquals(60000, getOffset(tz, 1185951600000L)); } public void testToTimeZone2() throws Exception { FixedDateTimeZone zone = new FixedDateTimeZone("A", "B", 1, 5); java.util.TimeZone tz = zone.toTimeZone(); assertEquals(1, tz.getRawOffset()); assertEquals(1, getOffset(tz, 1167638400000L)); assertEquals(1, getOffset(tz, 1185951600000L)); } /** Make test compile on JDK 1.3. */ private int getOffset(TimeZone zone, long millis) { Date date = new Date(millis); if (zone.inDaylightTime(date)) { return zone.getRawOffset() + 3600000; } return zone.getRawOffset(); } } joda-time-2.3/src/test/java/org/joda/time/tz/TestBuilder.java0000644000175000017500000004030311564251364023445 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; /** * Test cases for DateTimeZoneBuilder. * * @author Brian S O'Neill */ public class TestBuilder extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestBuilder.class); } static final DateTimeFormatter OFFSET_FORMATTER = new DateTimeFormatterBuilder() .appendTimeZoneOffset(null, true, 2, 4) .toFormatter(); // Each row is {transition, nameKey, standardOffset, offset} static final String[][] AMERICA_LOS_ANGELES_DATA = { {null, "LMT", "-07:52:58", "-07:52:58"}, {"1883-11-18T19:52:58.000Z", "PST", "-08:00", "-08:00"}, {"1918-03-31T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1918-10-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1919-03-30T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1919-10-26T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1942-02-09T02:00:00.000-08:00", "PWT", "-08:00", "-07:00"}, {"1945-08-14T23:00:00.000Z", "PPT", "-08:00", "-07:00"}, {"1945-09-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1948-03-14T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1949-01-01T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1950-04-30T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1950-09-24T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1951-04-29T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1951-09-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1952-04-27T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1952-09-28T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1953-04-26T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1953-09-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1954-04-25T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1954-09-26T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1955-04-24T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1955-09-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1956-04-29T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1956-09-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1957-04-28T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1957-09-29T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1958-04-27T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1958-09-28T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1959-04-26T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1959-09-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1960-04-24T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1960-09-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1961-04-30T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1961-09-24T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1962-04-29T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1962-10-28T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1963-04-28T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1963-10-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1964-04-26T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1964-10-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1965-04-25T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1965-10-31T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1966-04-24T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1966-10-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1967-04-30T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1967-10-29T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1968-04-28T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1968-10-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1969-04-27T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1969-10-26T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1970-04-26T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1970-10-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1971-04-25T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1971-10-31T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1972-04-30T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1972-10-29T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1973-04-29T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1973-10-28T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1974-01-06T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1974-10-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1975-02-23T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1975-10-26T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1976-04-25T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1976-10-31T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1977-04-24T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1977-10-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1978-04-30T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1978-10-29T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1979-04-29T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1979-10-28T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1980-04-27T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1980-10-26T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1981-04-26T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1981-10-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1982-04-25T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1982-10-31T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1983-04-24T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1983-10-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1984-04-29T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1984-10-28T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1985-04-28T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1985-10-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1986-04-27T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1986-10-26T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1987-04-05T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1987-10-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1988-04-03T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1988-10-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1989-04-02T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1989-10-29T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1990-04-01T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1990-10-28T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1991-04-07T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1991-10-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1992-04-05T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1992-10-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1993-04-04T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1993-10-31T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1994-04-03T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1994-10-30T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1995-04-02T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1995-10-29T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1996-04-07T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1996-10-27T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1997-04-06T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1997-10-26T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1998-04-05T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1998-10-25T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"1999-04-04T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"1999-10-31T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, {"2000-04-02T02:00:00.000-08:00", "PDT", "-08:00", "-07:00"}, {"2000-10-29T02:00:00.000-07:00", "PST", "-08:00", "-08:00"}, }; static DateTimeZoneBuilder buildAmericaLosAngelesBuilder() { return new DateTimeZoneBuilder() .addCutover(-2147483648, 'w', 1, 1, 0, false, 0) .setStandardOffset(-28378000) .setFixedSavings("LMT", 0) .addCutover(1883, 'w', 11, 18, 0, false, 43200000) .setStandardOffset(-28800000) .addRecurringSavings("PDT", 3600000, 1918, 1919, 'w', 3, -1, 7, false, 7200000) .addRecurringSavings("PST", 0, 1918, 1919, 'w', 10, -1, 7, false, 7200000) .addRecurringSavings("PWT", 3600000, 1942, 1942, 'w', 2, 9, 0, false, 7200000) .addRecurringSavings("PPT", 3600000, 1945, 1945, 'u', 8, 14, 0, false, 82800000) .addRecurringSavings("PST", 0, 1945, 1945, 'w', 9, 30, 0, false, 7200000) .addRecurringSavings("PDT", 3600000, 1948, 1948, 'w', 3, 14, 0, false, 7200000) .addRecurringSavings("PST", 0, 1949, 1949, 'w', 1, 1, 0, false, 7200000) .addRecurringSavings("PDT", 3600000, 1950, 1966, 'w', 4, -1, 7, false, 7200000) .addRecurringSavings("PST", 0, 1950, 1961, 'w', 9, -1, 7, false, 7200000) .addRecurringSavings("PST", 0, 1962, 1966, 'w', 10, -1, 7, false, 7200000) .addRecurringSavings("PST", 0, 1967, 2147483647, 'w', 10, -1, 7, false, 7200000) .addRecurringSavings("PDT", 3600000, 1967, 1973, 'w', 4, -1, 7, false, 7200000) .addRecurringSavings("PDT", 3600000, 1974, 1974, 'w', 1, 6, 0, false, 7200000) .addRecurringSavings("PDT", 3600000, 1975, 1975, 'w', 2, 23, 0, false, 7200000) .addRecurringSavings("PDT", 3600000, 1976, 1986, 'w', 4, -1, 7, false, 7200000) .addRecurringSavings("PDT", 3600000, 1987, 2147483647, 'w', 4, 1, 7, true, 7200000); } static DateTimeZone buildAmericaLosAngeles() { return buildAmericaLosAngelesBuilder().toDateTimeZone("America/Los_Angeles", true); } private DateTimeZone originalDateTimeZone = null; public TestBuilder(String name) { super(name); } protected void setUp() throws Exception { originalDateTimeZone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); } protected void tearDown() throws Exception { DateTimeZone.setDefault(originalDateTimeZone); } public void testID() { DateTimeZone tz = buildAmericaLosAngeles(); assertEquals("America/Los_Angeles", tz.getID()); assertEquals(false, tz.isFixed()); } public void testForwardTransitions() { DateTimeZone tz = buildAmericaLosAngeles(); testForwardTransitions(tz, AMERICA_LOS_ANGELES_DATA); } static void testForwardTransitions(DateTimeZone tz, String[][] data) { long instant = Long.MIN_VALUE; for (int i=0; i=1; ) { String[] row = data[i]; String[] prevRow = data[i - 1]; instant = tz.previousTransition(instant); long expectedInstant = new DateTime(row[0]).getMillis() - 1; String expectedKey = prevRow[1]; int expectedStandardOffset = -(int) OFFSET_FORMATTER.parseMillis(prevRow[2]); int expectedOffset = -(int) OFFSET_FORMATTER.parseMillis(prevRow[3]); assertEquals(expectedInstant, instant); assertEquals(expectedKey, tz.getNameKey(instant)); assertEquals(expectedStandardOffset, tz.getStandardOffset(instant)); assertEquals(expectedOffset, tz.getOffset(instant)); } } public void testSerialization() throws IOException { DateTimeZone tz = testSerialization (buildAmericaLosAngelesBuilder(), "America/Los_Angeles"); assertEquals(false, tz.isFixed()); testForwardTransitions(tz, AMERICA_LOS_ANGELES_DATA); testReverseTransitions(tz, AMERICA_LOS_ANGELES_DATA); } static DateTimeZone testSerialization(DateTimeZoneBuilder builder, String id) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); builder.writeTo("America/Los_Angeles", out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); DateTimeZone tz = DateTimeZoneBuilder.readFrom(in, id); assertEquals(id, tz.getID()); return tz; } public void testFixed() throws IOException { DateTimeZoneBuilder builder = new DateTimeZoneBuilder() .setStandardOffset(3600000) .setFixedSavings("LMT", 0); DateTimeZone tz = builder.toDateTimeZone("Test", true); for (int i=0; i<2; i++) { assertEquals("Test", tz.getID()); assertEquals(true, tz.isFixed()); assertEquals(3600000, tz.getOffset(0)); assertEquals(3600000, tz.getStandardOffset(0)); assertEquals(0, tz.nextTransition(0)); assertEquals(0, tz.previousTransition(0)); tz = testSerialization(builder, "Test"); } } } joda-time-2.3/src/test/java/org/joda/time/tz/TestUTCProvider.java0000644000175000017500000000471111564251364024230 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Set; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeZone; /** * This class is a JUnit test for UTCProvider. * * @author Stephen Colebourne */ public class TestUTCProvider extends TestCase { private DateTimeZone zone = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestUTCProvider.class); } public TestUTCProvider(String name) { super(name); } //----------------------------------------------------------------------- public void testClass() throws Exception { Class cls = UTCProvider.class; assertEquals(true, Modifier.isPublic(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isPublic(con.getModifiers())); } //----------------------------------------------------------------------- public void testGetAvailableIDs() throws Exception { Provider p = new UTCProvider(); Set set = p.getAvailableIDs(); assertEquals(1, set.size()); assertEquals("UTC", set.iterator().next()); } //----------------------------------------------------------------------- public void testGetZone_String() throws Exception { Provider p = new UTCProvider(); assertSame(DateTimeZone.UTC, p.getZone("UTC")); assertEquals(null, p.getZone(null)); assertEquals(null, p.getZone("Europe/London")); assertEquals(null, p.getZone("Blah")); } } joda-time-2.3/src/test/java/org/joda/time/tz/TestCachedDateTimeZone.java0000644000175000017500000000530711712473256025505 0ustar ebourgebourg/* * Copyright 2001-2012 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTimeZone; /** * Test cases for FixedDateTimeZone. * * @author Stephen Colebourne */ public class TestCachedDateTimeZone extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestCachedDateTimeZone.class); } private DateTimeZone originalDateTimeZone = null; public TestCachedDateTimeZone(String name) { super(name); } protected void setUp() throws Exception { originalDateTimeZone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); } protected void tearDown() throws Exception { DateTimeZone.setDefault(originalDateTimeZone); } public void test_caching() throws Exception { CachedDateTimeZone zone1 = CachedDateTimeZone.forZone(DateTimeZone.forID("Europe/Paris")); CachedDateTimeZone zone2 = CachedDateTimeZone.forZone(DateTimeZone.forID("Europe/Paris")); assertSame(zone1, zone2); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { CachedDateTimeZone test = CachedDateTimeZone.forZone(DateTimeZone.forID("Europe/Paris")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); CachedDateTimeZone result = (CachedDateTimeZone) ois.readObject(); ois.close(); assertEquals(test, result); } } joda-time-2.3/src/test/java/org/joda/time/TestInstant_Basics.java0000644000175000017500000006352211564251363024335 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Modifier; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.base.AbstractInstant; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for Instant. * * @author Stephen Colebourne */ public class TestInstant_Basics extends TestCase { // Test in 2002/03 as time zones are more well known // (before the late 90's they were all over the place) private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; // 2002-04-05 private long TEST_TIME1 = (y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; // 2003-05-06 private long TEST_TIME2 = (y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestInstant_Basics.class); } public TestInstant_Basics(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; } //----------------------------------------------------------------------- public void testTest() { assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString()); assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString()); assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString()); } //----------------------------------------------------------------------- public void testGet_DateTimeFieldType() { Instant test = new Instant(); // 2002-06-09 assertEquals(1, test.get(DateTimeFieldType.era())); assertEquals(20, test.get(DateTimeFieldType.centuryOfEra())); assertEquals(2, test.get(DateTimeFieldType.yearOfCentury())); assertEquals(2002, test.get(DateTimeFieldType.yearOfEra())); assertEquals(2002, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); assertEquals(2002, test.get(DateTimeFieldType.weekyear())); assertEquals(23, test.get(DateTimeFieldType.weekOfWeekyear())); assertEquals(7, test.get(DateTimeFieldType.dayOfWeek())); assertEquals(160, test.get(DateTimeFieldType.dayOfYear())); assertEquals(0, test.get(DateTimeFieldType.halfdayOfDay())); assertEquals(0, test.get(DateTimeFieldType.hourOfHalfday())); // UTC zone assertEquals(24, test.get(DateTimeFieldType.clockhourOfDay())); // UTC zone assertEquals(12, test.get(DateTimeFieldType.clockhourOfHalfday())); // UTC zone assertEquals(0, test.get(DateTimeFieldType.hourOfDay())); // UTC zone assertEquals(0, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(0, test.get(DateTimeFieldType.minuteOfDay())); assertEquals(0, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(0, test.get(DateTimeFieldType.secondOfDay())); assertEquals(0, test.get(DateTimeFieldType.millisOfSecond())); assertEquals(0, test.get(DateTimeFieldType.millisOfDay())); try { test.get((DateTimeFieldType) null); fail(); } catch (IllegalArgumentException ex) {} } public void testGet_DateTimeField() { Instant test = new Instant(); // 2002-06-09 assertEquals(1, test.get(ISOChronology.getInstance().era())); assertEquals(20, test.get(ISOChronology.getInstance().centuryOfEra())); assertEquals(2, test.get(ISOChronology.getInstance().yearOfCentury())); assertEquals(2002, test.get(ISOChronology.getInstance().yearOfEra())); assertEquals(2002, test.get(ISOChronology.getInstance().year())); assertEquals(6, test.get(ISOChronology.getInstance().monthOfYear())); assertEquals(9, test.get(ISOChronology.getInstance().dayOfMonth())); assertEquals(2002, test.get(ISOChronology.getInstance().weekyear())); assertEquals(23, test.get(ISOChronology.getInstance().weekOfWeekyear())); assertEquals(7, test.get(ISOChronology.getInstance().dayOfWeek())); assertEquals(160, test.get(ISOChronology.getInstance().dayOfYear())); assertEquals(0, test.get(ISOChronology.getInstance().halfdayOfDay())); assertEquals(1, test.get(ISOChronology.getInstance().hourOfHalfday())); assertEquals(1, test.get(ISOChronology.getInstance().clockhourOfDay())); assertEquals(1, test.get(ISOChronology.getInstance().clockhourOfHalfday())); assertEquals(1, test.get(ISOChronology.getInstance().hourOfDay())); assertEquals(0, test.get(ISOChronology.getInstance().minuteOfHour())); assertEquals(60, test.get(ISOChronology.getInstance().minuteOfDay())); assertEquals(0, test.get(ISOChronology.getInstance().secondOfMinute())); assertEquals(60 * 60, test.get(ISOChronology.getInstance().secondOfDay())); assertEquals(0, test.get(ISOChronology.getInstance().millisOfSecond())); assertEquals(60 * 60 * 1000, test.get(ISOChronology.getInstance().millisOfDay())); try { test.get((DateTimeField) null); fail(); } catch (IllegalArgumentException ex) {} } public void testGetMethods() { Instant test = new Instant(); assertEquals(ISOChronology.getInstanceUTC(), test.getChronology()); assertEquals(DateTimeZone.UTC, test.getZone()); assertEquals(TEST_TIME_NOW, test.getMillis()); } public void testEqualsHashCode() { Instant test1 = new Instant(TEST_TIME1); Instant test2 = new Instant(TEST_TIME1); assertEquals(true, test1.equals(test2)); assertEquals(true, test2.equals(test1)); assertEquals(true, test1.equals(test1)); assertEquals(true, test2.equals(test2)); assertEquals(true, test1.hashCode() == test2.hashCode()); assertEquals(true, test1.hashCode() == test1.hashCode()); assertEquals(true, test2.hashCode() == test2.hashCode()); Instant test3 = new Instant(TEST_TIME2); assertEquals(false, test1.equals(test3)); assertEquals(false, test2.equals(test3)); assertEquals(false, test3.equals(test1)); assertEquals(false, test3.equals(test2)); assertEquals(false, test1.hashCode() == test3.hashCode()); assertEquals(false, test2.hashCode() == test3.hashCode()); assertEquals(false, test1.equals("Hello")); assertEquals(true, test1.equals(new MockInstant())); assertEquals(false, test1.equals(new DateTime(TEST_TIME1))); } class MockInstant extends AbstractInstant { public String toString() { return null; } public long getMillis() { return TEST_TIME1; } public Chronology getChronology() { return ISOChronology.getInstanceUTC(); } } public void testCompareTo() { Instant test1 = new Instant(TEST_TIME1); Instant test1a = new Instant(TEST_TIME1); assertEquals(0, test1.compareTo(test1a)); assertEquals(0, test1a.compareTo(test1)); assertEquals(0, test1.compareTo(test1)); assertEquals(0, test1a.compareTo(test1a)); Instant test2 = new Instant(TEST_TIME2); assertEquals(-1, test1.compareTo(test2)); assertEquals(+1, test2.compareTo(test1)); DateTime test3 = new DateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(-1, test1.compareTo(test3)); assertEquals(+1, test3.compareTo(test1)); assertEquals(0, test3.compareTo(test2)); assertEquals(+1, test2.compareTo(new MockInstant())); assertEquals(0, test1.compareTo(new MockInstant())); try { test1.compareTo(null); fail(); } catch (NullPointerException ex) {} // try { // test1.compareTo(new Date()); // fail(); // } catch (ClassCastException ex) {} } //----------------------------------------------------------------------- public void testIsEqual_long() { assertEquals(false, new Instant(TEST_TIME1).isEqual(TEST_TIME2)); assertEquals(true, new Instant(TEST_TIME1).isEqual(TEST_TIME1)); assertEquals(false, new Instant(TEST_TIME2).isEqual(TEST_TIME1)); } public void testIsEqualNow() { assertEquals(false, new Instant(TEST_TIME_NOW - 1).isEqualNow()); assertEquals(true, new Instant(TEST_TIME_NOW).isEqualNow()); assertEquals(false, new Instant(TEST_TIME_NOW + 1).isEqualNow()); } public void testIsEqual_RI() { Instant test1 = new Instant(TEST_TIME1); Instant test1a = new Instant(TEST_TIME1); assertEquals(true, test1.isEqual(test1a)); assertEquals(true, test1a.isEqual(test1)); assertEquals(true, test1.isEqual(test1)); assertEquals(true, test1a.isEqual(test1a)); Instant test2 = new Instant(TEST_TIME2); assertEquals(false, test1.isEqual(test2)); assertEquals(false, test2.isEqual(test1)); DateTime test3 = new DateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(false, test1.isEqual(test3)); assertEquals(false, test3.isEqual(test1)); assertEquals(true, test3.isEqual(test2)); assertEquals(false, test2.isEqual(new MockInstant())); assertEquals(true, test1.isEqual(new MockInstant())); assertEquals(false, new Instant(TEST_TIME_NOW + 1).isEqual(null)); assertEquals(true, new Instant(TEST_TIME_NOW).isEqual(null)); assertEquals(false, new Instant(TEST_TIME_NOW - 1).isEqual(null)); } //----------------------------------------------------------------------- public void testIsBefore_long() { assertEquals(true, new Instant(TEST_TIME1).isBefore(TEST_TIME2)); assertEquals(false, new Instant(TEST_TIME1).isBefore(TEST_TIME1)); assertEquals(false, new Instant(TEST_TIME2).isBefore(TEST_TIME1)); } public void testIsBeforeNow() { assertEquals(true, new Instant(TEST_TIME_NOW - 1).isBeforeNow()); assertEquals(false, new Instant(TEST_TIME_NOW).isBeforeNow()); assertEquals(false, new Instant(TEST_TIME_NOW + 1).isBeforeNow()); } public void testIsBefore_RI() { Instant test1 = new Instant(TEST_TIME1); Instant test1a = new Instant(TEST_TIME1); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); Instant test2 = new Instant(TEST_TIME2); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); DateTime test3 = new DateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); assertEquals(false, test2.isBefore(new MockInstant())); assertEquals(false, test1.isBefore(new MockInstant())); assertEquals(false, new Instant(TEST_TIME_NOW + 1).isBefore(null)); assertEquals(false, new Instant(TEST_TIME_NOW).isBefore(null)); assertEquals(true, new Instant(TEST_TIME_NOW - 1).isBefore(null)); } //----------------------------------------------------------------------- public void testIsAfter_long() { assertEquals(false, new Instant(TEST_TIME1).isAfter(TEST_TIME2)); assertEquals(false, new Instant(TEST_TIME1).isAfter(TEST_TIME1)); assertEquals(true, new Instant(TEST_TIME2).isAfter(TEST_TIME1)); } public void testIsAfterNow() { assertEquals(false, new Instant(TEST_TIME_NOW - 1).isAfterNow()); assertEquals(false, new Instant(TEST_TIME_NOW).isAfterNow()); assertEquals(true, new Instant(TEST_TIME_NOW + 1).isAfterNow()); } public void testIsAfter_RI() { Instant test1 = new Instant(TEST_TIME1); Instant test1a = new Instant(TEST_TIME1); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); Instant test2 = new Instant(TEST_TIME2); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); DateTime test3 = new DateTime(TEST_TIME2, GregorianChronology.getInstance(PARIS)); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); assertEquals(true, test2.isAfter(new MockInstant())); assertEquals(false, test1.isAfter(new MockInstant())); assertEquals(true, new Instant(TEST_TIME_NOW + 1).isAfter(null)); assertEquals(false, new Instant(TEST_TIME_NOW).isAfter(null)); assertEquals(false, new Instant(TEST_TIME_NOW - 1).isAfter(null)); } //----------------------------------------------------------------------- public void testSerialization() throws Exception { Instant test = new Instant(TEST_TIME_NOW); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(test); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Instant result = (Instant) ois.readObject(); ois.close(); assertEquals(test, result); } //----------------------------------------------------------------------- public void testToString() { Instant test = new Instant(TEST_TIME_NOW); assertEquals("2002-06-09T00:00:00.000Z", test.toString()); } //----------------------------------------------------------------------- public void testToInstant() { Instant test = new Instant(TEST_TIME1); Instant result = test.toInstant(); assertSame(test, result); } public void testToDateTime() { Instant test = new Instant(TEST_TIME1); DateTime result = test.toDateTime(); assertEquals(TEST_TIME1, result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToDateTimeISO() { Instant test = new Instant(TEST_TIME1); DateTime result = test.toDateTimeISO(); assertSame(DateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToDateTime_DateTimeZone() { Instant test = new Instant(TEST_TIME1); DateTime result = test.toDateTime(LONDON); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(LONDON), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toDateTime(PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToDateTime_Chronology() { Instant test = new Instant(TEST_TIME1); DateTime result = test.toDateTime(ISOChronology.getInstance()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toDateTime(GregorianChronology.getInstance(PARIS)); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GregorianChronology.getInstance(PARIS), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toDateTime((Chronology) null); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToMutableDateTime() { Instant test = new Instant(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToMutableDateTimeISO() { Instant test = new Instant(TEST_TIME1); MutableDateTime result = test.toMutableDateTimeISO(); assertSame(MutableDateTime.class, result.getClass()); assertSame(ISOChronology.class, result.getChronology().getClass()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToMutableDateTime_DateTimeZone() { Instant test = new Instant(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(LONDON); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toMutableDateTime(PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toMutableDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToMutableDateTime_Chronology() { Instant test = new Instant(TEST_TIME1); MutableDateTime result = test.toMutableDateTime(ISOChronology.getInstance()); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toMutableDateTime(GregorianChronology.getInstance(PARIS)); assertEquals(test.getMillis(), result.getMillis()); assertEquals(GregorianChronology.getInstance(PARIS), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toMutableDateTime((Chronology) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); } public void testToDate() { Instant test = new Instant(TEST_TIME1); Date result = test.toDate(); assertEquals(test.getMillis(), result.getTime()); } //----------------------------------------------------------------------- public void testWithMillis_long() { Instant test = new Instant(TEST_TIME1); Instant result = test.withMillis(TEST_TIME2); assertEquals(TEST_TIME2, result.getMillis()); assertEquals(test.getChronology(), result.getChronology()); test = new Instant(TEST_TIME1); result = test.withMillis(TEST_TIME1); assertSame(test, result); } //----------------------------------------------------------------------- public void testWithDurationAdded_long_int() { Instant test = new Instant(TEST_TIME1); Instant result = test.withDurationAdded(123456789L, 1); Instant expected = new Instant(TEST_TIME1 + 123456789L); assertEquals(expected, result); result = test.withDurationAdded(123456789L, 0); assertSame(test, result); result = test.withDurationAdded(123456789L, 2); expected = new Instant(TEST_TIME1 + (2L * 123456789L)); assertEquals(expected, result); result = test.withDurationAdded(123456789L, -3); expected = new Instant(TEST_TIME1 - (3L * 123456789L)); assertEquals(expected, result); } //----------------------------------------------------------------------- public void testWithDurationAdded_RD_int() { Instant test = new Instant(TEST_TIME1); Instant result = test.withDurationAdded(new Duration(123456789L), 1); Instant expected = new Instant(TEST_TIME1 + 123456789L); assertEquals(expected, result); result = test.withDurationAdded(null, 1); assertSame(test, result); result = test.withDurationAdded(new Duration(123456789L), 0); assertSame(test, result); result = test.withDurationAdded(new Duration(123456789L), 2); expected = new Instant(TEST_TIME1 + (2L * 123456789L)); assertEquals(expected, result); result = test.withDurationAdded(new Duration(123456789L), -3); expected = new Instant(TEST_TIME1 - (3L * 123456789L)); assertEquals(expected, result); } //----------------------------------------------------------------------- public void testPlus_long() { Instant test = new Instant(TEST_TIME1); Instant result = test.plus(123456789L); Instant expected = new Instant(TEST_TIME1 + 123456789L); assertEquals(expected, result); } public void testPlus_RD() { Instant test = new Instant(TEST_TIME1); Instant result = test.plus(new Duration(123456789L)); Instant expected = new Instant(TEST_TIME1 + 123456789L); assertEquals(expected, result); result = test.plus((ReadableDuration) null); assertSame(test, result); } //----------------------------------------------------------------------- public void testMinus_long() { Instant test = new Instant(TEST_TIME1); Instant result = test.minus(123456789L); Instant expected = new Instant(TEST_TIME1 - 123456789L); assertEquals(expected, result); } public void testMinus_RD() { Instant test = new Instant(TEST_TIME1); Instant result = test.minus(new Duration(123456789L)); Instant expected = new Instant(TEST_TIME1 - 123456789L); assertEquals(expected, result); result = test.minus((ReadableDuration) null); assertSame(test, result); } //----------------------------------------------------------------------- public void testImmutable() { assertTrue(Modifier.isFinal(Instant.class.getModifiers())); } } joda-time-2.3/src/test/java/org/joda/time/TestYearMonth_Properties.java0000644000175000017500000003631211564251364025551 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.chrono.StrictChronology; /** * This class is a Junit unit test for YearMonth. * * @author Stephen Colebourne */ public class TestYearMonth_Properties extends TestCase { private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS); private long TEST_TIME_NOW = (31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private long TEST_TIME1 = (31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY + 12L * DateTimeConstants.MILLIS_PER_HOUR + 24L * DateTimeConstants.MILLIS_PER_MINUTE; private long TEST_TIME2 = (365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY + 14L * DateTimeConstants.MILLIS_PER_HOUR + 28L * DateTimeConstants.MILLIS_PER_MINUTE; private DateTimeZone zone = null; private Locale systemDefaultLocale = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestYearMonth_Properties.class); } public TestYearMonth_Properties(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); zone = DateTimeZone.getDefault(); DateTimeZone.setDefault(DateTimeZone.UTC); systemDefaultLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(zone); zone = null; Locale.setDefault(systemDefaultLocale); systemDefaultLocale = null; } //----------------------------------------------------------------------- public void testPropertyGetYear() { YearMonth test = new YearMonth(1972, 6); assertSame(test.getChronology().year(), test.year().getField()); assertEquals("year", test.year().getName()); assertEquals("Property[year]", test.year().toString()); assertSame(test, test.year().getReadablePartial()); assertSame(test, test.year().getYearMonth()); assertEquals(1972, test.year().get()); assertEquals("1972", test.year().getAsString()); assertEquals("1972", test.year().getAsText()); assertEquals("1972", test.year().getAsText(Locale.FRENCH)); assertEquals("1972", test.year().getAsShortText()); assertEquals("1972", test.year().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().years(), test.year().getDurationField()); assertEquals(null, test.year().getRangeDurationField()); assertEquals(9, test.year().getMaximumTextLength(null)); assertEquals(9, test.year().getMaximumShortTextLength(null)); } public void testPropertyGetMaxMinValuesYear() { YearMonth test = new YearMonth(1972, 6); assertEquals(-292275054, test.year().getMinimumValue()); assertEquals(-292275054, test.year().getMinimumValueOverall()); assertEquals(292278993, test.year().getMaximumValue()); assertEquals(292278993, test.year().getMaximumValueOverall()); } public void testPropertyAddYear() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.year().addToCopy(9); check(test, 1972, 6); check(copy, 1981, 6); copy = test.year().addToCopy(0); check(copy, 1972, 6); copy = test.year().addToCopy(292277023 - 1972); check(copy, 292277023, 6); try { test.year().addToCopy(292278993 - 1972 + 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6); copy = test.year().addToCopy(-1972); check(copy, 0, 6); copy = test.year().addToCopy(-1973); check(copy, -1, 6); try { test.year().addToCopy(-292275054 - 1972 - 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6); } public void testPropertyAddWrapFieldYear() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.year().addWrapFieldToCopy(9); check(test, 1972, 6); check(copy, 1981, 6); copy = test.year().addWrapFieldToCopy(0); check(copy, 1972, 6); copy = test.year().addWrapFieldToCopy(292278993 - 1972 + 1); check(copy, -292275054, 6); copy = test.year().addWrapFieldToCopy(-292275054 - 1972 - 1); check(copy, 292278993, 6); } public void testPropertySetYear() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.year().setCopy(12); check(test, 1972, 6); check(copy, 12, 6); } public void testPropertySetTextYear() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.year().setCopy("12"); check(test, 1972, 6); check(copy, 12, 6); } public void testPropertyCompareToYear() { YearMonth test1 = new YearMonth(TEST_TIME1); YearMonth test2 = new YearMonth(TEST_TIME2); assertEquals(true, test1.year().compareTo(test2) < 0); assertEquals(true, test2.year().compareTo(test1) > 0); assertEquals(true, test1.year().compareTo(test1) == 0); try { test1.year().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.year().compareTo(dt2) < 0); assertEquals(true, test2.year().compareTo(dt1) > 0); assertEquals(true, test1.year().compareTo(dt1) == 0); try { test1.year().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyGetMonth() { YearMonth test = new YearMonth(1972, 6); assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField()); assertEquals("monthOfYear", test.monthOfYear().getName()); assertEquals("Property[monthOfYear]", test.monthOfYear().toString()); assertSame(test, test.monthOfYear().getReadablePartial()); assertSame(test, test.monthOfYear().getYearMonth()); assertEquals(6, test.monthOfYear().get()); assertEquals("6", test.monthOfYear().getAsString()); assertEquals("June", test.monthOfYear().getAsText()); assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("Jun", test.monthOfYear().getAsShortText()); assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH)); assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField()); assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField()); assertEquals(9, test.monthOfYear().getMaximumTextLength(null)); assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null)); test = new YearMonth(1972, 7); assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH)); assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH)); } public void testPropertyGetMaxMinValuesMonth() { YearMonth test = new YearMonth(1972, 6); assertEquals(1, test.monthOfYear().getMinimumValue()); assertEquals(1, test.monthOfYear().getMinimumValueOverall()); assertEquals(12, test.monthOfYear().getMaximumValue()); assertEquals(12, test.monthOfYear().getMaximumValueOverall()); } public void testPropertyAddMonth() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.monthOfYear().addToCopy(6); check(test, 1972, 6); check(copy, 1972, 12); copy = test.monthOfYear().addToCopy(7); check(copy, 1973, 1); copy = test.monthOfYear().addToCopy(-5); check(copy, 1972, 1); copy = test.monthOfYear().addToCopy(-6); check(copy, 1971, 12); } public void testPropertyAddWrapFieldMonth() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.monthOfYear().addWrapFieldToCopy(4); check(test, 1972, 6); check(copy, 1972, 10); copy = test.monthOfYear().addWrapFieldToCopy(8); check(copy, 1972, 2); copy = test.monthOfYear().addWrapFieldToCopy(-8); check(copy, 1972, 10); } public void testPropertySetMonth() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.monthOfYear().setCopy(12); check(test, 1972, 6); check(copy, 1972, 12); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} } public void testPropertySetTextMonth() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.monthOfYear().setCopy("12"); check(test, 1972, 6); check(copy, 1972, 12); copy = test.monthOfYear().setCopy("December"); check(test, 1972, 6); check(copy, 1972, 12); copy = test.monthOfYear().setCopy("Dec"); check(test, 1972, 6); check(copy, 1972, 12); } public void testPropertyCompareToMonth() { YearMonth test1 = new YearMonth(TEST_TIME1); YearMonth test2 = new YearMonth(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPropertyEquals() { YearMonth test1 = new YearMonth(11, 11); YearMonth test2 = new YearMonth(11, 12); YearMonth test3 = new YearMonth(11, 11, CopticChronology.getInstanceUTC()); assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test1.year())); assertEquals(false, test1.monthOfYear().equals(test2.monthOfYear())); assertEquals(false, test1.monthOfYear().equals(test2.year())); assertEquals(false, test1.year().equals(test1.monthOfYear())); assertEquals(true, test1.year().equals(test1.year())); assertEquals(false, test1.year().equals(test2.monthOfYear())); assertEquals(true, test1.year().equals(test2.year())); assertEquals(false, test1.monthOfYear().equals(null)); assertEquals(false, test1.monthOfYear().equals("any")); // chrono assertEquals(false, test1.monthOfYear().equals(test3.monthOfYear())); } public void testPropertyHashCode() { YearMonth test1 = new YearMonth(2005, 11); YearMonth test2 = new YearMonth(2005, 12); assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode()); assertEquals(false, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); assertEquals(true, test1.year().hashCode() == test1.year().hashCode()); assertEquals(true, test1.year().hashCode() == test2.year().hashCode()); } public void testPropertyEqualsHashCodeLenient() { YearMonth test1 = new YearMonth(1970, 6, LenientChronology.getInstance(COPTIC_PARIS)); YearMonth test2 = new YearMonth(1970, 6, LenientChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear())); assertEquals(true, test2.monthOfYear().equals(test1.monthOfYear())); assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear())); assertEquals(true, test2.monthOfYear().equals(test2.monthOfYear())); assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode()); assertEquals(true, test2.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); } public void testPropertyEqualsHashCodeStrict() { YearMonth test1 = new YearMonth(1970, 6, StrictChronology.getInstance(COPTIC_PARIS)); YearMonth test2 = new YearMonth(1970, 6, StrictChronology.getInstance(COPTIC_PARIS)); assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear())); assertEquals(true, test2.monthOfYear().equals(test1.monthOfYear())); assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear())); assertEquals(true, test2.monthOfYear().equals(test2.monthOfYear())); assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode()); assertEquals(true, test2.monthOfYear().hashCode() == test2.monthOfYear().hashCode()); } //----------------------------------------------------------------------- private void check(YearMonth test, int year, int month) { assertEquals(year, test.getYear()); assertEquals(month, test.getMonthOfYear()); } } joda-time-2.3/src/tz-data/0000755000175000017500000000000012073523033014710 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/0000755000175000017500000000000012073523033015477 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/0000755000175000017500000000000012073523033016414 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/0000755000175000017500000000000012073523033017352 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/0000755000175000017500000000000012073523033020007 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/0000755000175000017500000000000012205344143020720 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/0000755000175000017500000000000012205344143022457 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Bermuda0000644000175000017500000000105011564260551023764 0ustar ebourgebourgCLMTASTADTFÿ€¿ÿÿÃH¿ÿÿÃH¿´ÃØ88@"­¨:8@&­,88@*­(:8@.¬¬88@2¬¨:8@6ÓŒ88@:¬(:8@>Ó 88@BÓ:8@FÒŒ88@JÒˆ:8@NÒ 88@RÒ:8@VÑŒ88@Zш:8@^Ñ 88@bÑ:8@f÷ì88@jЈ:8@n÷l88@r÷h:8@vöì88@zöè:8@~öl88@‚öh:8@†õì88@ŠÈ:8@Žõl88@’H:8@—L88@š~È:8@ŸÌ88@¢~H:8@§L88@ª¥(:8@¯Ì88@²¤¨:8@·L88@º¤(:8@¿A,88@£¨:8@Ç@¬88@Ê£(:8@Ï@,88@ÒÊ:8@×?¬88@ÚɈ:8@ß?,88@âÉ:8@ç>¬88@êȈ:8@ïeŒ88@òÈ:8@÷e 88@úLj:8@ÿdŒ88Aîh:8Ad 88A íè:8AcŒ88Aíh:8AŠl88Aìè:8A‰ì88A"ìh:8A'‰l88A*uÈ:8A/°L888wADTw ASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/South_Georgia0000644000175000017500000000005611564260551025151 0ustar ebourgebourgPLMTGSTÿ€¿ÿÿÝÀ¿ÿÿÝÀ¿i†ýÀ<<joda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Reykjavik0000644000175000017500000000100711564260550024345 0ustar ebourgebourgCLMTGMTISTRMTISSTBÿ€¿ÿÿë„¿ÿÿë„¿Ö"ü¿ÿÿël¿ÿÿël¿‹`ƒ”>>~WÀ€>~]œ>>~_Å >~e®ü>> Ñ€>€>>oT>ø˜>>•ø>ø>> ¼Ø>%Ð8>>(¼X>-ϸ>>0»Ø>5Ï8>>8»X>=ö>>@ºØ>Eõ˜>>I8>Mõ>>Q~¸>Uô˜>>Y~8>^x>>a}¸>eó˜>>i}8>nx>>q¤>vø>>y£˜>~x>>£>†ø>>‰¢˜>Žx>>‘¢>–?X>>™Èø>ž>Ø>>¡Èx>¦>X>>©Çø>®=Ø>>±Çx>¶=X>>¹Æø>¾<Ø>>ÁÆx>Æc¸>>ÉíX>Îc8>>ÑìØ>Öb¸>>ÙìX>Þb8>>áëØ>æa¸>>éëX>>>ò8joda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Madeira0000644000175000017500000000206611564260550023756 0ustar ebourgebourgCWESTLMTMADTWETFMTMADMTMADSTŒÿ€¿ÿÿð(¿ÿÿð(¿^=X¿ÿÿð(¿ÿÿð(¿‘ÁñX>>~RS >~UP\>>~Wó >~\õ >>~_ýà>~dúÀ>>~gý`>~lÿà>>~p >~u  >>~x @>~}À>>~‘* >~•$À>>~¡:€>~¤ë€>>~© >~¬ë>>~±9€>~µà>>~¹``>~½`>>~É_`>~Í`>>~Ñ >~Õà>>~á6€>~å6@>>~é >~í5À>>~ñ„@>~õ5@>>~ù5>~ý4À>> >4@>> ‚À>G`>>n >Z >>Z`>_À>> ãÀ>!ÏÄ>$EÄ>%ÏÀ>>(ã@>)§ä>,”>-ö >>0âÀ>1ÎÄ>4“„>5ö >>8â@>9ÎD><“>=õ >>A@>E>>It>M4>>Q~ô>U~´>>Y~t>]~4>>i}t>m¤”>>q¤T>u¤>>y£Ô>}£”>>£T>…£>>‰¢Ô>¢”>>‘¢T>•Ét>>™É4>Èô>>¡È´>¥Èt>>©È4>­Çô>>±Ç´>µÇt>>¹Ç4>½Æô>>ÁÆ´>ÅíÔ>>Éí”>ÍíT>>Ñí>ÕìÔ>>Ùì”>ÝìT>>áì@: @@> @B4 @F3à@J3 @N3œ@R3 @V3@Z2Ü@^2œ@b2\@f2@j2@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿWESTu ÿWETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/St_Helena0000644000175000017500000000010311564260547024252 0ustar ebourgebourgPLMTGMTJMTÿ€¿ÿÿú¨¿ÿÿú¨¿i†àØ¿ÿÿú¨¿ÿÿú¨¿ÜB›Xjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Faroe0000644000175000017500000000045611564260550023451 0ustar ebourgebourgCWESTLMTWET"ÿ€¿ÿÿù¨¿ÿÿù¨¿‹m¤X@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿWESTu ÿWETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Cape_Verde0000644000175000017500000000011111564260547024404 0ustar ebourgebourgPCVSTLMTCVTÿ€¿ÿÿéô¿ÿÿéô¿‰QŒ<<$ x><=¬¼<<@/U0>>joda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Canary0000644000175000017500000000051111564260550023622 0ustar ebourgebourgCWESTCANTLMTWET%ÿ€¿ÿÿñ¿ÿÿñ¿¦\ð>>E]¸@RZ€@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿWESTu ÿWETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Azores0000644000175000017500000000206211564260550023653 0ustar ebourgebourgCLMTWETAZOMTAZOSTAZOTHMTŒÿ€¿ÿÿçð¿ÿÿçð¿^=¿ÿÿå(¿ÿÿå(¿‘ÁüX<<~RS\><~UP˜<<~Wó\><~\õÜ<<~_þ><~dúü<<~gýœ><~m<<~p\><~u Ü<<~x |><~}ü<<~‘*Ü><~•$ü<<~¡:¼><~¤ë¼<<~©Ü><~¬ë<<<~±9¼><~µ<<~¹`œ><~½œ<<~É_œ><~Íœ<<~Ñ\><~Õ<<~á6¼><~å6|<<~éÜ><~í5ü<<~ñ„|><~õ5|<<~ù5<><~ý4ü<< \><4|<< ‚ü><Gœ<<nÜ><ZÜ<<Zœ><_ü<< ãü><!Ð<$F><%Ïü<<(ã|><)¨ <,”@><-öÜ<<0âü><1Ï<4“À><5ö\<<8â|><9΀<<“@><=õÜ<<A|><E<<<I°><Mp<<Q0><U~ð<<Y~°><]~p<<i}°><m¤Ð<<q¤><u¤P<<y¤><}£Ð<<£><…£P<<‰£><¢Ð<<‘¢><•ɰ<<™Ép><É0<<¡Èð><¥È°<<©Èp><­È0<<±Çð><µÇ°<<¹Çp><½Ç0<<ÁÆð><Åî<<ÉíÐ><Íí<<ÑíP><Õí<<ÙìÐ><Ýì<<áìP>>@: |>@> <>>@B4\>@F4>>@J3Ü>@N3Ø>>@R3\>@V3X>>@Z3>@^2Ø>>@b2˜>@f2X>>@j2T>@n1Ø>>@r1˜>@vX¸>>@zXx>@~X8>>@‚Wø>@†W¸>>@ŠWx>@ŽW8>>@’Vø>@–V¸>>@šVx>@žV8>>@¢Uø>@¦}>>@ª|Ø>@®|˜>>@²|X>@¶|@º{œ>@¾{\>>@Â{>@ÆzÜ>>@Êzœ>@Îz\>>@Ò¡|>@×>¼>>>uÿAZOSTu ÿAZOTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Atlantic/Stanley0000644000175000017500000000070111564260551024026 0ustar ebourgebourgCLMTFKSTFKTSMT5ÿ€¿ÿÿÉÄ¿ÿÿÉÄ¿i‡¼¿ÿÿÉÄ¿ÿÿÉÄ¿“D_<88~ýP:8æt88 Ð:8åô88 4°:8 Ô8840:8 T883°:8! Ô88%30:8'Nô88@j÷p::@n2<:@röx::@v 4<:@zõø::@~ ð:8@‚ÎT88@† p:8@ŠÍÔ88@Žð:8@’ÍT88@–p:8@šÌÔ88@žð:8@¢ó´88@¦p:8@ªó488@®.P:8@²ò´88@¶-Ð:8@ºò488@¾-P:8@Âñ´88@Æ,Ð:8@Êñ488@Î,P:8@Ó88@ÖS0:8@Û”88@ÞR°:8@ã88@æR0:8@ë”88@îQ°:8@ó88@öQ0:8@û 88@þ)È:88wFKTw FKSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/MST7MDT0000644000175000017500000000126011564260550021747 0ustar ebourgebourgCMWTMDTMPTMSTZÿ€22~`£42~e@ 22~h¢œ42~m? 22 &œ42ÓÀ22@BÓ¼42@FÓ@22@JÓ<42@NÒÀ22@RÒ¼42@VÒ@22@ZÒ<42@^ÑÀ22@bѼ42@fø 22@jÑ<42@nø 22@rø42@v÷ 22@z÷œ42@~÷ 22@‚÷42@†ö 22@Š€|42@Žö 22@’ü42@—22@š|42@Ÿ€22@¢~ü42@§22@ª¥Ü42@¯€22@²¥\42@·22@º¤Ü42@¿Aà22@¤\42@ÇA`22@Ê£Ü42@Ï@à22@Òʼ42@×@`22@ÚÊ<42@ß?à22@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@úÈ<42@ÿe@22Aï42AdÀ22A îœ42Ad@22Aî42A‹ 22Aíœ42AŠ 22A"í42A'Š 22A*v|42A/±222wMDTw MSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/0000755000175000017500000000000012205344143022122 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Mayotte0000644000175000017500000000005611564260547023504 0ustar ebourgebourgPLMTEATÿ€€*h€*h¿‘óÐjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Mahe0000644000175000017500000000005611564260547022734 0ustar ebourgebourgPSCTLMTÿ€€3ü€3ü¿ˆdæ„joda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Kerguelen0000644000175000017500000000004511564260547024001 0ustar ebourgebourgPzzzTFTÿ€_}` joda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Comoro0000644000175000017500000000005611564260547023320 0ustar ebourgebourgPLMTEATÿ€€(€(¿‘óÑðjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Mauritius0000644000175000017500000000011511564260547024040 0ustar ebourgebourgCMUTLMTMUSTÿ€@æ@æ~b:@f° @j´A7†È A:èÌjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Christmas0000644000175000017500000000005611564260550024011 0ustar ebourgebourgPLMTCXTÿ€€c€c¿s©äjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Cocos0000644000175000017500000000005611564260550023122 0ustar ebourgebourgPLMTCCTÿ€€ZÜ€ZÜ¿|U&¤ joda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Antananarivo0000644000175000017500000000010211564260547024473 0ustar ebourgebourgCLMTEASTEATÿ€€,Œ€,Œ¿‘óÍô€ÜЂܰjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Maldives0000644000175000017500000000007511564260550023621 0ustar ebourgebourgPLMTMVTMMTÿ€@&@&}-µÚ@&@&¯ºº joda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Chagos0000644000175000017500000000006511564260547023266 0ustar ebourgebourgPLMTIOTÿ€€Cä€C俉~÷œ @Ð¥Ô joda-time-2.3/src/tz-data/org/joda/time/tz/data/Indian/Reunion0000644000175000017500000000005611564260547023501 0ustar ebourgebourgPRETLMTÿ€€4€4¿‘Ì9€joda-time-2.3/src/tz-data/org/joda/time/tz/data/EST5EDT0000644000175000017500000000126011564260550021725 0ustar ebourgebourgCEPTEWTEDTESTZÿ€66~`¢¤86~e?¨66~h¢$86~m?(66 &$86ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/WET0000644000175000017500000000052111564260550021306 0ustar ebourgebourgCWESTWET)ÿ€@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿWESTu ÿWETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/0000755000175000017500000000000012205344143022645 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Darwin0000644000175000017500000000017111564260550024021 0ustar ebourgebourgCCSTLMT CST-Summer ÿ€€z¨€z¨¿s’X}ÈÕd~V¥~Xx"G^!0‚%0~)0-W^1/‚joda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Adelaide0000644000175000017500000000124611564260550024271 0ustar ebourgebourgCCSTLMT CST-SummerVÿ€€ì€ì¿s‹}ÈÕd~V¥~Xx"G^!0‚%0~)0-W^1/‚@«¾@I@«>@oþ@ª¾@!o~@&ª>@)nþ@.©¾@1•Þ@6О@9•^@>Ð@A”Þ@FÏž@I”^@NÏ@Q“Þ@VΞ@Y“^@^Î@aº>@fôþ@i¹¾@nô~@q¹>@vóþ@y¸¾@~ó~@‚þ@†Ëž@Š~@Žò~@’-^@—^@š,Þ@ŸÞ@¢,^@§^@©Ý@¯Þ@²R¾@·^@º~@¿>>@ÂQ¾@Ç=¾@Êxž@Ï=>@ÒŸ~@×<¾@Úžþ@ß<>@âž~@ç;¾@êþ@ïbž@ò~@÷b@úœþ@ÿažAÃÞAaA Ã^A`žAÂÞA‡~AÂ^A†þA"é>A'†~A*Á^A/…þA3žA7^sCSTs  CST-Summerjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Broken_Hill0000644000175000017500000000126211564260550024767 0ustar ebourgebourgCCSTLMT CST-SummerESTWÿ€€„œ€„œ¿sˆd}³G}ÈÕd~V¥~Xx"G^!0‚%0~)0-W^1/‚@«¾@I@«>@oþ@ª¾@!o~@&ª>@)nþ@.©¾@1•Þ@6О@9•^@>Ð@A”Þ@FÏž@I”^@NÏ@Q“Þ@VΞ@Y“^@^Î@bW¾@fôþ@i¹¾@nô~@q¹>@vóþ@y¸¾@~ó~@‚þ@†Ëž@Š~@Žò~@’-^@—^@š,Þ@ŸÞ@¡Ýž@§^@©Ý@¯Þ@±Üž@·^@º~@¿>>@Âþ@Ç=¾@Ê~@Ï=>@ÒŸ~@×<¾@Úžþ@ß<>@âž~@ç;¾@êþ@ïbž@ò~@÷b@úœþ@ÿažAÃÞAaA Ã^A`žAÂÞA‡~AÂ^A†þA"é>A'†~A*Á^A/…þA3žA7^sCSTs  CST-Summerjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Currie0000644000175000017500000000123011564260550024023 0ustar ebourgebourgCLMT EST-SummerESTTÿ€€†à€†à¿t. ~TŸà~XxG@!0d%0`)/ä-W@1/d@« @I@« @oà@ª @!o`@&ª @)nà@.© @1•À@6Ѐ@9•@@>Ð@A”À@FÏ€@I”@@NÏ@Q“À@V΀@Y“@@^Î@b0@@fôà@j/À@nô`@q¹ @vóà@y¸ @~ó`@¸ @†Ë€@Š`@Žò`@’-@@—@@š,À@ŸÀ@¢,@@§@@ªz€@®¡ @²z@¶¡ @ºy€@¾  @Ây@Æ  @Êx€@Ο @ÒŸ`@ÖÆ€@Úžà@ÞÆ@âž`@æÅ€@êà@îÅ@ò`@õÿ @úœà@þë`AÃÀAêàA Ã@Aê`AÂÀAéàAÂ@Aé`A"é A&èàA*Á@A/ÀA3€s  EST-SummersESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Brisbane0000644000175000017500000000025211564260550024322 0ustar ebourgebourgCLMT EST-SummerESTÿ€€x€x¿ríŸ~V¤é~XxG@!0d%0`)/ä-W@1/d@« @I@ŸÀ@¡Ý€@§@@©Ý@¯À@±Ü€joda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Eucla0000644000175000017500000000045411564260550023632 0ustar ebourgebourgCCWSTLMT CWST-Summerÿ€€xЀxпt¦ °@ @ ~V¥4@I@ ~XxO@ @ G‹@I@ !0¯@ @ %0«@I@ )0/@ @ @&ªk@I@ @)o+@ @ @nô«@I@ @q¹k@ @ @¯Ž+@I@ @±ÜË@ @ A(K‹@I@ A*Á‹@ @ A/†+@I@ A2èk@ @ A7…«@I@ A:çë@ @ joda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Hobart0000644000175000017500000000132011564260550024011 0ustar ebourgebourgCLMT EST-SummerEST\ÿ€€Š€Š¿t.ä~TŸà~XxG@!0d%0`)/ä-W@1/díèÀñè€ö…Àùqàþ…@@q`@„À@ ˜@@« @I@« @oà@ª @!o`@&ª @)nà@.© @1•À@6Ѐ@9•@@>Ð@A”À@FÏ€@I”@@NÏ@Q“À@V΀@Y“@@^Î@b0@@fôà@j/À@nô`@q¹ @vóà@y¸ @~ó`@¸ @†Ë€@Š`@Žò`@’-@@—@@š,À@ŸÀ@¢,@@§@@ªz€@®¡ @²z@¶¡ @ºy€@¾  @Ây@Æ  @Êx€@Ο @ÒŸ`@ÖÆ€@Úžà@ÞÆ@âž`@æÅ€@êà@îÅ@ò`@õÿ @úœà@þë`AÃÀAêàA Ã@Aê`AÂÀAéàAÂ@Aé`A"é A&èàA*Á@A/ÀA3€s  EST-SummersESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Lindeman0000644000175000017500000000030611564260550024324 0ustar ebourgebourgCLMT EST-SummerESTÿ€€‹¬€‹¬¿rí¢Ô~V¤é~XxG@!0d%0`)/ä-W@1/d@« @I@ŸÀ@¡Ý€@§@@©Ý@¯À@±Ü€@·@@º`@¿> @Âàjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Perth0000644000175000017500000000027011564260550023657 0ustar ebourgebourgCWSTLMT WST-Summerÿ€€lœ€lœ¿t¦ä~V¥a~Xx|G¸!0Ü%0Ø)0\@&ª˜@)oX@nôØ@q¹˜@¯ŽX@±ÜøA(K¸A*Á¸A/†XA2è˜A7…ØA:èjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Melbourne0000644000175000017500000000123711564260550024531 0ustar ebourgebourgCLMT EST-SummerESTUÿ€€‡è€‡è¿s…~V¤é~XxG@!0d%0`)/ä-W@1/d@« @I@« @oà@ª @!o`@&ª @)nà@.© @1•À@6Ѐ@9•@@>Ð@A”À@FÏ€@I”@@NÏ@Q“À@V΀@Y“@@^Î@aº @fôà@i¹ @nô`@q¹ @vóà@y¸ @~ó`@‚à@†Ë€@Š`@ŽË@’-@@—@@š,À@ŸÀ@¢,@@§@@©Ý@¯À@±Ü€@·@@º`@¿> @Âà@Ç= @Êx€@Ï= @ÒŸ`@×< @Úžà@ß< @âž`@ç; @êà@ïb€@ò`@õÿ @úœà@ÿa€AÃÀAaA Ã@A`€AÂÀA‡`AÂ@A†àA"é A'†`A*Á@A/…àA3€A7@sESTs  EST-Summerjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Sydney0000644000175000017500000000123711564260550024054 0ustar ebourgebourgCLMT EST-SummerESTUÿ€€Ä€Ä¿s<~V¤é~XxG@!0d%0`)/ä-W@1/d@« @I@« @oà@ª @!o`@&ª @)nà@.© @1•À@6Ѐ@9•@@>Ð@A”À@FÏ€@I”@@NÏ@Q“À@V΀@Y“@@^Î@bW @fôà@i¹ @nô`@q¹ @vóà@y¸ @~ó`@‚à@†Ë€@Š`@Žò`@’-@@—@@š,À@ŸÀ@¡Ý€@§@@©Ý@¯À@±Ü€@·@@º`@¿> @Âà@Ç= @Ê`@Ï= @ÒŸ`@×< @Úžà@ß< @âž`@ç; @êà@ïb€@ò`@õÿ @úœà@ÿa€AÃÀAaA Ã@A`€AÂÀA‡`AÂ@A†àA"é A'†`A*Á@A/…àA3€A7@sESTs  EST-Summerjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Australia/Lord_Howe0000644000175000017500000000075311564260550024465 0ustar ebourgebourgCLMT LHST-SummerLHSTEST:ÿ€€•$€•$¿swÜ@Y’È@^Íâ@a¹Æ@fôÂ@i¹F@nôB@q¸Æ@vóÂ@y¸F@~óB@‚¤@†Ëb@Š$@ŽòB@’-@—"@š,„@Ÿ¢@¡ÝD@§"@©ÜÄ@¯¢@±ÜD@·"@º$@¿>@¤@Ç=‚@Ê$@Ï=@ÒŸ$@×<‚@Úž¤@ß<@âž$@ç;‚@ê¤@ïbb@ò$@õÿ‚@úœ¤@ÿabAÄA`âA ÃA`bA„A‡BAÂA†ÂA"èäA'†BA*ÁA/…ÂA3DA7"wLHSTw  LHST-Summerjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/0000755000175000017500000000000012205344143022261 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/North_Dakota/0000755000175000017500000000000012205344143024636 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/North_Dakota/New_Salem0000644000175000017500000000131611564260550026442 0ustar ebourgebourgCCSTMWTLMTMDTMPTCDTMST[ÿ€¿ÿÿ í¿ÿÿ í}LÞ22~`£42~e@ 22~h¢œ42~m? 22 &œ42ÓÀ22@BÓ¼42@FÓ@22@JÓ<42@NÒÀ22@RÒ¼42@VÒ@22@ZÒ<42@^ÑÀ22@bѼ42@fø 22@jÑ<42@nø 22@rø42@v÷ 22@z÷œ42@~÷ 22@‚÷42@†ö 22@Š€|42@Žö 22@’ü42@—22@š|42@Ÿ€22@¢~ü42@§22@ª¥Ü42@¯€22@²¥\42@·22@º¤Ü42@¿Aà22@¤\42@ÇA`22@Ê£Ü42@Ï@à22@Òʼ42@×@`22@ÚÊ<42@ß?à22@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@úÈ<42@ÿe@22Aï42AdÀ22A îœ42Ad@44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/North_Dakota/Center0000644000175000017500000000131611564260550026010 0ustar ebourgebourgCCSTMWTLMTMDTMPTCDTMST[ÿ€¿ÿÿ¡¿ÿÿ¡}LÞ22~`£42~e@ 22~h¢œ42~m? 22 &œ42ÓÀ22@BÓ¼42@FÓ@22@JÓ<42@NÒÀ22@RÒ¼42@VÒ@22@ZÒ<42@^ÑÀ22@bѼ42@fø 22@jÑ<42@nø 22@rø42@v÷ 22@z÷œ42@~÷ 22@‚÷42@†ö 22@Š€|42@Žö 22@’ü42@—22@š|42@Ÿ€22@¢~ü42@§22@ª¥Ü42@¯€22@²¥\42@·44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@úÈ64@ÿe44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Winnipeg0000644000175000017500000000170111564260551023772 0ustar ebourgebourgCCSTLMTCPTCWTCDTÿ€¿ÿÿ¤ì¿ÿÿ¤ì¿dä°”44~Qˆ64~TT,44~`ñ 64~eVd44~ú# 64~ý44 &`64ÓÀ44@BÓ€64@FÓ@44@JÓ64@NÒÀ44@RÒ€64@VÒ@44@ZÒ64@^ÑÀ44@bÑ€64@fø 44@jÑ64@nø 44@r÷à64@v÷ 44@z÷`64@~÷ 44@‚öà64@†ö 44@Š€@64@Žö 44@’À64@—44@š@64@Ÿ€44@¢~À64@§44@ª¥ 64@¯€44@²¥ 64@·44@º¤ 64@¿Aà44@¤ 64@ÇA`44@Ê£ 64@Ï@à44@ÒÊ€64@×@`44@ÚÊ64@ß?à44@âÉ€64@ç?`44@êÉ64@ïf@44@òÈ€64@÷eÀ44@úÈ64@ÿe@44Aîà64AdÀ44A î`64Ad@44Aíà64A‹ 44Aí`64AŠ 44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Cancun0000644000175000017500000000030511564260551023420 0ustar ebourgebourgCCSTLMTEDTCDTESTÿ€¿ÿÿ®¨¿ÿÿ®¨~~Çè44@`(66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@åfh64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@ûŒà64@þÇ„44Aîà64Ad„444wCDTw ÿCSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Indiana/0000755000175000017500000000000012205344143023624 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Indiana/Petersburg0000644000175000017500000000075611564260551025710 0ustar ebourgebourgCCSTLMTCPTEDTESTCWTCDT;ÿ€¿ÿÿ®-¿ÿÿ®-}LÝØ44~`¢à64~e?ä44~h¢`64~m?d44 &`64Ó„66A"ìà64A'‰ä44A*v@64A/°Ä66A2u„86A7°666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Indiana/Vincennes0000644000175000017500000000060511564260551025507 0ustar ebourgebourgCCSTLMTCPTEDTESTCWTCDT,ÿ€¿ÿÿ­ñ¿ÿÿ­ñ}LÝØ44~`¢à64~e?ä44~h¢`64~m?d44 &`64Ó„44@BÓ€64@FÓ44@JÓ64@NÒ„44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D66A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Indiana/Tell_City0000644000175000017500000000056711564260551025456 0ustar ebourgebourgCCSTLMTCPTEDTESTCWTCDT*ÿ€¿ÿÿ®©¿ÿÿ®©}LÝØ44~`¢à64~e?ä44~h¢`64~m?d44 &`64/°:8@A€Ô88@F4Ð:8@J4T88@N9ð:8@R?88@VD°:8@ZD488@^IÐ:8@bIT88@fNð:8@jNt88@nT:8@rY488@v^Ð:8@z^T88@~cð:8@‚ct88@†i:8@Šh”88@Žn0:8@’sT88@–xð:8@šxt88@žô0:8@¢}”88@¦ƒ0:8@ª‚´88@®¤p:8@±ß88@¶©:8@ºŒô88@¾˜0:8@ÁÞ88@ÆP:8@ÉÝ”88@΢p:8@Ñù488@ÖÉP:8@ÙÜ”88@ÞÈÐ:8@ât88@æÈP:8@ê*T88@îÇÐ:8@ò)Ô88@öÇP:8@ú)T88@þî0:8Aí´88A(Ð:8A í488AO°:8Aì´88A;p:8Av88A:ð:8A"u”88A':p:8A*u88A/aP:8A2t”88A7`Ð:8A:t88A?`P:8AC8t88AG:88w PYSTwPYTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Ojinaga0000644000175000017500000000051211564260551023561 0ustar ebourgebourgCCSTLMTMDTCDTMST%ÿ€¿ÿÿž¿ÿÿž~~È$22~ªpÈ44~Åøè22~É©è44~Íè22~Ñ„44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@û42@þÇÀ22Aï42AdÀ22A îœ42Ad@22Aî42A‹ 22Aíœ42AŠ 22A"í42A'Š 22A*ìœ42A/‰ 22A3|42A7‰ 22A;ü42A?ˆ 22ABœ\42AGÖà222wMDTw MSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Porto_Velho0000644000175000017500000000037011564260551024453 0ustar ebourgebourgCLMTAMTAMSTÿ€¿ÿÿÄ¿ÿÿÄ¿–ª‚è88~ÍD:8~Ñ”88~Õp:8~Ù ´88^Ïð:8aÌð88fÕ:8i}t88nÚ0:8qˆ488väð:8xÞô88ÏU:8Ñ(488ØŠp:8ÙÖ88ß8p:8á2t88æ”Ð:8é7”88î™ð:8ñBT88@ð:8@‚Ô88@†ð:8@‰eÔ88@Žõ0:8@‘C”88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Boa_Vista0000644000175000017500000000042411564260551024062 0ustar ebourgebourgCLMTAMTAMST"ÿ€¿ÿÿÇ ¿ÿÿÇ ¿–ªà88~ÍD:8~Ñ”88~Õp:8~Ù ´88^Ïð:8aÌð88fÕ:8i}t88nÚ0:8qˆ488väð:8xÞô88ÏU:8Ñ(488ØŠp:8ÙÖ88ß8p:8á2t88æ”Ð:8é7”88î™ð:8ñBT88@ð:8@‚Ô88@†ð:8@‰eÔ88@Žõ0:8@‘C”88@îÇÐ:8@òt88@öî°:8@÷Ô88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Merida0000644000175000017500000000030011564260551023405 0ustar ebourgebourgCCSTLMTCDTESTÿ€¿ÿÿ«ü¿ÿÿ«ü~~Çè44@`(66@g«ì44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@ûŒà64@þÇ„44Aîà64Ad„444wCDTw ÿCSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/St_Vincent0000644000175000017500000000010311564260551024261 0ustar ebourgebourgPLMTKMTASTÿ€¿ÿÿƘ¿ÿÿƘ¿i‡è¿ÿÿƘ¿ÿÿƘ¿’æÇè88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Detroit0000644000175000017500000000117511564260551023631 0ustar ebourgebourgCCSTEPTLMTEWTEDTESTPÿ€¿ÿÿ²%¿ÿÿ²%¿…½"[44~I‹66 &$86ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Paramaribo0000644000175000017500000000014711564260551024272 0ustar ebourgebourgPNEGTPMTLMTSRTÿ€¿ÿÿÌH¿ÿÿÌH¿‘ޏ¿ÿÿÌ<¿ÿÿÌ<¿¾*KÄ¿ÿÿÌL¿ÿÿÌL¿Òb,´99@/8ò99@v^²::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Halifax0000644000175000017500000000234711564260551023575 0ustar ebourgebourgCAWTLMTAPTASTADT©ÿ€¿ÿÿÄ`¿ÿÿÄ`¿€ñ« 88~PP:8~T¢t88~`ñ(:8~eUì88~q0:8~tô88~yp:8~|/t88~dÐ:8~„4”88~‰‹°:8~Œ488~‘‹0:8~”|´88~™Š°:8~œÊô88~¡Øð:8~¤{´88~©‰°:8~¬Éô88~±×ð:8~´u88~¹×p:8~¼Xt88~ÁÖð:8~Ä¡88~ÉÖp:8~ÌïT88~Ñ®:8~ÔîÔ88~Ù®:8~Ý´88~â#°:8~äÀÔ88~êqð:8~í´88~òw:8~ôÅt88~ùÓp:8~ý´88Òð:8488 oð:8 ´88ùP:89”88øÐ:8988 %è:8Ó 88@BÓ:8@FÒŒ88@JÒˆ:8@NÒ 88@RÒ:8@VÑŒ88@Zш:8@^Ñ 88@bÑ:8@f÷ì88@jЈ:8@n÷l88@r÷h:8@vöì88@zöè:8@~öl88@‚öh:8@†õì88@ŠÈ:8@Žõl88@’H:8@—L88@š~È:8@ŸÌ88@¢~H:8@§L88@ª¥(:8@¯Ì88@²¤¨:8@·L88@º¤(:8@¿A,88@£¨:8@Ç@¬88@Ê£(:8@Ï@,88@ÒÊ:8@×?¬88@ÚɈ:8@ß?,88@âÉ:8@ç>¬88@êȈ:8@ïeŒ88@òÈ:8@÷e 88@úLj:8@ÿdŒ88Aîh:8Ad 88A íè:8AcŒ88Aíh:8AŠl88Aìè:8A‰ì88A"ìh:8A'‰l88A*uÈ:8A/°L888wADTw ASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Iqaluit0000644000175000017500000000100111564260551023613 0ustar ebourgebourgCCSTEPTEDDTEWTzzzEDTCDTEST>ÿ€#ñ 86è66@êÈÄ86@ïf44@òÈ€64@÷e„66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Grand_Turk0000644000175000017500000000076711564260551024265 0ustar ebourgebourgCLMTKMTEDTEST=ÿ€¿ÿÿ½P¿ÿÿ½P¿i‡0¿ÿÿ¸¿ÿÿ¸¿“µ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Bogota0000644000175000017500000000012711564260551023426 0ustar ebourgebourgCLMTCOTCOSTBMTÿ€¿ÿÿºŒ¿ÿÿºŒ¿^œ4ô¿ÿÿºŒ¿ÿÿºŒ¿˜XUt66@³Aì86@º£°66joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Costa_Rica0000644000175000017500000000020111564260551024213 0ustar ebourgebourgCCSTLMTSJMTCDT ÿ€¿ÿÿ±,¿ÿÿ±,¿i‡*T¿ÿÿ±,¿ÿÿ±,¿£èT44@Ip(64@K—,44@Qo¨64@S–¬44@¨îh64@¬ƒ 44@°íè64@².L44joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Belize0000644000175000017500000000066311564260551023432 0ustar ebourgebourgCCSTLMTCDTCHDT8ÿ€¿ÿÿ­P¿ÿÿ­P¿“^Ù°44~dɈ54~gŽ*44~lÉ54~oµ 44~tȈ54~w´Š44~|È54~´ 44~„îè54~‡³Š44~Œîh54~³ 44~”íè54~—Ùê44~œíh54~ŸÙj44~¤ìè54~§Øê44~¬ìh54~¯Øj44~µH54~·×ê44~½È54~¿×j44~ÅH54~ÇþJ44~ÍÈ54~ÏýÊ44~ÕH54~×ýJ44~Ý8(54~ßüÊ44~å7¨54~çüJ44~í7(54~ïûÊ44~õ6¨54~ø"ª44~ý6(54"*445¨54!ª44 \ˆ54!*44\54 ª44[ˆ54 GŠ44%[54(G 44@ƒ¨64@ ö¬44@h(64@i@ì44joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Recife0000644000175000017500000000047611564260551023417 0ustar ebourgebourgCBRTLMTBRST(ÿ€¿ÿÿßH¿ÿÿßH¿–ªg¸::~Í<:~ÑX::~Õ4<:~Ù x::^Ï´<:aÌ´::fÔÔ<:i}8::nÙô<:q‡ø::vä´<:xÞ¸::ÏUT<:Ñ'ø::ØŠ4<:ÙÕØ::ß84<:á28::æ””<:é7X::î™´<:ñB::@´<:@‚˜::@†ïÔ<:@‰e˜::@Žôô<:@‘CX::@–Í<:@™x::@žÌ”<:@¡i¸::@îÇ”<:@ò8::@öît<:@÷˜::@ÿT<:AÙØ::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Santarem0000644000175000017500000000040411564260551023763 0ustar ebourgebourgCBRTLMTAMTAMSTÿ€¿ÿÿ̸¿ÿÿ̸¿–ªzH88~ÍD:8~Ñ”88~Õp:8~Ù ´88^Ïð:8aÌð88fÕ:8i}t88nÚ0:8qˆ488väð:8xÞô88ÏU:8Ñ(488ØŠp:8ÙÖ88ß8p:8á2t88æ”Ð:8é7”88î™ð:8ñBT88@ð:8@‚Ô88@†ð:8@‰eÔ88@Žõ0:8@‘C”88A4ΰ::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Vancouver0000644000175000017500000000173511564260551024171 0ustar ebourgebourgCLMTPWTPDTPSTPPTƒÿ€¿ÿÿŒ”¿ÿÿŒ”¿^=vì00~`ò20~eVÜ00 &Ø20Óü00@BÓø20@FÓ|00@JÓx20@NÒü00@RÒø20@VÒ|00@ZÒx20@^Ñü00@bÑø20@føÜ00@jÑx20@nø\00@røX20@v÷Ü00@z÷Ø20@~÷\00@‚÷X20@†öÜ00@Š€¸20@Žö\00@’€820@—<00@š¸20@Ÿ¼00@¢820@§<00@ª¦20@¯¼00@²¥˜20@·<00@º¥20@¿B00@¤˜20@ÇAœ00@ʤ20@ÏA00@ÒÊø20@×@œ00@ÚÊx20@ß@00@âÉø20@ç?œ00@êÉx20@ïf|00@òÈø20@÷eü00@úÈx20@ÿe|00AïX20Adü00A îØ20Ad|00AîX20A‹\00AíØ20AŠÜ00A"íX20A'Š\00A*v¸20A/±<000wPDTw PSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Dawson0000644000175000017500000000106411564260551023447 0ustar ebourgebourgCLMTPDTPSTYDDTYPTYSTYDTYWTDÿ€¿ÿÿ}L¿ÿÿ}L¿}†Ž´..~`òT0.~e@˜..~iÞ0.~ma`.. '0.Ô8..@BÔ40.@FÓ¸..@JÓ´0.@NÓ8..@RÓ40.@VÒ¸..@ZÒ´0.@^Ò8..@bÒ40.@fù..@jÑ´0.@nø˜..@o¦¼..@rø”0.@vø..@zø0.@~÷˜..@‚÷”0.@†÷..@Š€ô0.@Žö˜..@’€t0.@—x..@šô0.@Ÿø..@¢t0.@§x..@ª¦T0.@¯ø..@²¥Ô0.@·x..@º¥T0.@¿BX..@¤Ô0.@ÇAØ..@ʤT0.@ÏAX..@ÒË40.@×@Ø..@ÚÊ´0.@ß@X..@âÊ40.@ç?Ø..@êÉ´0.@ïf¸..@òÉ40.@÷f8..@úÈ´0.@ÿe¸..Aï”0.Ae8..A ï0.Ad¸..Aî”0.A‹˜..Aî0.A‹..A"í”0.A'Š˜..A*vô0.A/±x...wAKDTw AKSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Tijuana0000644000175000017500000000135411564260551023611 0ustar ebourgebourgCLMTPWTPDTPSTMSTPPT`ÿ€¿ÿÿ’L¿ÿÿ’L~~È`22~ŽÒd00~ªq22~Åù$00~Èü20~Ìû„00!Æ 20K¤00Q…À20WÃ00‚20…}00Š˜20|œ00’Ax20•£|00š@ø20¢ü00¢@x20¥¢|00ª?ø20­¡ü00²?x20µ¡|00@2­˜20@6Ô|00@:­20@>Óü00@BÓø20@FÓ|00@JÓx20@NÒü00@RÒø20@VÒ|00@ZÒx20@^Ñü00@bÑø20@føÜ00@jÑx20@nø\00@røX20@v÷Ü00@z÷Ø20@~÷\00@‚÷X20@†öÜ00@Š€¸20@Žö\00@’€820@—<00@š¸20@Ÿ¼00@¢820@§<00@ª¦20@¯¼00@²¥˜20@·<00@º¥20@¿B00@¤˜20@ÇAœ00@ʤ20@ÏA00@ÒÊø20@×@œ00@ÚÊx20@ß@00@âÉø20@ç?œ00@êÉx20@ïf|00@òÈø20@÷eü00@úÈx20@ÿe|00AïX20Adü00A îØ20Ad|00AîX20A‹\00AíØ20AŠÜ00A"íX20A'Š\00A*ìØ20A/‰Ü00A3¸20A7‰\00A;820A?ˆÜ00ABœ˜20AG×000wPDTw PSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Menominee0000644000175000017500000000123111564260551024124 0ustar ebourgebourgCCSTLMTCPTESTCWTCDTTÿ€¿ÿÿ­Ý¿ÿÿ­Ý¿awIc44~`¢à64~e?ä44~h¢`64~m?d44 &`64Ó„44@BÓ€64@FÓ44@JÓ64@NÒ„44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D44@²¥ 64@·Ä44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@úÈ64@ÿe44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Moncton0000644000175000017500000000213111564260551023625 0ustar ebourgebourgCAWTLMTAPTASTESTADT”ÿ€¿ÿÿÃD¿ÿÿÃD¿^í¼66}áå,88~`ñ(:8~eUì88~ÚšŒ:8~Üš088~âš :8~ä™°88~Ꙍ:8~ì™088~ò™ :8~ô˜°88~ú˜Œ:8~ü˜088˜ :8—°88 jŒ:8 °88HL:8088ù :8.88 %è:8Œ88²>ˆ:8¶el88ºeh:8¾dì88Âdè:8Ædl88Êdh:8Îcì88Òcè:8Öcl88Úch:8ÞŠL88âbè:8æ‰Ì88ê‰È:8î‰L88ò‰H:8öˆÌ88úˆÈ:8þˆL88@ˆH:8@‡Ì88@ ‡È:8@®¬88@®¨:8@®,88@"­¨:8@&­,88@*­(:8@.¬¬88@2¬¨:8@6ÓŒ88@:¬(:8@>Ó 88@BÓ:8@FÒŒ88@JÒˆ:8@NÒ 88@RÒ:8@VÑŒ88@Zш:8@^Ñ 88@bÑ:8@f÷ì88@jЈ:8@n÷l88@r÷h:8@vöì88@zöè:8@~öl88@‚öh:8@†õì88@ŠÈ:8@Žõl88@’H:8@—L88@š~È:8@ŸÌ88@¢~H:8@§L88@ª¥(:8@¯Ì88@²¤¨:8@·L88@º£±:8@¿@µ88@£1:8@Ç@588@Ê¢±:8@Ï?µ88@ÒÉ‘:8@×?588@ÚÉ:8@ß>µ88@âÈ‘:8@ç>588@êÈ:8@ïe88@òÇ‘:8@÷d•88@úÇ:8@ÿd88Aíñ:8Ac•88A íq:8Ac88Aìñ:8A‰õ88Aìq:8A‰u88A"ëñ:8A'ˆõ88A*uÈ:8A/°L888wADTw ASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Havana0000644000175000017500000000141011564260551023405 0ustar ebourgebourgCCSTLMTCDTHMTdÿ€¿ÿÿ²È¿ÿÿ²È¿i‡(¸¿ÿÿ²À¿ÿÿ²À¿¬b€66~²u¬86~µ#°66— 86–°66–Œ86½66"½l86$½66:»ì86<»66B»l86D»66Û3L86ÝÛ°66ã'Œ86åì66ê Ì86íup66ò:L86õtð66úˆŒ86þˆ66@ˆ 86@‡66@ ‡Œ86@®p66@®l86@7Ð66@­ì86@<ð66@"­l86@&B66@*¬ì86@.¬p66@2¬l86@6ÓP66@:«ì86@>ÒÐ66@Bú,86@F\066@Iæ 86@Nƒ66@QåŒ86@V‚66@[ 86@^‚66@cŒ86@f66@k 86@n66@sŒ86@v§ð66@{ 86@~§p66@‚ ì86@†¦ð66@Š l86@ަp66@’0L86@–¥ð66@š/Ì86@ž¥p66@¢~ 86@¦ÌP66@ª¤ì86@®Ì 66@²¤l86@¶ËŒ66@º£ì86@¾Ë 66@£l86@ÆÊŒ66@Ê¢ì86@ÎÊ 66@ÒÉÌ86@ÖÉŒ66@ÚÉL86@Þðl66@â¡l86@ç>¬66@ê ì86@ïeŒ66@òÇÌ86@÷e 66@úÇL86@ÿdŒ66Aî,86Ad 66A í¬86AcŒ66Aí,86A'‰l66A*uŒ86A/ˆì66A2œl86A7ˆl66A:tŒ866s ÿCSTsCDTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Cuiaba0000644000175000017500000000170011564260551023375 0ustar ebourgebourgCLMTAMTAMST€ÿ€¿ÿÿËl¿ÿÿËl¿–ª{”88~ÍD:8~Ñ”88~Õp:8~Ù ´88^Ïð:8aÌð88fÕ:8i}t88nÚ0:8qˆ488väð:8xÞô88ÏU:8Ñ(488ØŠp:8ÙÖ88ß8p:8á2t88æ”Ð:8é7”88î™ð:8ñBT88@ð:8@‚Ô88@†ð:8@‰eÔ88@Žõ0:8@‘C”88@–ÍP:8@™´88@žÌÐ:8@¡iô88@¦ó°:8@©Ô88@®ó0:8@±hô88@·:8@¹A88@¾ò0:8@Á¶´88@Æñ°:8@ɶ488@Îñ0:8@ÑŽT88@ÖÉP:8@Ùµ488@ÞÎp:8@ât88@æï°:8@éÛ”88@îÇÐ:8@òt88@öî°:8@ùÚ”88@ÿ:8AÚ88A‹0:8A Ù”88A•p:8Aÿô88A:ð:8A!ÿt88A'°:8A*&T88A/9ð:8A1þt88A7`Ð:8A9ýô88A?`P:8AB$Ô88AG_Ð:8AJ$T88AO_P:8ARK488AW†0:8AZ#T88A_…°:8Ab"Ô88Ag…0:8AjI´88Ao„°:8ArI488Aw„0:8AzH´88Aƒ°:8A‚H488A‡ª:8AŠG´88Aª:8A’G488A—©:8Ašn88AŸ©:8A¢m”88A§¨:8Aª”t88A¯¨:8A²l”88A·Îð:8Aºl88A¿Îp:8AÂ’ô88AÇÍð:8AÊ’t88AÏÍp:8AÒ‘ô88A×Ìð:8AÚ‘t88AßóÐ:8Aâô88AçóP:8Aêt88AïòÐ:8Aòô88A÷òP:8Aú¶Ô88AÿñÐ:8BÝ´88BñP:8B µÔ88B0:8BµT88B°:8BÜ488B 0:8B"Û´888w AMSTwAMTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Cayenne0000644000175000017500000000006511564260551023576 0ustar ebourgebourgPLMTGFTÿ€¿ÿÿÎð¿ÿÿÎð¿‘ô+88íë::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/0000755000175000017500000000000012205344143024171 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Rio_Gallegos0000644000175000017500000000075411564260551026477 0ustar ebourgebourgCLMTARSTCMTARTWART>ÿ€¿ÿÿ¿¿ÿÿ¿¿rœ²d¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©ßX::@®òô<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A2ô88Až::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/San_Luis0000644000175000017500000000077211564260551025646 0ustar ebourgebourgCLMTARSTCMTARTWARSTWART?ÿ€¿ÿÿÁÌ¿ÿÿÁÌ¿rœ¯´¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¢88@¦Ñð:8@©ÔT88@«Ú::@îÇ”:8@ò”::A-T88Abð::A0êÔ<:A1fX:8A2t”88A79p:8A:t88A?8ð:8joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/La_Rioja0000644000175000017500000000076311564260551025611 0ustar ebourgebourgCLMTARSTCMTARTWART?ÿ€¿ÿÿÁT¿ÿÿÁT¿rœ°,¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©Ô88@«Mp::@®òô<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A2ô88Až::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/San_Juan0000644000175000017500000000076311564260551025627 0ustar ebourgebourgCLMTARSTCMTARTWART?ÿ€¿ÿÿ¿Ä¿ÿÿ¿Ä¿rœ±¼¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©Ô88@«Mp::@®òô<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A-T88Abð::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Cordoba0000644000175000017500000000075411564260551025502 0ustar ebourgebourgCLMTARSTCMTARTWART>ÿ€¿ÿÿÃпÿÿÃпrœ­°¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©ßX88@®ó0<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A0êÔ<:A2›¸::A7`”<:A:›8::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Salta0000644000175000017500000000073611564260551025175 0ustar ebourgebourgCLMTARSTCMTARTWART<ÿ€¿ÿÿ¬¿ÿÿ¬¿rœ®Ô¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©ßX88@®ó0<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Mendoza0000644000175000017500000000076311564260551025526 0ustar ebourgebourgCLMTARSTCMTARTWARSTWART>ÿ€¿ÿÿ¿|¿ÿÿ¿|¿rœ²¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ88@¦Ñð:8@©ÔT88@®×:8@±ß88@¶ò°<:@º¸::@îÇÐ:8@ò”::AT88AÅP::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Buenos_Aires0000644000175000017500000000074611564260551026510 0ustar ebourgebourgCLMTARSTCMTART>ÿ€¿ÿÿÉ4¿ÿÿÉ4¿rœ¨L¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©ßX::@®òô<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A0êÔ<:A2›¸::A7`”<:A:›8::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Jujuy0000644000175000017500000000074511564260551025237 0ustar ebourgebourgCLMTARSTCMTARTWARSTWART<ÿ€¿ÿÿÂÈ¿ÿÿÂÈ¿rœ®¸¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ88@§:8@ª.T88@®¤p<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Tucuman0000644000175000017500000000077211564260551025545 0ustar ebourgebourgCLMTARSTCMTARTWART@ÿ€¿ÿÿÂÜ¿ÿÿÂÜ¿rœ®¤¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©ßX88@®ó0<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A2ô88Av°::A0êÔ<:A2›¸::A7`”<:A:›8::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Ushuaia0000644000175000017500000000075411564260551025530 0ustar ebourgebourgCLMTARSTCMTARTWART>ÿ€¿ÿÿ¿ø¿ÿÿ¿ø¿rœ±ˆ¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©ßX::@®òô<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A'´88Až::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Argentina/Catamarca0000644000175000017500000000075411564260551026005 0ustar ebourgebourgCLMTARSTCMTARTWART>ÿ€¿ÿÿÂT¿ÿÿÂT¿rœ¯,¿ÿÿÃпÿÿÃп¢’088~ÆRp:8~ÈúÔ88~ÍO0:8~ÐW488~Õ¹:8~Ø\T88~ݾ°:8~àat88~åÃÐ:8~èf”88~íÈð:8~ðqT88~õÓ°:8~øvt88~ýØÐ:8{”88Ýð:8€´88 ã:8‹t889ð:8äÔ88“P:8+÷t88-:8@¯Ô88EcÐ:8ÍÑ488ÏwP:8Ñ(488Ö*ð:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@—ÏÔ<:@™àX::@žÌ”<:@¡ßØ::@¦ót<:@©ßX88@®ó0<:@±ÞØ::@¶òt<:@º¸::@îÇÐ:8@ò”::A2ô88Až::A0êÔ<:A2›¸::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Martinique0000644000175000017500000000012711564260551024331 0ustar ebourgebourgCLMTASTFFMTADTÿ€¿ÿÿƼ¿ÿÿƼ¿i‡Ä¿ÿÿƼ¿ÿÿƼ¿‘£ÈD88@R[p:8@V3”88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Scoresbysund0000644000175000017500000000050711564260550024677 0ustar ebourgebourgCLMTEGTCGTEGSTCGST$ÿ€¿ÿÿëh¿ÿÿëh¿›€L<<@R[p><@V3Ð<<@Z3>@^2œ>>@b2\>@f2>>@j1Ü>@n1œ>>@r1\>@vX|>>@zX<>@~Wü>>@‚W¼>@†W|>>@ŠW<>@ŽVü>>@’V¼>@–V|>>@šV<>@žUü>>@¢U¼>@¦|Ü>>@ª|œ>@®|\>>@²|>@¶{Ü>>@º{œ>@¾{\>>@Â{>@ÆzÜ>>@Êzœ>@Îz\>>@Ò¡|>@×>¼>>>uÿEGSTu ÿEGTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Thule0000644000175000017500000000047211564260550023276 0ustar ebourgebourgCLMTASTADT$ÿ€¿ÿÿ¿„¿ÿÿ¿„¿›€wü88@ª}È:8@®}L88@²}H:8@¶|Ì88@º¤(:8@¿A,88@£¨:8@Ç@¬88@Ê£(:8@Ï@,88@ÒÊ:8@×?¬88@ÚɈ:8@ß?,88@âÉ:8@ç>¬88@êȈ:8@ïeŒ88@òÈ:8@÷e 88@úLj:8@ÿdŒ88Aîh:8Ad 88A íè:8AcŒ88Aíh:8AŠl88Aìè:8A‰ì88A"ìh:8A'‰l88A*uÈ:8A/°L888wADTw ASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Cayman0000644000175000017500000000010311564260551023415 0ustar ebourgebourgPLMTKMTESTÿ€¿ÿÿ³´¿ÿÿ³´¿i‡'Ì¿ÿÿ¸¿ÿÿ¸¿“µ66joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Guyana0000644000175000017500000000012511564260551023435 0ustar ebourgebourgPLMTGYTGBGTÿ€¿ÿÿÉx¿ÿÿÉx¿˜Ùyˆÿÿÿÿãaÿÿÿÿ@,Ã::@¨ˆt88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Montserrat0000644000175000017500000000005611564260551024352 0ustar ebourgebourgPLMTASTÿ€¿ÿÿŬ¿ÿÿŬ¿‘ô588joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Guatemala0000644000175000017500000000015311564260551024112 0ustar ebourgebourgCCSTLMTCDT ÿ€¿ÿÿ«$¿ÿÿ«$¿ŸêÜ44@Kh64@!K 44@khh64@n!¬44@ªPÈ64@®Œ44A#‰è64A&ëì44joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Thunder_Bay0000644000175000017500000000117211564260551024420 0ustar ebourgebourgCCSTEPTLMTEWTEDTESTPÿ€ÿþ›ÿþ›}¦Å44~yˆ66 &$86ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Inuvik0000644000175000017500000000075311564260551023465 0ustar ebourgebourgCPDDTMDTPSTzzzMST=ÿ€w’`00Úcà40Þ‹00@JÓx22@RÒ¼42@VÒ@22@ZÒ<42@^ÑÀ22@bѼ42@fø 22@jÑ<42@nø 22@rø42@v÷ 22@z÷œ42@~÷ 22@‚÷42@†ö 22@Š€|42@Žö 22@’ü42@—22@š|42@Ÿ€22@¢~ü42@§22@ª¥Ü42@¯€22@²¥\42@·22@º¤Ü42@¿Aà22@¤\42@ÇA`22@Ê£Ü42@Ï@à22@Òʼ42@×@`22@ÚÊ<42@ß?à22@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@úÈ<42@ÿe@22Aï42AdÀ22A îœ42Ad@22Aî42A‹ 22Aíœ42AŠ 22A"í42A'Š 22A*v|42A/±222wMDTw MSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Aruba0000644000175000017500000000007211564260551023244 0ustar ebourgebourgPLMTASTANTÿ€¿ÿÿ¾H¿ÿÿ¾H¿“/877×áÎ88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Montevideo0000644000175000017500000000111511564260551024322 0ustar ebourgebourgCUYTLMTUYSTMMTUYHSTHÿ€¿ÿÿËT¿ÿÿËT¿y}ú,¿ÿÿËT¿ÿÿËT¿¢’‡¬99~ŒÑ²:9~ÑT99~”ÖÒ:9~˜Öt99~œÛò:9~ Û”99~Ý­²:9~áÔ99~å­2:9~éT99~í¬²:9~ñÔ99~õÓ’:9~ùT99~ýÓ:9 Ô99Ò’:9 T99 Ò:94499Ñ’:93´99íR:9IÔ99&éÒ<:(ã¸::ªÛÔ<:®³ø::°”<:±)ø::Ùì”<:Ýĸ::áì<:掸::éë”<:î“Ø::ó+´;:÷R¶::û0Ô;:ÿWÖ::@5ô;:@\ö::@Œ4<:@˜::@!™T;:@'ç–<:@6*::@?—t<:@B.ø::@N9´<:@Rç˜::@4<:@’ Ø::@˜<:@š¸::@ŸT<:@¡ßØ::@¦ót<:@©ßX::@¯T<:@±ÞØ::@¶òt<:@¹ÞX::A´<:AÅ::AÌ<:A"uÐ::A&ëì<:A*uP:::w UYSTwUYTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/St_Lucia0000644000175000017500000000007511564260551023720 0ustar ebourgebourgPLMTCMTASTÿ€ÿÿ ÿÿ }}üÿÿ ÿÿ ~.ƒT88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Goose_Bay0000644000175000017500000000216011564260551024061 0ustar ebourgebourgCNSTNPTNDTLMTASTNWTADDTADT‘ÿ€¿ÿÿÇ\¿ÿÿÇ\¿^=<$¿ÿÿΔ¿ÿÿΔ¿ž¸~Œ¿ÿÿܤ¿ÿÿΔ¿ŸÀ|¿ÿÿΔ¿ÿÿΔ¿¾žMl99~òÒ;9~õ;v99~úR;9~ý:ö99ÿÒ;9:v99 &²;9 9ö99&2;9`Ö99%²;9`V99"%2;9ê;9­ î99²>j;9¶eN99ºeJ;9¾dÎ99ÂdÊ;9ÆdN99ÊdJ;9ÎcÎ99ÒcÊ;9ÖcN99ÚcJ;9ÞŠ.99áÊ88âbè:8æ‰Ì88ê‰È:8î‰L88ò‰H:8öˆÌ88úˆÈ:8þˆL88@ˆH:8@‡Ì88@ ‡È:8@®¬88@®¨:8@®,88@®(:8@­¬88@"­¨:8@&­,88@*­(:8@.¬¬88@2¬¨:8@6ÓŒ88@:¬(:8@>Ó 88@BÓ:8@FÒŒ88@JÒˆ:8@NÒ 88@RÒ:8@VÑŒ88@Zш:8@^Ñ 88@bÑ:8@f÷ì88@jЈ:8@n÷l88@r÷h:8@vöì88@zöè:8@~öl88@‚öh:8@†õì88@ŠQ:8@Žôõ88@’~Ñ<8@—™88@š~Q:8@ŸU88@¢}Ñ:8@§Õ88@ª¤±:8@¯U88@²¤1:8@·Õ88@º£±:8@¿@µ88@£1:8@Ç@588@Ê¢±:8@Ï?µ88@ÒÉ‘:8@×?588@ÚÉ:8@ß>µ88@âÈ‘:8@ç>588@êÈ:8@ïe88@òÇ‘:8@÷d•88@úÇ:8@ÿd88Aíñ:8Ac•88A íq:8Ac88Aìñ:8A‰õ88Aìq:8A‰u88A"ëñ:8A'ˆõ88A*uQ:8A/¯Õ888w@ADTw @ASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Eirunepe0000644000175000017500000000042211564260551023765 0ustar ebourgebourgCACSTACTLMTAMT!ÿ€¿ÿÿ¾€¿ÿÿ¾€¿–ªˆ€66~Í€86~ÑÐ66~Õ¬86~Ù ð66^Ð,86aÍ,66fÕL86i}°66nÚl86qˆp66vå,86xß066ÏUÌ86Ñ(p66ØŠ¬86ÙÖP66ß8¬86á2°66æ• 86é7Ð66îš,86ñB66@,86@‚66@†ðL86@‰f66@Žõl86@‘CÐ66@¾òl86@Á¶ð66A4Îì88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Campo_Grande0000644000175000017500000000171611564260551024537 0ustar ebourgebourgCLMTAMTAMST‚ÿ€¿ÿÿÌÌ¿ÿÿÌÌ¿–ªz488~ÍD:8~Ñ”88~Õp:8~Ù ´88^Ïð:8aÌð88fÕ:8i}t88nÚ0:8qˆ488väð:8xÞô88ÏU:8Ñ(488ØŠp:8ÙÖ88ß8p:8á2t88æ”Ð:8é7”88î™ð:8ñBT88@ð:8@‚Ô88@†ð:8@‰eÔ88@Žõ0:8@‘C”88@–ÍP:8@™´88@žÌÐ:8@¡iô88@¦ó°:8@©Ô88@®ó0:8@±hô88@·:8@¹A88@¾ò0:8@Á¶´88@Æñ°:8@ɶ488@Îñ0:8@ÑŽT88@ÖÉP:8@Ùµ488@ÞÎp:8@ât88@æï°:8@éÛ”88@îÇÐ:8@òt88@öî°:8@ùÚ”88@ÿ:8AÚ88A‹0:8A Ù”88A;ð:8AÙ88A•p:8Aÿô88A:ð:8A!ÿt88A'°:8A*&T88A/9ð:8A1þt88A7`Ð:8A9ýô88A?`P:8AB$Ô88AG_Ð:8AJ$T88AO_P:8ARK488AW†0:8AZ#T88A_…°:8Ab"Ô88Ag…0:8AjI´88Ao„°:8ArI488Aw„0:8AzH´88Aƒ°:8A‚H488A‡ª:8AŠG´88Aª:8A’G488A—©:8Ašn88AŸ©:8A¢m”88A§¨:8Aª”t88A¯¨:8A²l”88A·Îð:8Aºl88A¿Îp:8AÂ’ô88AÇÍð:8AÊ’t88AÏÍp:8AÒ‘ô88A×Ìð:8AÚ‘t88AßóÐ:8Aâô88AçóP:8Aêt88AïòÐ:8Aòô88A÷òP:8Aú¶Ô88AÿñÐ:8BÝ´88BñP:8B µÔ88B0:8BµT88B°:8BÜ488B 0:8B"Û´888w AMSTwAMTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Fortaleza0000644000175000017500000000047311564260551024146 0ustar ebourgebourgCBRTLMTBRST(ÿ€ÿÿfÿÿf~>’Ú::~Í<:~ÑX::~Õ4<:~Ù x::^Ï´<:aÌ´::fÔÔ<:i}8::nÙô<:q‡ø::vä´<:xÞ¸::ÏUT<:Ñ'ø::ØŠ4<:ÙÕØ::ß84<:á28::æ””<:é7X::î™´<:ñB::@´<:@‚˜::@†ïÔ<:@‰e˜::@Žôô<:@‘CX::@–Í<:@™x::@žÌ”<:@¡i¸::@îÇ”<:@ò8::@öît<:@÷<ø::@ÿT<:AÙØ::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Araguaina0000644000175000017500000000060411564260551024103 0ustar ebourgebourgCBRTLMTBRST2ÿ€¿ÿÿÒпÿÿÒп–ªt0::~Í<:~ÑX::~Õ4<:~Ù x::^Ï´<:aÌ´::fÔÔ<:i}8::nÙô<:q‡ø::vä´<:xÞ¸::ÏUT<:Ñ'ø::ØŠ4<:ÙÕØ::ß84<:á28::æ””<:é7X::î™´<:ñB::@´<:@‚˜::@†ïÔ<:@‰e˜::@Žôô<:@‘CX::@–Í<:@™x::@žÌ”<:@¡i¸::@Îðô<:@ÑŽ::@ÖÉ<:@Ù´ø::@ÞÎ4<:@â8::@æït<:@éÛX::@îÇ”<:@ò8::@öît<:@ùÚX::@ÿT<:AÙØ::AŠô<:A ÙX::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Godthab0000644000175000017500000000047411564260550023567 0ustar ebourgebourgCLMTWGSTWGT$ÿ€¿ÿÿÏ€¿ÿÿÏ€¿›€h::@R[¬<:@V3::@Z2Ü<:@^2œ::@b2\<:@f2::@j1Ü<:@n1œ::@r1\<:@vX|::@zX<<:@~Wü::@‚W¼<:@†W|::@ŠW<<:@ŽVü::@’V¼<:@–V|::@šV<<:@žUü::@¢U¼<:@¦|Ü::@ª|œ<:@®|\::@²|<:@¶{Ü::@º{œ<:@¾{\::@Â{<:@ÆzÜ::@Êzœ<:@Îz\::@Ò¡|<:@×>¼:::uÿWGSTu ÿWGTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Mexico_City0000644000175000017500000000042211564260551024425 0ustar ebourgebourgCCSTLMTCWTCDTMSTÿ€¿ÿÿ£ ¿ÿÿ£ ~~È$22~ªpÈ44~Åøè22~É©è44~Íè22~Ñ„44úh64 ¬44Ä64?l44.úÈ641ý,44`k64dÌ44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@ûŒà64@þÇ„44Aîà64Ad„444wCDTw ÿCSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Sao_Paulo0000644000175000017500000000171611564260551024102 0ustar ebourgebourgCBRTLMTBRST‚ÿ€¿ÿÿÔL¿ÿÿÔL¿–ªr´::~Í<:~ÑX::~Õ4<:~Ù x::^Ï´<:aÌ´::fÔÔ<:i}8::nÙô<:q‡ø::vä´<:xÞ¸::ÎLô<:Ñ'ø::ØŠ4<:ÙÕØ::ß84<:á28::æ””<:é7X::î™´<:ñB::@´<:@‚˜::@†ïÔ<:@‰e˜::@Žôô<:@‘CX::@–Í<:@™x::@žÌ”<:@¡i¸::@¦ót<:@©˜::@®òô<:@±h¸::@·Ô<:@¹@Ø::@¾ñô<:@Á¶x::@Æñt<:@ɵø::@Îðô<:@ÑŽ::@ÖÉ<:@Ù´ø::@ÞÎ4<:@â8::@æït<:@éÛX::@îÇ”<:@ò8::@öît<:@ùÚX::@ÿT<:AÙØ::AŠô<:A ÙX::A;´<:AØØ::A•4<:Aÿ¸::A:´<:A!ÿ8::A'°T<:A*&::A/9´<:A1þ8::A7`”<:A9ý¸::A?`<:AB$˜::AG_”<:AJ$::AO_<:ARJø::AW…ô<:AZ#::A_…t<:Ab"˜::Ag„ô<:AjIx::Ao„t<:ArHø::Awƒô<:AzHx::Aƒt<:A‚Gø::A‡ªT<:AŠGx::A©Ô<:A’Fø::A—©T<:AšmØ::AŸ¨Ô<:A¢mX::A§¨T<:Aª”8::A¯§Ô<:A²lX::A·Î´<:AºkØ::A¿Î4<:AÂ’¸::AÇÍ´<:AÊ’8::AÏÍ4<:AÒ‘¸::A×Ì´<:AÚ‘8::Aßó”<:Aâ¸::Açó<:Aê8::Aïò”<:Aò¸::A÷ò<:Aú¶˜::Aÿñ”<:BÝx::Bñ<:B µ˜::Bô<:Bµ::Bt<:BÛø::B ô<:B"Ûx:::w BRSTwBRTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Maceio0000644000175000017500000000051411564260551023410 0ustar ebourgebourgCBRTLMTBRST*ÿ€¿ÿÿÞ„¿ÿÿÞ„¿–ªh|::~Í<:~ÑX::~Õ4<:~Ù x::^Ï´<:aÌ´::fÔÔ<:i}8::nÙô<:q‡ø::vä´<:xÞ¸::ÏUT<:Ñ'ø::ØŠ4<:ÙÕØ::ß84<:á28::æ””<:é7X::î™´<:ñB::@´<:@‚˜::@†ïÔ<:@‰e˜::@Žôô<:@‘CX::@–Í<:@™x::@žÌ”<:@¡i¸::@Îðô<:@ÑŽ::@îÇ”<:@ò8::@öît<:@÷<ø::@ÿT<:AÙØ::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/St_Johns0000644000175000017500000000321511564260551023743 0ustar ebourgebourgCNSTNPTNDTLMTNDDTNWT´ÿ€¿ÿÿΔ¿ÿÿΔ¿^=4ì¿ÿÿΔ¿ÿÿΔ¿œÏb ¿ÿÿܤ¿ÿÿΔ¿¤æü¿ÿÿΔ¿ÿÿΔ¿ž¸~Œ¿ÿÿܤ¿ÿÿΔ¿ŸÀ|¿ÿÿΔ¿ÿÿΔ¿ ¶ˆÜ¿ÿÿܤ¿ÿÿΔ¿¡8ÿL¿ÿÿΔ¿ÿÿΔ¿¢•\¿ÿÿܤ¿ÿÿΔ¿£„üL¿ÿÿΔ¿ÿÿΔ¿¤tû\¿ÿÿܤ¿ÿÿΔ¿¥dÞL¿ÿÿΔ¿ÿÿΔ¿¦^Ü¿ÿÿܤ¿ÿÿΔ¿§DÀL¿ÿÿΔ¿ÿÿΔ¿¨=ùÜ¿ÿÿܤ¿ÿÿΔ¿©$¢L¿ÿÿΔ¿ÿÿΔ¿ªÛÜ¿ÿÿܤ¿ÿÿΔ¿«„L¿ÿÿΔ¿ÿÿΔ¿«ý½Ü¿ÿÿܤ¿ÿÿΔ¿¬äfL¿ÿÿΔ¿ÿÿΔ¿­ÝŸÜ¿ÿÿܤ¿ÿÿΔ¿®Í‚Ì¿ÿÿΔ¿ÿÿΔ¿¯½Ü¿ÿÿܤ¿ÿÿΔ¿°­dÌ¿ÿÿΔ¿ÿÿΔ¿±¦ž\¿ÿÿܤ¿ÿÿΔ¿²FÌ¿ÿÿΔ¿ÿÿΔ¿³†€\¿ÿÿܤ¿ÿÿΔ¿´m(Ì¿ÿÿΔ¿ÿÿΔ¿µfb\¿ÿÿܤ¿ÿÿΔ¿¶M Ì¿ÿÿΔ¿ÿÿΔ¿·FD\¿ÿÿܤ¿ÿÿΔ¿¸,ìÌ¿ÿÿΔ¿ÿÿΔ¿¹&&\¿ÿÿܤ¿ÿÿΔ¿º L¿ÿÿΔ¿ÿÿΔ¿»BÜ¿ÿÿܤ¿ÿÿΔ¿»õëL¿ÿÿΔ¿ÿÿΔ¿¼ï$Ü¿ÿÿܤ¿ÿÿΔ¿½ÕÍL¿ÿÿΔ¿ÿÿΔ¿¾žMl99~éÙ¶;9~í±Ú99~òÒ;9~õ;v99~úR;9~ý:ö99ÿÒ;9:v99 &²;9 9ö99&2;9`Ö99%²;9`V99"%2;9ê;9­ î99²>j;9¶eN99ºeJ;9¾dÎ99ÂdÊ;9ÆdN99ÊdJ;9ÎcÎ99ÒcÊ;9ÖcN99ÚcJ;9ÞŠ.99âbÊ;9扮99ꉪ;9î‰.99ò‰*;9öˆ®99úˆª;9þˆ.99@ˆ*;9@‡®99@ ‡ª;9@®Ž99@®Š;9@®99@® ;9@­Ž99@"­Š;9@&­99@*­ ;9@.¬Ž99@2¬Š;9@6Ón99@:¬ ;9@>Òî99@BÒê;9@FÒn99@JÒj;9@NÑî99@RÑê;9@VÑn99@ZÑj;9@^Ðî99@bÐê;9@f÷Î99@jÐj;9@n÷N99@r÷J;9@vöÎ99@zöÊ;9@~öN99@‚öJ;9@†õÎ99@Š3;9@Žô×99@’~³=9@—{99@š~3;9@Ÿ799@¢}³;9@§·99@ª¤“;9@¯799@²¤;9@··99@º£“;9@¿@—99@£;9@Ç@99@Ê¢“;9@Ï?—99@ÒÉs;9@×?99@ÚÈó;9@ß>—99@âÈs;9@ç>99@êÇó;9@ïd÷99@òÇs;9@÷dw99@úÆó;9@ÿc÷99AíÓ;9Acw99A íS;9Ab÷99AìÓ;9A‰×99AìS;9A‰W99A"ëÓ;9A'ˆ×99A*u3;9A/¯·999w@NDTw @NSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Anguilla0000644000175000017500000000005611564260551023750 0ustar ebourgebourgPLMTASTÿ€¿ÿÿÄà¿ÿÿÄà¿“75 88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Mazatlan0000644000175000017500000000035411564260551023764 0ustar ebourgebourgCCSTLMTMDTPSTMSTÿ€¿ÿÿœ<¿ÿÿœ<~~È$22~ªpÈ44~Åøè22~É©è44~Íè22~Ñ„44!Æ(22WÃ0022@Òʼ42@×@`22@ÚÊ<42@ß?à22@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@û42@þÇÀ22Aï42AdÀ222wMDTw ÿMSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Atikokan0000644000175000017500000000015411564260551023754 0ustar ebourgebourgCCSTLMTCPTESTCWTCDTÿ€¿ÿÿª¿ÿÿª¿rî„d44~`ñ 64~eVd444¨64 &`64ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Rio_Branco0000644000175000017500000000040411564260551024226 0ustar ebourgebourgCACSTACTLMTAMTÿ€¿ÿÿÀp¿ÿÿÀp¿–ª†66~Í€86~ÑÐ66~Õ¬86~Ù ð66^Ð,86aÍ,66fÕL86i}°66nÚl86qˆp66vå,86xß066ÏUÌ86Ñ(p66ØŠ¬86ÙÖP66ß8¬86á2°66æ• 86é7Ð66îš,86ñB66@,86@‚66@†ðL86@‰f66@Žõl86@‘CÐ66A4Îì88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Yellowknife0000644000175000017500000000077611564260551024515 0ustar ebourgebourgCMWTMDDTMDTMPTzzzMST?ÿ€~ç22 &œ42¤86~| ¨66~e„86~„ (66~‰e86~ŒÇ66~‘d„86~”ƈ66~™d86~œÆ66~¡c„86~¤Åˆ66~©c86~¬Å66~±‰ä86~´ëè66~¹‰d86~¼ëh66~Áˆä86~Äêè66~Ɉd86~Ìêh66~чä86~Ôéè66~Ù®Ä86~Üéh66~á®D86~åH66~é­Ä86~íÈ66~ñ­D86~õH66~ù¬Ä86~ýÈ66¬D86H66 Ó$86 È66Ò¤864¨66Ò$864(66 &$86È66²>Ä86¶e¨66ºe¤86¾e(66Âe$86Æd¨66Êd¤86Îd(66Òd$86Öc¨66Úc¤86ÞŠˆ66âc$86æŠ66êŠ8666ò‰„86ö‰66ú‰86þˆˆ66@ˆ„86@ˆ66@ ˆ86@®è66@®ä86@®h66@®d86@­è66@ 7ä86@&­h66@)K86@.¬è66@2¬ä86@6ÓÈ66@:¬d86@>ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Denver0000644000175000017500000000137411564260550023442 0ustar ebourgebourgCMWTLMTMDTMPTMSTcÿ€¿ÿÿ”¿ÿÿ”}LÞ22~`£42~e@ 22~h¢œ42~m? 22~p¢42~uf€22~x¡œ42~yÜ`22 &œ42ÓÀ22@BÓ¼42@FÓ@22@JÓ<42@NÒÀ22@RÒ¼42@VÒ@22@ZÒ<42@^ÑÀ22@bѼ42@fø 22@jÑ<42@nø 22@rø42@v÷ 22@z÷œ42@~÷ 22@‚÷42@†ö 22@Š€|42@Žö 22@’ü42@—22@š|42@Ÿ€22@¢~ü42@§22@ª¥Ü42@¯€22@²¥\42@·22@º¤Ü42@¿Aà22@¤\42@ÇA`22@Ê£Ü42@Ï@à22@Òʼ42@×@`22@ÚÊ<42@ß?à22@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@úÈ<42@ÿe@22Aï42AdÀ22A îœ42Ad@22Aî42A‹ 22Aíœ42AŠ 22A"í42A'Š 22A*v|42A/±222wMDTw MSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Matamoros0000644000175000017500000000045111564260551024155 0ustar ebourgebourgCCSTLMTCDT"ÿ€ÿþpÿþp~~Çè44@’À64@—Ä44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@ûŒà64@þÇ„44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*ì`64A/‰d44A3@64A7ˆä44A;À64A?ˆd44ABœ 64AGÖ¤444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Port_of_Spain0000644000175000017500000000005611564260551024756 0ustar ebourgebourgPLMTASTÿ€¿ÿÿÆT¿ÿÿÆT¿“73¬88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Anchorage0000644000175000017500000000130711564260550024102 0ustar ebourgebourgC LMTAKDTCAPTYSTAHDTAHSTCATAKSTCAWTVÿ€€Äø€Äø¿?Àà¿ÿÿsx¿ÿÿsx¿}‡AH,, 'P.,Ôt,,@BÔp.,@FÓô,,@JÓð.,@NÓt,,@RÓp.,@VÒô,,@ZÒð.,@^Òt,,@bÒp.,@fùT,,@jÑð.,@nøÔ..@o¦¼..@rø”0.@vø..@zø0.@~÷˜..@‚÷”0.@†÷..@Š€ô0.@Žö˜..@’€t0.@—x..@šô0.@Ÿø..@¢t0.@§x..@ª¦T0.@¯ø..@²¥Ô0.@·x..@º¥T0.@¿BX..@¤Ô0.@ÇAØ..@ʤT0.@ÏAX..@ÒË40.@×@Ø..@ÚÊ´0.@ß@X..@âÊ40.@ç?Ø..@êÉ´0.@ïf¸..@òÉ40.@÷f8..@úÈ´0.@ÿe¸..Aï”0.Ae8..A ï0.Ad¸..Aî”0.A‹˜..Aî0.A‹..A"í”0.A'Š˜..A*vô0.A/±x...wAKDTw AKSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/El_Salvador0000644000175000017500000000011711564260551024405 0ustar ebourgebourgCCSTLMTCDTÿ€¿ÿÿ¬`¿ÿÿ¬`¿£Õ¦ 44@‹H64@ŽWì44@“È64@–Wl44joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Tegucigalpa0000644000175000017500000000013511564260551024437 0ustar ebourgebourgCCSTLMTCDTÿ€¿ÿÿ®<¿ÿÿ®<¿¤LKD44@‹H64@ŽWì44@“È64@–Wl44A#±H64A%¶Œ44joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Caracas0000644000175000017500000000012111564260551023542 0ustar ebourgebourgPLMTCMTVETÿ€¿ÿÿÁ@¿ÿÿÁ@¿i‡@¿ÿÿÁD¿ÿÿÁD¿“,<77×áÎ88A0u¤77joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Port-au-Prince0000644000175000017500000000046411564260551024764 0ustar ebourgebourgCPPMTLMTEDTEST%ÿ€¿ÿÿ¼0¿ÿÿ¼0¿i‡Pÿþßÿþß~W,‘66@k 86@n÷066@r÷,86@vö°66@zö¬86@~ö066@‚ö,86@†õ°66@Šõ¬86@Žõ066@’H86@—ˆ66@š~È86@Ÿ66@¢~H86@§ˆ66@ª¥(86@¯66@²¤¨86@·ˆ66@º¤(86@¿Ah66@£¨86@Ç@è66@Ê£(86@Ï@h66@ÒÊ86@×?è66@ÚɈ86@ß?h66Aì¬86A‰°66A"ì,86A'‰066joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Adak0000644000175000017500000000130411564260551023051 0ustar ebourgebourgC NSTNPTLMTBSTHASTBDTAHSTNWTHADTVÿ€€«á€«á¿?Àù¿ÿÿZb¿ÿÿZb¿}‡Z^** 'Œ,*Ô°**@BÔ¬,*@FÔ0**@JÔ,,*@NÓ°**@RÓ¬,*@VÓ0**@ZÓ,,*@^Ò°**@bÒ¬,*@fù**@jÒ,,*@nù,,@o¦ø,,@røÐ.,@vøT,,@zøP.,@~÷Ô,,@‚÷Ð.,@†÷T,,@Š0.,@ŽöÔ,,@’€°.,@—´,,@š€0.,@Ÿ4,,@¢°.,@§´,,@ª¦.,@¯4,,@²¦.,@·´,,@º¥.,@¿B”,,@Â¥.,@ÇB,,@ʤ.,@ÏA”,,@ÒËp.,@×A,,@ÚÊð.,@ß@”,,@âÊp.,@ç@,,@êÉð.,@ïfô,,@òÉp.,@÷ft,,@úÈð.,@ÿeô,,AïÐ.,Aet,,A ïP.,Adô,,AîÐ.,A‹Ô,,AîP.,A‹T,,A"íÐ.,A'ŠÔ,,A*w0.,A/±´,,,wHADTw HASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Santiago0000644000175000017500000000151411564260551023761 0ustar ebourgebourgCCLTLMTSMTCLSTkÿ€¿ÿÿ½º¿ÿÿ½º¿i‡Æ¿ÿÿ½º¿ÿÿ½º¿$iÆ66~Rl¿ÿÿ½º¿ÿÿ½º¿ŸqF88~j¬¿ÿÿ½º¿ÿÿ½º~¬=Ì86~°ë°66~´HŒ86~¸ðÐ66~¼M¬86~Àõð66~ÄRÌ86~Èû66~ÌWì86~ÑÐ66~Ôb¬86"›p66#òÌ86DºÔ66J‚¬88ö¯ð:8ùê”88ÿ%:8@ê88@8Ð:8@ šÔ88@8P:8@šT88@_0:8@™Ô88@ð:8@!™T88@&^0:8@)˜Ô88@.]°:8@1¿´88@6]0:8@9¿488@>\°:8@A¾´88@Fƒ:8@I¾488@Nƒ:8@Q½´88@V‚:8@Yä”88@^‚:8@aä88@f:8@iã”88@n:8@qã88@v§ð:8@yâ”88@~§p:8@â88@†¦ð:8@Цt88@ަp:8@’t88@–~:8@šô88@žÌÐ:8@¢.Ô88@¦.Ð:8@ªô88@®ËÐ:8@²-Ô88@¶ËP:8@º-T88@¾ÊÐ:8@Â,Ô88@ÆÊP:8@Ê,T88@Îñ0:8@Ò+Ô88@Öð°:8@Ú¡t88@Þð0:8@âR488@æ ð:8@êÇÔ88@îï0:8@òQ488@÷:8@úP´88@ÿ:8AP488A:8A O´88A:8Av”88A:8Av88A:8A"u”88A':p:8A*u88A/9ð:8A2ê´88A79p:8A:›t88A?8ð:8AC88AG8p:8AJšt888u CLSTu CLTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Blanc-Sablon0000644000175000017500000000014011564260551024441 0ustar ebourgebourgCAWTLMTAPTASTADTÿ€¿ÿÿÊt¿ÿÿÊt¿^=9 88~`ñ(:8~eUì88 %è:8Ó„44@BÓ€64@FÓ44@JÓ64@NÒ„44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D44@²¥ 64@·Ä44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@úÈ64@ÿe44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Cambridge_Bay0000644000175000017500000000102411564260551024660 0ustar ebourgebourgC CSTMWTMDDTMDTMPTzzzESTCDTMST@ÿ€~n¶ 22 &œ42Ó„44@BÓ€64@FÓ44@JÓ64@NÒ„44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D44@²¥ 64@·Ä44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@úÈ64@ÿe44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Resolute0000644000175000017500000000073511564260551024022 0ustar ebourgebourgCCSTzzzCDDTESTCDT;ÿ€L¹ 44Úch84ÞŠˆ44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D44@²¥ 64@·Ä44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„66@úÈ64@ÿe44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä66A*v666w ESTwCDTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Juneau0000644000175000017500000000126711564260550023447 0ustar ebourgebourgCLMTAKDTPWTPDTPSTYSTAKSTPPTUÿ€€Ó{€Ó{¿?ÀÑ…¿ÿÿû¿ÿÿû¿}‡2Å00 &Ø20Óü00@BÓø20@FÓ|00@JÓx20@NÒü00@RÒø20@VÒ|00@ZÒx20@^Ñü00@bÑø20@føÜ00@jÑx20@nø˜..@o¦¼..@rø”0.@vø..@zø0.@~÷˜..@‚÷”0.@†÷..@Š€ô0.@Žö˜..@’€t0.@—x..@šô0.@Ÿø..@¢t0.@§x..@ª¦T0.@¯ø..@²¥Ô0.@·x..@º¥T0.@¿BX..@¤Ô0.@ÇAØ..@ʤT0.@ÏAX..@ÒË40.@×@Ø..@ÚÊ´0.@ß@X..@âÊ40.@ç?Ø..@êÉ´0.@ïf¸..@òÉ40.@÷f8..@úÈ´0.@ÿe¸..Aï”0.Ae8..A ï0.Ad¸..Aî”0.A‹˜..Aî0.A‹..A"í”0.A'Š˜..A*vô0.A/±x...wAKDTw AKSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Rankin_Inlet0000644000175000017500000000074411564260551024575 0ustar ebourgebourgCCSTzzzCDDTESTCDT<ÿ€—¬€44Úch84ÞŠˆ44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D44@²¥ 64@·Ä44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„66@úÈ64@ÿe44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Managua0000644000175000017500000000025711564260551023570 0ustar ebourgebourgCCSTLMTMMTCDTESTÿ€¿ÿÿ¯¿ÿÿ¯¿i‡,d¿ÿÿ¯¿ÿÿ¯¿½-Hè44@¹h66@)#,44@IæH64@Lì44@QåÈ64@Tl44@°866@¶kì44@¸™66@زì44AH64Aìl44A#Š`64A&ì(44joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Miquelon0000644000175000017500000000060211564260551024002 0ustar ebourgebourgCLMTPMSTASTPMDT-ÿ€¿ÿÿËX¿ÿÿËX¿‘¶8¨88@Rè::@ŠŒ<:@Žõ0::@’ <:@—::@š~Œ<:@Ÿ::@¢~ <:@§::@ª¤ì<:@¯::@²¤l<:@·::@º£ì<:@¿@ð::@£l<:@Ç@p::@Ê¢ì<:@Ï?ð::@ÒÉÌ<:@×?p::@ÚÉL<:@ß>ð::@âÈÌ<:@ç>p::@êÈL<:@ïeP::@òÇÌ<:@÷dÐ::@úÇL<:@ÿdP::Aî,<:AcÐ::A í¬<:AcP::Aí,<:AŠ0::Aì¬<:A‰°::A"ì,<:A'‰0::A*uŒ<:A/°:::wPMDTw PMSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Panama0000644000175000017500000000010311564260551023402 0ustar ebourgebourgPLMTCMTESTÿ€¿ÿÿµp¿ÿÿµp¿i‡&¿ÿÿµ¿ÿÿµ¿‹ôaè66joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Edmonton0000644000175000017500000000134111564260551023775 0ustar ebourgebourgCMWTLMTMDTMPTMST_ÿ€¿ÿÿ• ¿ÿÿ• ¿ˆÞÎà22~`ñÜ42~eV 22~hñ\42~iè 22~q?œ42~uf€22~y?42~|¡ 22~eü42~„  22~‰e|42~ŒÇ€22 &œ42ÓÀ22@BÓ¼42@FÓ@22@JÓ<42@NÒÀ22@RÒ¼42@VÒ@22@ZÒ<42@^ÑÀ22@bѼ42@fø 22@jÑ<42@nø 22@rø42@v÷ 22@z÷œ42@~÷ 22@‚÷42@†ö 22@Š€|42@Žö 22@’ü42@—22@š|42@Ÿ€22@¢~ü42@§22@ª¥Ü42@¯€22@²¥\42@·22@º¤Ü42@¿Aà22@¤\42@ÇA`22@Ê£Ü42@Ï@à22@Òʼ42@×@`22@ÚÊ<42@ß?à22@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@úÈ<42@ÿe@22Aï42AdÀ22A îœ42Ad@22Aî42A‹ 22Aíœ42AŠ 22A"í42A'Š 22A*v|42A/±222wMDTw MSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Antigua0000644000175000017500000000007211564260551023602 0ustar ebourgebourgPLMTASTESTÿ€¿ÿÿÆ¿ÿÿÆ¿“73ð66gƒ¬88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Nome0000644000175000017500000000130311564260550023105 0ustar ebourgebourgC NSTNPTLMTAKDTBSTBDTYSTAKSTNWTVÿ€€¶m€¶m¿?Àî“¿ÿÿdî¿ÿÿdî¿}‡OÒ** 'Œ,*Ô°**@BÔ¬,*@FÔ0**@JÔ,,*@NÓ°**@RÓ¬,*@VÓ0**@ZÓ,,*@^Ò°**@bÒ¬,*@fù**@jÒ,,*@nù..@o¦¼..@rø”0.@vø..@zø0.@~÷˜..@‚÷”0.@†÷..@Š€ô0.@Žö˜..@’€t0.@—x..@šô0.@Ÿø..@¢t0.@§x..@ª¦T0.@¯ø..@²¥Ô0.@·x..@º¥T0.@¿BX..@¤Ô0.@ÇAØ..@ʤT0.@ÏAX..@ÒË40.@×@Ø..@ÚÊ´0.@ß@X..@âÊ40.@ç?Ø..@êÉ´0.@ïf¸..@òÉ40.@÷f8..@úÈ´0.@ÿe¸..Aï”0.Ae8..A ï0.Ad¸..Aî”0.A‹˜..Aî0.A‹..A"í”0.A'Š˜..A*vô0.A/±x...wAKDTw AKSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Noronha0000644000175000017500000000047611564260551023626 0ustar ebourgebourgCLMTFNTFNST(ÿ€¿ÿÿ᜿ÿÿ᜿–ªed<<~Í Ì><~Ñ<<~Õø><~Ù <<<^Ïx><aÌx<<fÔ˜><i|ü<<nÙ¸><q‡¼<<väx><xÞ|<<ÏU><Ñ'¼<<؉ø><ÙÕœ<<ß7ø><á1ü<<æ”X><é7<<î™x><ñAÜ<<@x><@‚\<<@†ï˜><@‰e\<<@Žô¸><@‘C<<@–ÌØ><@™<<<@žÌX><@¡i|<<@îÇX><@òü<<@öî8><@÷\<<@ÿ><AÙœ<<joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Barbados0000644000175000017500000000020011564260551023720 0ustar ebourgebourgCLMTASTBMTADT ÿ€¿ÿÿÈ¿ÿÿÈ¿©y$ä¿ÿÿÈ¿ÿÿÈ¿¸…cä88@;¿È:8@>5Œ88@B„H:8@F5 88@JƒÈ:8@N4Œ88@Rª¨:8@V#,88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Tortola0000644000175000017500000000005611564260551023640 0ustar ebourgebourgPLMTASTÿ€¿ÿÿÃl¿ÿÿÃl¿‘ô788joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Dominica0000644000175000017500000000005611564260551023737 0ustar ebourgebourgPLMTASTÿ€¿ÿÿÆp¿ÿÿÆp¿‘ô4L88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Dawson_Creek0000644000175000017500000000072111564260551024557 0ustar ebourgebourgCLMTPWTPDTPSTMSTPPT;ÿ€¿ÿÿH¿ÿÿH¿^=t800~`ò20~eVÜ00 &Ø20ÓÀ22@BÓ¼42@FÓ@22@JÓ<42@NÒÀ22@RÒ¼42@VÒ@22@ZÒ<42@^ÑÀ22@bѼ42@fø 22@jÑ<42@nø 22@rø42@v÷ 22@z÷œ42@~÷ 22@‚÷42@†ö 22@Š€|42@Žö 22@’ü42@—22@š|42@Ÿ€22@¢~ü42@§22@ª¥Ü42@¯€22@²¥\42@·22@º¤Ü42@¿Aà22@¤\42@ÇA`22@Ê£Ü42@Ï@à22@Òʼ42@×@`22@ÚÊ<42@ß?à22@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@úÈ<42@ÿe@22Aï42AdÀ22A îœ42Ad@22Aî42A‹ 22Aíœ42AŠ 22A"í42A'Š 22A*v|42A/±222wMDTw MSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Los_Angeles0000644000175000017500000000170011564260550024403 0ustar ebourgebourgCLMTPWTPDTPSTPPTÿ€¿ÿÿ‘&¿ÿÿ‘&}LÞP00~`£X20~e@\00~h¢Ø20~m?Ü00 &Ø20Óü00@BÓø20@FÓ|00@JÓx20@NÒü00@RÒø20@VÒ|00@ZÒx20@^Ñü00@bÑø20@føÜ00@jÑx20@nø\00@røX20@v÷Ü00@z÷Ø20@~÷\00@‚÷X20@†öÜ00@Š€¸20@Žö\00@’€820@—<00@š¸20@Ÿ¼00@¢820@§<00@ª¦20@¯¼00@²¥˜20@·<00@º¥20@¿B00@¤˜20@ÇAœ00@ʤ20@ÏA00@ÒÊø20@×@œ00@ÚÊx20@ß@00@âÉø20@ç?œ00@êÉx20@ïf|00@òÈø20@÷eü00@úÈx20@ÿe|00AïX20Adü00A îØ20Ad|00AîX20A‹\00AíØ20AŠÜ00A"íX20A'Š\00A*v¸20A/±<000wPDTw PSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Whitehorse0000644000175000017500000000106411564260551024335 0ustar ebourgebourgCLMTPDTPSTYDDTYPTYSTYDTYWTDÿ€¿ÿÿd¿ÿÿd¿}†Šœ..~`òT0.~e@˜..~iÞ0.~ma`.. '0.ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Santa_Isabel0000644000175000017500000000117411564260551024543 0ustar ebourgebourgCLMTPWTPDTPSTMSTPPTPÿ€¿ÿÿ”P¿ÿÿ”P~~È`22~ŽÒd00~ªq22~Åù$00~Èü20~Ìû„00!Æ 20K¤00Q…À20WÃ00‚20…}00Š˜20|œ00’Ax20•£|00š@ø20¢ü00¢@x20¥¢|00ª?ø20­¡ü00²?x20µ¡|00@2­˜20@6Ô|00@:­20@>Óü00@BÓø20@FÓ|00@JÓx20@NÒü00@RÒø20@VÒ|00@ZÒx20@^Ñü00@bÑø20@føÜ00@jÑx20@nø\00@røX20@v÷Ü00@z÷Ø20@~÷\00@‚÷X20@†öÜ00@Š€¸20@Žö\00@’€820@—<00@š¸20@Ÿ¼00@¢820@§<00@ª¦20@¯¼00@²¥˜20@·<00@º¥20@¿B00@¤˜20@ÇAœ00@ʤ20@ÏA00@ÒÊø20@×@œ00@ÚÊx20@ß@00@âÉø20@ç?œ00@êÉx20@ïf|00@òÈø20@÷eü00@úÈx20@ÿe|00AïX20Adü000wPDTw ÿPSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/La_Paz0000644000175000017500000000013111564260551023354 0ustar ebourgebourgCBOSTLMTCMTBOTÿ€¿ÿÿÀ¿ÿÿÀ¿i‡d¿ÿÿÀ¿ÿÿÀ¿¸–ä¿ÿÿÎ,¿ÿÿÀ¿¸îÕÔ88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Kentucky/0000755000175000017500000000000012205344143024056 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Kentucky/Louisville0000644000175000017500000000162211564260551026140 0ustar ebourgebourgCCSTLMTCPTEDTESTCWTCDTwÿ€¿ÿÿ¯š¿ÿÿ¯š}LÝØ44~`¢à64~e?ä44~h¢`64~m?d44~yf@64~|ä44Ò`644d44 &`64$66ò‰„86ö‰66ú‰86þˆˆ66@ˆ„86@ˆ66@ ˆ86@®è66@®ä86@®h66@®d86@­è66@ 7ä64@&­¤66@)K86@.¬è66@2¬ä86@6ÓÈ66@:¬d86@>ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Kentucky/Monticello0000644000175000017500000000130011564260551026107 0ustar ebourgebourgCCSTLMTCPTEDTESTCWTCDTYÿ€¿ÿÿ°t¿ÿÿ°t}LÝØ44~`¢à64~e?ä44~h¢`64~m?d44 &`64Ó„44@BÓ€64@FÓ44@JÓ64@NÒ„44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D44@²¥ 64@·Ä44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/St_Thomas0000644000175000017500000000005611564260551024115 0ustar ebourgebourgPLMTASTÿ€¿ÿÿà ¿ÿÿà ¿‘ô7`88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Manaus0000644000175000017500000000040611564260551023437 0ustar ebourgebourgCLMTAMTAMST ÿ€¿ÿÿǼ¿ÿÿǼ¿–ªD88~ÍD:8~Ñ”88~Õp:8~Ù ´88^Ïð:8aÌð88fÕ:8i}t88nÚ0:8qˆ488väð:8xÞô88ÏU:8Ñ(488ØŠp:8ÙÖ88ß8p:8á2t88æ”Ð:8é7”88î™ð:8ñBT88@ð:8@‚Ô88@†ð:8@‰eÔ88@Žõ0:8@‘C”88@¾ò0:8@Á¶´88joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Nipigon0000644000175000017500000000113411564260551023615 0ustar ebourgebourgCEPTLMTEWTEDTESTLÿ€¿ÿÿ­@¿ÿÿ­@¿rî@66~`ñd86~eV(664l86 &$86ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Montreal0000644000175000017500000000241211564260551023773 0ustar ebourgebourgCEPTLMTEWTEDTEST®ÿ€¿ÿÿ»¿ÿÿ»¿^=Hx66~X{Ä86~Y#Ð66~`ñd86~eV(66~h§â86~m9¦66~qf¢86~tȦ66~yf86~|È&66~e„86~„Ǧ66~‘Õ86~”Ʀ66~™‹d86~œÆ&66~¡Šä86~¤Å¦66~©‰ì86~¬Ä66~±‰l86~´ëp66~¹ˆì86~¼êð66~Áˆl86~Äêp66~ɇì86~Ìéð66~Ñ®Ì86~Ôép66~Ù®L86~ÝP66~á­Ì86~åÐ66~é­L86~íP66~ñ¬Ì86~õÐ66~ù¬L86~ýP66«Ì86 Ð66 Ò¬86 P66Ò,86 &$86È66²>Ä86¶e¨66ºe¤86¾e(66Âe$86Æd¨66Êd¤86Îd(66Òd$86Öc¨66Úc¤86ÞŠˆ66âc$86æŠ66êŠ8666ò‰„86ö‰66ú‰86þˆˆ66@ˆ„86@ˆ66@ ˆ86@®è66@®ä86@®h66@®d86@­è66@"­ä86@&­h66@*­d86@.¬è66@2¬ä86@6ÓÈ66@:¬d86@>ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Regina0000644000175000017500000000065611564260551023427 0ustar ebourgebourgCCSTMWTLMTMDTMPTMST6ÿ€¿ÿÿä¿ÿÿ俆ý“22~`ñÜ42~eV 22~Á°D42~ÅH22~ɯÄ42~ÍÈ22~ѯD42~ÕH22~ÙÖ$42~ÝÈ22~áÕ¤42~å7¨22~ù^42~ý]ˆ22]„425¨22 ]42 \ˆ22ƒä42ƒh22ƒd42‚è22 &œ42°66~qf„86~t °66~y´Ä86~|hh66~´D86~„xÈ66~‰³Ä86~ŒxH66~‘‹ä86~”Ÿ(66~™‹d86~œž¨66~¡Šä86~¤ž(66~©Šd86~¬Å66~±‰ä86~´ëè66~¹‰d86~¼ëh66~Áˆä86~Äêè66~Ɉd86~Ìêh66~ѯD86~Ôéè66~Ù®Ä86~ÝÈ66~á®D86~åH66~é­Ä86~íÈ66~ñ­D86~õH66~ù¬Ä86~ýÈ66¬D86H66 Ó$86 È66Ò¤86 &$86È66²>Ä86¶e¨66ºe¤86¾e(66Âe$86Æd¨66Êd¤86Îd(66Òd$86Öc¨66Úc¤86ÞŠˆ66âc$86æŠ66êŠ8666ò‰„86ö‰66ú‰86þˆˆ66@ˆ„86@ˆ66@ ˆ86@®è66@®ä86@®h66@®d86@­è66@"­ä86@&­h66@*­d86@.¬è66@2¬ä86@6ÓÈ66@:¬d86@>ÓH66@BÓD86@FÒÈ66@JÒÄ86@NÒH66@RÒD86@VÑÈ66@ZÑÄ86@^ÑH66@bÑD86@fø(66@jÐÄ86@n÷¨66@r÷¤86@v÷(66@z÷$86@~ö¨66@‚ö¤86@†ö(66@Š€86@Žõ¨66@’„86@—ˆ66@š86@Ÿ66@¢~„86@§ˆ66@ª¥d86@¯66@²¤ä86@·ˆ66@º¤d86@¿Ah66@£ä86@Ç@è66@Ê£d86@Ï@h66@ÒÊD86@×?è66@ÚÉÄ86@ß?h66@âÉD86@ç>è66@êÈÄ86@ïeÈ66@òÈD86@÷eH66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Belem0000644000175000017500000000037011564260551023237 0ustar ebourgebourgCBRTLMTBRSTÿ€¿ÿÿÒŒ¿ÿÿÒŒ¿–ªtt::~Í<:~ÑX::~Õ4<:~Ù x::^Ï´<:aÌ´::fÔÔ<:i}8::nÙô<:q‡ø::vä´<:xÞ¸::ÏUT<:Ñ'ø::ØŠ4<:ÙÕØ::ß84<:á28::æ””<:é7X::î™´<:ñB::@´<:@‚˜::@†ïÔ<:@‰e˜::@Žôô<:@‘CX::joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Glace_Bay0000644000175000017500000000117711564260551024027 0ustar ebourgebourgCAWTLMTAPTASTADTQÿ€¿ÿÿÇÌ¿ÿÿÇÌ¿€ñ¨488~`ñ(:8~eUì88 %è:8Ó 88@BÓ:8@FÒŒ88@JÒˆ:8@NÒ 88@RÒ:8@VÑŒ88@Zш:8@^Ñ 88@bÑ:8@f÷ì88@jЈ:8@n÷l88@r÷h:8@vöì88@zöè:8@~öl88@‚öh:8@†õì88@ŠÈ:8@Žõl88@’H:8@—L88@š~È:8@ŸÌ88@¢~H:8@§L88@ª¥(:8@¯Ì88@²¤¨:8@·L88@º¤(:8@¿A,88@£¨:8@Ç@¬88@Ê£(:8@Ï@,88@ÒÊ:8@×?¬88@ÚɈ:8@ß?,88@âÉ:8@ç>¬88@êȈ:8@ïeŒ88@òÈ:8@÷e 88@úLj:8@ÿdŒ88Aîh:8Ad 88A íè:8AcŒ88Aíh:8AŠl88Aìè:8A‰ì88A"ìh:8A'‰l88A*uÈ:8A/°L888wADTw ASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Lima0000644000175000017500000000024611564260551023077 0ustar ebourgebourgCLMTPESTPETÿ€¿ÿÿ·Ä¿ÿÿ·Ä¿i‡#¼¿ÿÿ·¬¿ÿÿ·¬¿Œt@Ô66~ÿ0,86*066 86 66 Œ86 66@€i¬86@‚c°66@ˆnÌ86@ŠhÐ66@ ƒÌ86@¢}Ð66@Àì86@—ð66joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Pangnirtung0000644000175000017500000000102211564260551024502 0ustar ebourgebourgC CSTAWTAPTASTzzzEDTCDTESTADTADDT?ÿ€~vÁ`88 %è:8è66@êÈÄ86@ïf44@òÈ€64@÷e„66@úÇÄ86@ÿdÈ66Aî¤86AdH66A î$86AcÈ66Aí¤86AЍ66Aí$86AŠ(66A"ì¤86A'‰¨66A*v86A/°ˆ666wEDTw ESTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Chihuahua0000644000175000017500000000033211564260551024110 0ustar ebourgebourgCCSTLMTMDTCDTMSTÿ€¿ÿÿœŒ¿ÿÿœŒ~~È$22~ªpÈ44~Åøè22~É©è44~Íè22~Ñ„44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âɼ42@ç?`22@êÉ<42@ïf@22@òȼ42@÷eÀ22@û42@þÇÀ22Aï42AdÀ222wMDTw ÿMSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Phoenix0000644000175000017500000000017511564260551023630 0ustar ebourgebourgCMWTLMTMDTMST ÿ€¿ÿÿ–î¿ÿÿ–î}LÞ22~`£42~e@ 22~h¢œ42~m? 22 &œ42/TÉ221Tå425Z 22êŠ|42îŠ22joda-time-2.3/src/tz-data/org/joda/time/tz/data/America/Curacao0000644000175000017500000000007211564260551023567 0ustar ebourgebourgPLMTASTANTÿ€¿ÿÿ¿`¿ÿÿ¿`¿“. 77×áÎ88joda-time-2.3/src/tz-data/org/joda/time/tz/data/EET0000644000175000017500000000052111564260550021264 0ustar ebourgebourgCEESTEET)ÿ€@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/MET0000644000175000017500000000066311564260550021303 0ustar ebourgebourgCMETMEST7ÿ€~QD¨~T¡„~Xö~\X\~`õœ~dWÜ9\%üü)7Ü-^ü1^¼5^|9^<= œ@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼sÿMESTs ÿMETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/HST0000644000175000017500000000001011564260550021276 0ustar ebourgebourgFHST,,joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/0000755000175000017500000000000012205344143022105 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Dakar0000644000175000017500000000007211564260547023065 0ustar ebourgebourgPLMTGMTWATÿ€¿ÿÿ憎ÿÿ憎’æžØ>>•œjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Lusaka0000644000175000017500000000005611564260547023265 0ustar ebourgebourgPLMTCATÿ€€„€„¿‚FÉüjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Mogadishu0000644000175000017500000000010211564260547023755 0ustar ebourgebourgPLMTBEATEATÿ€€*ˆ€*ˆ¿p¼dø~Æÿ,—«êjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Maputo0000644000175000017500000000005611564260547023312 0ustar ebourgebourgPLMTCATÿ€€Œ€Œ¿‚FÅôjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Abidjan0000644000175000017500000000005611564260547023375 0ustar ebourgebourgPLMTGMTÿ€¿ÿÿü8¿ÿÿü8¿’æ’Hjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Blantyre0000644000175000017500000000005311564260547023622 0ustar ebourgebourgPLMTCATÿ€@Œ@Œ}ç”Tjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Maseru0000644000175000017500000000010711564260547023276 0ustar ebourgebourgCLMTSAST SAST-Summerÿ€@n@n}ç”r- `1 äjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Dar_es_Salaam0000644000175000017500000000011411564260547024513 0ustar ebourgebourgPLMTEATBEAUTÿ€€$Ô€$Ô¿¶£Ó¬OlÌ€&€&¿ïfãjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Kigali0000644000175000017500000000005611564260547023245 0ustar ebourgebourgPLMTCATÿ€€0€0¿¾ñPjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Ndjamena0000644000175000017500000000010211564260547023552 0ustar ebourgebourgCLMTWASTWATÿ€€€¿’æ€d@Nä@Q¶èjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Conakry0000644000175000017500000000010111564260547023442 0ustar ebourgebourgPLMTGMTWATÿ€¿ÿÿó$¿ÿÿó$¿’æ›\~àOà>>¯¼joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Ceuta0000644000175000017500000000060611564260550023101 0ustar ebourgebourgCWESTLMTCESTCETWET-ÿ€¿ÿÿû¿ÿÿû¿~6¹ü~apä~dÒè~‘*d~”ìD~¡:D~¤ëD~©d~¬êÄ~±9D~µ¤ëJpíêd@#ìà@%pÄ@2Í@4ÒD@:Ò @>¤@C… @Díd@qþ€@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Algiers0000644000175000017500000000046411564260547023436 0ustar ebourgebourgCWESTPMTLMTCESTCETWET#ÿ€€Ü€Ü¿kÈIà€1€1¿‘`PO~RB~T§$~Xyä~\Î~`*¤~dÍ„~hÄ~lÍ~o³„~u=~x[Ä~zˆ¤ ȤG`o1^¼5€9^<= $E„d?@Ê@ ‹Ä@ î@:î@@>Ÿ@B€@F|@NÅd@RÅ`@Vì¼@Zì@joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/El_Aaiun0000644000175000017500000000007211564260547023520 0ustar ebourgebourgPLMTWETWATÿ€¿ÿÿó ¿ÿÿó ¿¼Hðà>>@2mœjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Addis_Ababa0000644000175000017500000000010411564260547024131 0ustar ebourgebourgPLMTADMTEATÿ€€$H€$H¿C踀$h€$h¿À¯ò˜joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Kinshasa0000644000175000017500000000005611564260547023606 0ustar ebourgebourgPLMTWATÿ€€X€X¿xM,¨joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Freetown0000644000175000017500000000045311564260547023637 0ustar ebourgebourgCLMTGMTSLSTFMTWAT ÿ€ÿÿËÿÿË}=ÇÿÿËÿÿË~9Þµ>>~êkœÿÿì>~í´>>~òv\ÿÿì>~õ$t>>~ú{|ÿÿì>~ý)”>>€œÿÿì>.´>> …¼ÿÿì> 3Ô>>|ÿÿì>>”>>•œÿÿì>C´>>"š¼ÿÿì>%HÔ>>—¬¼šýà$£¥D« ­ d³àµ$»½Dà Å"djoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Tunis0000644000175000017500000000045111564260547023146 0ustar ebourgebourgCPMTLMTCESTCET#ÿ€€ Œ€ Œ¿YFô€1€1¿‘`PO ‚HFèsÈ_H ÁÄ%üü)7Ü)¢€)ϼ-^À1^¼5ˆ9^<=è@:ÌD@>$@B×@F3¤@“É„@–V@šUÄ@žU„@£%d@¦|dAˆÄAàA"ÃÜA'ˆ|A*Ã\A/‡üA2ê<A7‡|joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Monrovia0000644000175000017500000000013011564260547023630 0ustar ebourgebourgPLMTGMTMMTLRTÿ€¿ÿÿõä¿ÿÿõä¿Zz¦œ¿ÿÿõä¿ÿÿõä¿ _lœ¿ÿÿõ’¿ÿÿõ’€aöîjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Harare0000644000175000017500000000005611564260547023247 0ustar ebourgebourgPLMTCATÿ€€€¿‚FÇdjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Casablanca0000644000175000017500000000034111564260547024052 0ustar ebourgebourgCWESTLMTCETWETÿ€¿ÿÿøä¿ÿÿøä¿–Qùœ ÈàG$n >k„cfDëJpíêd@#ìà@%pÄ@2Í@4ÒD@:Ò @>¤@C… @Díd@qþ€@€hDA4L`A6Q¤AäAC­àAEÔäjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Nouakchott0000644000175000017500000000010111564260547024153 0ustar ebourgebourgPLMTGMTWATÿ€¿ÿÿñ ¿ÿÿñ ¿’æt~àOà>>·œjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Porto-Novo0000644000175000017500000000007211564260547024065 0ustar ebourgebourgPLMTGMTWATÿ€€t€t¿’æŒ ~àOàjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Bissau0000644000175000017500000000007211564260547023271 0ustar ebourgebourgPLMTGMTWATÿ€¿ÿÿñd¿ÿÿñd¿‘Ä“>>@(|joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Brazzaville0000644000175000017500000000005611564260547024332 0ustar ebourgebourgPLMTWATÿ€€T€T¿’æ€,joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Nairobi0000644000175000017500000000013111564260547023422 0ustar ebourgebourgCLMTBEATEATBEAUTÿ€€"„€"„¿±îÚü~¾ú 8ª€&€&¿í/áãjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Tripoli0000644000175000017500000000037511564260547023473 0ustar ebourgebourgCLMTCESTCETEETÿ€€ \€ \¿¡òÁ$mË|o‡(}¿<—–d¡H§¶„@`Mè@bHd@fMˆ@jM„@nR¨@rXD@v]h@zy„@~bˆ@‚sd@†rè@Šg¤@ŽlÈ@’rd@–wˆ@šw„@ž|¨@£6D@Ö¦(@Ú¼¤@ÞÁÈjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Windhoek0000644000175000017500000000022011564260547023606 0ustar ebourgebourgCLMTWASTSASTCATSWATWAT ÿ€€€¿m{Kx}甆% à) d@¢>ˆ@¡È@Ƽ@Ê¡Àw WASTwWATjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Banjul0000644000175000017500000000011711564260547023256 0ustar ebourgebourgPLMTGMTBMTWATÿ€¿ÿÿðd¿ÿÿðd¿’æž¿ÿÿðd¿ÿÿðd¿¾*'œ>>ÏÖ<joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Niamey0000644000175000017500000000010111564260547023256 0ustar ebourgebourgPLMTGMTWATÿ€€ü€ü¿’挄>>~àP¯»àjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Asmara0000644000175000017500000000013111564260547023243 0ustar ebourgebourgPLMTADMTAMTEATÿ€€$t€$t¿C茀$t€$t¿i†· €$h€$h¿À¯ò˜joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Johannesburg0000644000175000017500000000013411564260547024467 0ustar ebourgebourgCLMTSAST SAST-Summerÿ€@p@p}ŽÚ°}甆% à) d- `1 äjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Libreville0000644000175000017500000000005611564260547024136 0ustar ebourgebourgPLMTWATÿ€€Ü€Ü¿’æ…¤joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Khartoum0000644000175000017500000000044011564260547023634 0ustar ebourgebourgCCASTLMTCATEAT#ÿ€€€€€¿¶£Ú@¢ˆ@M¬@ ¢@RÌ@¬È@]Œ@¬H@b¬@"«È@&gÌ@*«H@.lì@2ªÈ@6w¬@:ªH@>|Ì@BÑ(@Fì@JШ@N‡ @RÐ(@V‘Ì@ZϨ@^–ì@bÏ(@fœ @jΨ@n¡,@rõˆ@v«ì@zõ@~± @ñ8joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Mbabane0000644000175000017500000000005711564260547023373 0ustar ebourgebourgPLMTSASTÿ€€(€(¿‚FÇXjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Sao_Tome0000644000175000017500000000007611564260547023555 0ustar ebourgebourgPLMTGMTÿ€€P€P¿^<ý0¿ÿÿ÷p¿ÿÿ÷p¿’æ—joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Lome0000644000175000017500000000005611564260547022741 0ustar ebourgebourgPLMTGMTÿ€€$€$¿o+Æ\joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Cairo0000644000175000017500000000165311564260547023106 0ustar ebourgebourgCLMTEESTEET}ÿ€@}@}}Ô8ÇH=ÌŒˆîŒ!Bè%ÚL)H-ûŒ1RÈ6L9¬H> lš¨«l¢T(¥°ŒªY„­°À²dDµ»€ºid½À Ân„ÅÅÀÊs¤ÍÊàÒ~dÕÕ Úƒ„ÝÚÀ∤åå€êÄíê ò˜„õõ`ú¤ýú€@¢Ä@ÿ @ §ä@À@²¤@€@·Ä@ @"¼ä@&À@*Â@.à@2ÌÄ@6) @:Ñä@>.À@B×@F3à@JÜ$@N9@Ræä@VCÀ@Zì@^Hà@dÏD@fN@l‹D@nS @s@v]à@{$@~c@ƒ D@†h @‹d@Žm@@“$@–x@›lAC¢(AEåLAFŽHAG,AK¡¨sÿEESTs ÿ@dEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Accra0000644000175000017500000000025311564260547023055 0ustar ebourgebourgCLMTGMTGHSTÿ€¿ÿÿÿÌ¿ÿÿÿÌ¿ž0f´~ô{ @~÷$,~ü€À@~ÿ)L…à@.l ‹@3Œ•À@>Lšà@Cl$ @'HŒjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Luanda0000644000175000017500000000010311564260547023242 0ustar ebourgebourgPLMTAOTWATÿ€€ h€ h¿mI6€ 4€ 4¿‘ÄxLjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Bamako0000644000175000017500000000007611564260547023241 0ustar ebourgebourgPLMTGMTWATÿ€ÿÿàÿÿà~.‚€~àOà>>³}üjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Bujumbura0000644000175000017500000000005611564260547024001 0ustar ebourgebourgPLMTCATÿ€€ˆ€ˆ¿i†¿øjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Lagos0000644000175000017500000000005611564260547023112 0ustar ebourgebourgPLMTWATÿ€€0€0¿¡QóPjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Bangui0000644000175000017500000000005611564260547023252 0ustar ebourgebourgPLMTWATÿ€€l€l¿’æ}joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Kampala0000644000175000017500000000013111564260547023405 0ustar ebourgebourgCLMTBEATEATBEAUTÿ€€d€d¿±îß~¾ú Olê€&€&¿çŒGcjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Douala0000644000175000017500000000005611564260547023252 0ustar ebourgebourgPLMTWATÿ€€ € ¿’æ…hjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Gaborone0000644000175000017500000000010211564260547023571 0ustar ebourgebourgCCASTLMTCATÿ€€L€L¿`p4- `1 äjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Lubumbashi0000644000175000017500000000005611564260547024140 0ustar ebourgebourgPLMTCATÿ€€À€À¿xM!@joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Djibouti0000644000175000017500000000005611564260547023616 0ustar ebourgebourgPLMTEATÿ€€(t€(t¿‘óÒ joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Malabo0000644000175000017500000000007211564260547023236 0ustar ebourgebourgPLMTGMTWATÿ€€<€<¿’æ†DÏv`joda-time-2.3/src/tz-data/org/joda/time/tz/data/Africa/Ouagadougou0000644000175000017500000000005611564260547024324 0ustar ebourgebourgPLMTGMTÿ€¿ÿÿþ”¿ÿÿþ”¿’æìjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/0000755000175000017500000000000012205344143022157 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Vienna0000644000175000017500000000072611564260550023335 0ustar ebourgebourgCLMTCESTCET:ÿ€€P€P¿o¢_0~QD¨~T¡„~Xö~\X\~`õœ~dWÜ~pÍ<~tVÜ9\%üü)7Ü-^ü1^¼5^|9^<9–|A¦ÜE<I~üM~¼QÍ<U~<@RZD@V2h@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Luxembourg0000644000175000017500000000142511564260550024243 0ustar ebourgebourgCWESTLMTCESTCETWETfÿ€€Ä€Ä¿„¢­¼~Q“h~T¡„~Y>ˆ~\Wä~`õœ~dWÜ~eá$~hÄ~lÈ~o³„~u=|~x[Ä~}MÜ~€žÄ~„í€~‰;Ä~Œí<~Å$~”ì€~˜ñ¤~œì~¡:D~¤ë€~©d~¬ë~±9D~µà~¹`$~½Ø~Á8ø~ÅX~É_Ø~ÍØ~ј~ÕX~Øè¸~Ý78~á6ø~å6¸~é~í68~ñ„¸~õ5¸~ù5x~ý58 ˜4¸ ƒ8GØo+x%üü)7Ü-^ü1^¼5¼9^<= œBk¼E„Ü@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Vilnius0000644000175000017500000000074111564260550023543 0ustar ebourgebourgC LMTKMTCESTMSKEESTCETEETWMTMSD5ÿ€€¼€¼¿V¶ÌD@T@T~V¦ì€h€h¿¡…J˜~rô~tèhòd %üü)7Ü-^ü1^¼4@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@¢UD@¦|d@ª|$@®| @²{à@¶{ @º{`@¾{ @Âzà@Æz @Êz`@Îz @Ò¡@@×>€@Ú À@ß>@â |@ç=¼@êŸü@ïdœA Å\AbœuÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Madrid0000644000175000017500000000122611564260550023311 0ustar ebourgebourgCWESTLMTCESTCETWETWEMTSÿ€¿ÿÿüŒ¿ÿÿüŒ¿~6¸t~Yf$~\Èd~`úÄ~dÍ„~hǤ~lÒ¤~‘*d~”ìD~¡:D~¤ëD~©d~¬êÄ~±9D~µ¤~¹`$~½$~úHd~ý4„öd4 ‚„ Zää„!öè$¥()§¨-^H1§(5h9¦¨=WäA¦(E\ÈZÈ]r@"]@&5¤@*ƒè@.5$@2 H@6 D@:4(@> Ä@B9H@F3¤@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Bucharest0000644000175000017500000000073511564260550024035 0ustar ebourgebourgCLMTEESTEETBMT9ÿ€€x€x¿lÏà€x€x¿·°Ò~Ò¨~Õh~Ù(~Ýè~á6~å5È~é5ˆ~í5H~ñ5~õ4È~ù4ˆ~ý4H43È 3ˆ 3H@Kn(@N2¬@RYÌ@V2h@Z2 @^2`@b2 @f1à@j1 @n1`@r1 @vX@@zX@~WÀ@‚W€@†W@@ŠW@ŽVÀ@’V€@–V@@šV@žUÀ@¢U€@¦| @ª{è@®{¨@²{h@¶{(@ºzè@¾z¨@Âzh@Æyì@Êyè@Îyl@Ò È@×=Ì@Ú ü@ß><uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Riga0000644000175000017500000000101511564260550022767 0ustar ebourgebourgC LMTCESTMSKRMTEESTCETEETLSTMSD7ÿ€€˜€˜¿V¶Íh€˜€˜¿ž¹ˆ€$¨€˜¿Ÿ„€˜€˜¿ ˆFˆ€$¨€˜¿ Ëƒ€˜€˜¿­çñèýh=l%üü)7Ü-^ü1^¼5^|5›ä@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žUÀ@¢U€@¦| @ª|`@®| @²{à@¶{ @º{`@¾{ @Âzà@Æz @Êz`@Îz @Ò¡@@Ö¡@Ú ü@ß><@â |@ç=¼@êŸü@ïdœ@úžü@ÿcœuÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Monaco0000644000175000017500000000146711564260550023334 0ustar ebourgebourgCWESTPMTLMTCESTCETWETWEMThÿ€€ì€ì¿kÈE”€1€1¿‘`PO~RB~T§$~Xyä~\Î~`*¤~dÍ„~hÄ~lÍ~o³„~u=~x[Ä~}Md~€žÄ~„íD~Ф~ŒìÄ~Å$~”ìD~˜ì~œëÄ~¡:D~¤ëD~©d~¬êÄ~±9D~µ¤~¹`$~½$~Á8D~Ť~É_$~Í$~Ñä~Õ¤~Øè~Ý6„~á6D~å6~éd~í5„~ñ„~õ5~ù4Ä~ý4„ ä4 ‚„G$oýD_H ÁÄ%üü)7Ü-^ü1^¼5Ä9^<= œ@2 À@6 D@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Warsaw0000644000175000017500000000123711564260550023357 0ustar ebourgebourgCLMTCESTEESTCETEETWMTTÿ€@T@T}-¶¬@T@T~KV ~QD¨~T¡„~Xö~\X\~`õœ~dWÜ~hú€~l\À~‚h <%üü)7Ü-^ü1^¼5i€9õ¤> ¨A¦dE„ÜJ|M~¼QÍ<U~<Y¥\]}¼›€ à¡  ¥ `«€­Ç@±ÇµÆÀ»€½Æ@ÃÅÅÀË€ÍÅ@Ó'`ÕÄÀ@:4 @> @B4 @F3à@J3 @N3`@RZ€@V2à@Z2 @^2`@b2 @f1à@j1 @n1`@r1 @vX@@zX@~WÀ@‚W€@†W@@ŠW@ŽVÀ@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Kiev0000644000175000017500000000055511564260550023013 0ustar ebourgebourgCLMTKMTCESTMSKEESTCETEETMSD&ÿ€€œ€œ¿V¶Çd€œ€œ¿ª§d~¼( %üü)7Ü-^ü.$@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@¤|„@²{h@¶zì@ºzè@¾zl@Âzh@Æyì@Êzœ@Îz\@Ò¡|@×>¼uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Paris0000644000175000017500000000146011564260550023167 0ustar ebourgebourgCWESTPMTLMTCESTCETWETWEMTgÿ€€1€1¿kÈJ‹€1€1¿‘`P‹~RB~T§$~Xyä~\Î~`*¤~dÍ„~hÄ~lÍ~o³„~u=~x[Ä~}Md~€žÄ~„íD~Ф~ŒìÄ~Å$~”ìD~˜ì~œëÄ~¡:D~¤ëD~©d~¬êÄ~±9D~µ¤~¹`$~½$~Á8D~Ť~É_$~Í$~Ñä~Õ¤~Øè~Ý6„~á6D~å6~éd~í5„~ñ„~õ5~ù4Ä~ý4„ ä4 ‚„G$oÞˆ%üü)7Ü-^ü1^¼4ˆ5Ä9^<= œ@2 À@6 D@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Prague0000644000175000017500000000077111564260550023340 0ustar ebourgebourgCPMTLMTCESTCET=ÿ€€ ˆ€ ˆ¿I’ø€ ˆ€ ˆ¿lÏêø~QD¨~T¡„~Xö~\X\~`õœ~dWÜ9\%üü)7Ü-^ü1^¼5 9ü>küB"œE<IͼM~¼QÍ<U~<YŸ¼]}¼@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Gibraltar0000644000175000017500000000160311564260550024017 0ustar ebourgebourgCLMTBSTGMTCESTCETBDSTuÿ€¿ÿÿúü¿ÿÿúü¿WÑ ~Q¶~T¢8~XÉX~\X˜~`z~d¦Ø~h ø~l¦X~p x~uCX~xÇX~|̸~€Ÿx~„íø~‰¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Belgrade0000644000175000017500000000050711564260550023617 0ustar ebourgebourgCLMTCESTCET&ÿ€@R@R}MÐΣ%üü)7Ü-^ü1^¼5^|:(¼= œ@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Vaduz0000644000175000017500000000045611564260550023206 0ustar ebourgebourgCLMTCESTCET"ÿ€€ì€ì¿qÔ”@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Rome0000644000175000017500000000127511564260550023017 0ustar ebourgebourgCLMTCESTRMTCETYÿ€€ ´€ ´¿=¾Ì€ ´€ ´¿p¼ƒÌ~Qþ„~T¡„~X¡D~\¡~`*¤~dÇä~hÄ~lÇd~pxd~tx$ÞÄ%üü)7Ü-^ü1^¼5 ¤9^<=„A \E<IdM~DP¹œU~<âþÄåÃHë%¤íÂÈó%$õÂHûLýé(@K„@è¨@ #¤@ èd@J„@@qd@ˆ@#I„@&@+pd@. Ä@3oä@6 D@;H@> Ä@Cnä@F3¤@Knd@N3$@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Amsterdam0000644000175000017500000000227211564260550024030 0ustar ebourgebourgCNSTLMTNETNESTCESTAMTCETcÿ€€”€”¿Ql€”€”¿› .쀤€”¿›ÕÖ\€”€”¿œÙ¸ €¤€”¿¤¿ €”€”¿ž§% €¤€”¿Ÿ— €”€”¿ AŒ€¤€”¿¡vø €”€”¿¢p#Œ€¤€”¿£VÚ €”€”¿¤PŒ€¤€”¿¥6¼ €”€”¿¦%[Œ€¤€”¿§'ÁŒ€”€”¿¨^㌀¤€”¿©£Œ€”€”¿©îZ €¤€”¿ªç…Œ€”€”¿¬'â €¤€”¿¬ÇgŒ€”€”¿­íf €¤€”¿®§IŒ€”€”¿¯Î™Œ€¤€”¿°‡+Œ€”€”¿±±Œ€¤€”¿²pH €”€”¿³’R €¤€”¿´P* €”€”¿µs…Œ€¤€”¿¶0 €”€”¿·T¹ €¤€”¿¸î €”€”¿¹@xŒ€¤€”¿¹ïÐ €”€”¿»qŒ€¤€”¿»ØìŒ€”€”¿¼ù¥ €¤€”¿½¸ÎŒ€”€”¿¾ÚØŒ€¤€”¿¿˜°Œ€”€”¿À½]Œ€¤€”¿Áx’Œ€”€”¿Â§ËŒ€¤€”¿ÂÜ]\@P@~ý5$@@!$@P@4¤@@ &D@P@ [„@@6,%üü)7Ü-^ü1^¼5^|9^<= œ@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Malta0000644000175000017500000000125011564260550023144 0ustar ebourgebourgCLMTCESTCETXÿ€€ œ€ œ¿p½Ód~Qþ„~T¡„~X¡D~\¡~`*¤~dÇä~hÄ~lÇd~pxd~tx$ÞÄ%üü)7Ü-^ü1^¼5^|9^<=„A \E<IdM~DP¹œU~<âþÄåÃHë%¤íÂÈó%$õÂHûLýé(@K„@è¨@ #¤@ èd@J„@@ d@ $@"„¤@%Å$@*„œ@-æ @2„@5æ @:ƒœ@=å @Bƒ@Eå @J‚œ@Mä @R8ü@V €@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Budapest0000644000175000017500000000107011564260550023655 0ustar ebourgebourgCLMTCESTCETHÿ€€ä€ä¿jî³~QD¨~T¡„~Xö~\X\~`§~d ü~húø~lW\~pÍx~t¶|Zœ%üü)7Ü-^ü1^¼5^|:H>èAXE<I~üM~¼Q~|U~<Y¥\]}¼aÑÜeøü‚¶…¡èŠ»$§“Ä• è›€¡@RZ€@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Helsinki0000644000175000017500000000052111564260550023654 0ustar ebourgebourgCLMTEESTEETHMT%ÿ€€h€h¿Sº&˜€h€h¿¤so!N(%SL@Z2 @^2`@b2 @f1à@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Samara0000644000175000017500000000103011564260550023306 0ustar ebourgebourgCKUYTLMTSAMSTSAMTKUYSTAÿ€€/€/¿¡&œ~»ì~ç«P@ZB @^G´@bG° @fLÔ@jLÐ @nQô@rW @vWÈ@zWˆ @~WH@‚W @†VÈ@ŠVˆ @ŽVH@’V @–UÈ@šUÄ@žU„@¢UD@¦|d@ª|`@®| @®ò@@²z´ @¶z8@ºzè @¾z¨@Âzh @Æz(@Êyè @Îy¨@Ò È @×>@Ú H @ß=ˆ@âŸÈ @ç=@êŸH @ïcè@òžÈ @÷ch@úžH @ÿbèAÅ( AbhA Ĩ AaèAÄ( AˆÈAè AˆHA"Ã( A'‡ÈA*¨ A/‡HA2éˆ A7†ÈA:é A?†HABèÄAG­dsÿSAMSTs ÿSAMTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Athens0000644000175000017500000000075011564260550023334 0ustar ebourgebourgCLMTCESTAMTEESTCETEET9ÿ€€<€<¿t?˜D€<€<¿›€!€~Ó&~Ô`Ì_ˆà¬%üü)=-^H1cäs†èv@,@*Vè@/Yh@2\€@6\@@:4 @> @B4 @F ¼@J5D@N-„@R=è@V2,@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Tallinn0000644000175000017500000000073511564260550023516 0ustar ebourgebourgCLMTMSKCESTEESTCETTMTEETMSD6ÿ€@c@c}-¶@c@c~_Z]~`õœ~dWÜ~j«d@c@c~ycýèì%üü)7Ü-^ü1^¼5%ˆ@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žUÀ@¢U€@¦| @ª|`@®| @²{à@¶{ @º{`@¾{ @Âzà@Æz @Êz`@Îz @Ò¡@@×>€@Ú À@ß>@â @@ç=¼@êŸü@ïdœAÅÜAcuÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Brussels0000644000175000017500000000146111564260550023714 0ustar ebourgebourgCWESTLMTCESTCETWETBMThÿ€€€¿V¶ß怀¿mél¦~Eg ~QDä~T¡„~Xö~\X\~`õœ~dWÜ~e•4~hÄ~lÇd~o³„~u=~x[Ä~}Md~€žÄ~„íD~‰;Ä~ŒìÄ~Å$~”ìD~˜ì~œëÄ~¡:D~¤ëD~©d~¬êÄ~±9D~µX~¹`Ø~½Ø~Á8ø~ÅX~É_Ø~ÍØ~ј~ÕX~Øè¸~Ý78~á6ø~å6¸~é~í68~ñ„¸~õ5¸~ù5x~ý58 ˜4¸ ƒ8GØoM8%üü)7Ü-^ü1^¼5 9^<= œBk¼E„Ü@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Uzhgorod0000644000175000017500000000054611564260550023716 0ustar ebourgebourgCLMTMSKCESTEESTCETEETMSD'ÿ€€è€è¿jî°9\%üü)7Ü-^ü1^¼5äÈ;LÄ@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@¤|„@ª|Ø@²{h@¶zì@ºzè@¾zl@Âzh@Æyì@Êzœ@Îz\@Ò¡|@×>¼uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/London0000644000175000017500000000224411564260550023343 0ustar ebourgebourgCLMTBSTGMTBDST ÿ€¿ÿÿÿµ¿ÿÿÿµ¿] Ë~Q¶~T¢8~XÉX~\X˜~`z~d¦Ø~h ø~l¦X~p x~uCX~xÇX~|̸~€Ÿx~„íø~‰ªø@AåØ@FÑØ@IåX@NÑX@QäØ@VÐØ@Z2Ü@^Ð@b2\@fÏœ@j1Ü@nÏ@r1\@võü@zX<@~õ|@‚W¼@†ôü@ŠW<@Žô|@’V¼@–óü@šV<@ŸÜ@¢U¼@§\@ª|œ@¯Ü@²|@·\@º{œ@¿Ü@Â{@Ç\@Êzœ@ÏÜ@Ò¡|@×>¼uÿBSTu ÿGMTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Sofia0000644000175000017500000000064211564260550023153 0ustar ebourgebourgCLMTCESTEESTCETEETIMT/ÿ€€Ü€Ü¿V¶Î$€h€h¿rÃã%üü)7Ü-^ü1^¼5^|9^x@J2ì@N8ˆ@RYÌ@V8@ZYL@^2$@bXÌ@f1à@j1 @n1`@r1 @vX@@zX@~WÀ@‚W€@†W@@ŠW@ŽVÀ@’V€@–V@@šV@žUÀ@¢U€@¦| @ª{è@®{l@²{h@¶zì@ºzè@¾zl@Âzh@Æyì@Êyè@Îyl@Ò È@×=Ì@Ú ü@ß><uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Oslo0000644000175000017500000000074111564260550023026 0ustar ebourgebourgCLMTCESTCET<ÿ€@+@+}¦5~Q»@~T›¨(%üü)7Ü-^ü1^¼5^|9^<=]ü©Qœ­x¼±x|µx<¹wü½w¼Áw|Åw<ÉvüÍv¼Ñv|ÕœÚb<Ý@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Zurich0000644000175000017500000000053711564260550023361 0ustar ebourgebourgCLMTCESTCETBMT'ÿ€€€¿Ö€€ø€ø¿qÔˆý€_À!ý%_@@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Tirane0000644000175000017500000000065411564260550023337 0ustar ebourgebourgCLMTCESTCET4ÿ€€˜€˜¿–ª4häd%üü)7Ü){\@"ÍÄ@&è@*Â@.$@2Òd@64h@:ùD@>3è@Bó$@F3h@Jò¤@N2è@Rò$@VT(@ZÏä@^1è@böÄ@fXÈ@j­$@nR¨@rXD@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Andorra0000644000175000017500000000040211564260550023472 0ustar ebourgebourgCLMTCESTCETWETÿ€€l€l¿~6³”E]@@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Berlin0000644000175000017500000000077011564260550023327 0ustar ebourgebourgCLMTCESTCEMTCET>ÿ€€ ˆ€ ˆ¿o¢aø~QD¨~T¡„~Xö~\X\~`õœ~dWÜ9\%üü)7Ü-^ü1^¼5^|9^<:‚¼=6`>küA¦ÜE„ÜI8JCÜKW@M~¼QÍ<U~<Y¥\]}¼@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Dublin0000644000175000017500000000212511564260550023325 0ustar ebourgebourgCLMTBSTGMTISTDMT’ÿ€ÿÿçÿÿç}2jÙ¿ÿÿú¿ÿÿú¿›&³‘€¿ÿÿú¿›Ö ~XÉX~\X˜~`z~d¦Ø~h ø~l¦X~p x~uCX~xÇX~|̸~€Ÿx~„íø~‰ªø@AåØ@FÑØ@IåX@NÑX@QäØ@VÐØ@Z2Ü@^Ð@b2\@fÏœ@j1Ü@nÏ@r1\@võü@zX<@~õ|@‚W¼@†ôü@ŠW<@Žô|@’V¼@–óü@šV<@ŸÜ@¢U¼@§\@ª|œ@¯Ü@²|@·\@º{œ@¿Ü@Â{@Ç\@Êzœ@ÏÜ@Ò¡|@×>¼uÿISTu ÿGMTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Stockholm0000644000175000017500000000053711564260550024060 0ustar ebourgebourgCLMTSETCESTCET'ÿ€€ì€ì¿TÕŸ”€€¿|Usb~Q“h~T¡„@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Zaporozhye0000644000175000017500000000057711564260550024273 0ustar ebourgebourgCLMTCESTMSKEESTCETEETCUTMSD)ÿ€€ ø€ ø¿V¶Ã@Œ@Œ~‘~t~¼(rÌ%üü)7Ü-^ü-Ô¤@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@¢UD@¦|d@ª|$@®{l@²{h@¶zì@ºzè@¾zl@Âzh@Æyì@Êzœ@Îz\@Ò¡|@×>¼uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Kaliningrad0000644000175000017500000000066011564260550024335 0ustar ebourgebourgCLMTMSKCESTEESTCETEETMSD2ÿ€@R@R}˜ ~QD¨~T¡„~Xö~\X\~`õœ~dWÜ9\%üü)7Ü-^ü1^¼5^|7]ä9õh> l?bÈ@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@¢UD@¦|d@ª|`@®| @²{,@¶z°@º{`@¾{ @Âzà@Æz @Êz`@Îz @Ò¡@@×>€sÿEESTs ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Minsk0000644000175000017500000000057011564260550023173 0ustar ebourgebourgCLMTCESTMSKEESTCETEETMMTMSD(ÿ€€Ø€Ø¿V¶Ê(@n@n~‘~’~¼(,Œ%üü)7Ü-^ü1^¼3]è@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@ª|$@®| @²{h@¶{(@º{`@¾{ @Âzà@Æz @Êz`@Îz @Ò¡@@×>€sÿEESTs ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Moscow0000644000175000017500000000074611564260550023366 0ustar ebourgebourgCLMTMSKEESTEETMMTMDSTMSTMSD1ÿ€€#<€#<¿V¶ÀÄ~R¦ê€#X€#X¿>ò˜€1h€#X¿ž*ï€#X€#X¿ž÷9ˆ€?x€#X¿Ÿ„X€1h€#X¿ Øm€?x€#X¿¡(~k­p~w½~x|” ~|~|À~„Ål~¼(@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@¢UD@¦|d@ª|`@®| @°ò @²zð@¶zt@º{$@¾zä@Âz¤@Æzd@Êz$@Îyä@Ò¡@×>DsÿMSDs ÿMSKjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Lisbon0000644000175000017500000000205411564260550023337 0ustar ebourgebourgCWESTLMTCESTCETWETWEMTÿ€¿ÿÿ÷p¿ÿÿ÷p¿’æ—~RRä~UP ~Wòä~\õd~_ý¤~dú„~gý$~lÿ¤~pä~u d~x ~}„~‘*d~•$„~¡:D~¤ëD~©d~¬êÄ~±9D~µ¤~¹`$~½$~É_$~Í$~Ñä~Õ¤~á6D~å6~éd~í5„~ñ„~õ5~ù4Ä~ý4„ ä4 ‚„G$ndZdZ$_„ ã„!ψ$Eˆ%Ï„(ã)§¨,“È-öd0â„1Έ4“H5õä8â9Î<’È=õdAE~ÄI8M~øQ~¸U~xY~8]}øi}8m¤Xq¤u£Øy£˜}£X£…¢Ø‰¢˜¢X‘¢•É8™Èøȸ¡Èx¥È8©Çø­Ç¸±ÇxµÇ8¹Æø½Æ¸ÁÆxÅí˜ÉíXÍíÑìØÕì˜ÙìXÝìáëØ@6 €@: @@> @B4 @F3à@J3 @N3œ@R3 @V3@Z2Ü@^2œ@b2\@f2@j2@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼@Ú üuÿWESTu ÿWETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Volgograd0000644000175000017500000000051411564260550024034 0ustar ebourgebourgCSTATLMTVOLSTTSATVOLT$ÿ€€)¤€)¤¿¡õFÜ~˜ñ,~»ì¾«ð@ZB @^G´@bG° @fLÔ@jLÐ @nQô@rW @vWÈ@zWˆ @~WH@‚W @†VÈ@ŠVˆ @ŽVH@’V @–UÈ@šUÄ@žU„@¢UD@¦|d@ª|$@²{h@¶zt@º{$@¾zä@Âz¤@Æzd@Êz$@Îyä@Ò¡@×>DsÿVOLSTs ÿVOLTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Copenhagen0000644000175000017500000000070111564260550024155 0ustar ebourgebourgCLMTCMTCESTCET5ÿ€€ Ì€ Ì¿i†Ï´€ Ì€ Ì¿q ï4~Q“h~T¡ 0d%üü)7Ü-^ü1^¼5^|9^<¼uÿCESTu ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Chisinau0000644000175000017500000000102211564260550023646 0ustar ebourgebourgC LMTCMTMSKCESTEESTCETEETBMTMSD<ÿ€€€¿V¶Èø@s@s~_© €x€x¿·°Ò~Ò¨~Õh~Ù(~Ýè~á6~å5È~é5ˆ~í5H~ñ5~õ4È~ù4ˆ~ý4H43È 3ˆ 3H5¨—l%üü)7Ü-^ü1^¼4‚h@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@£A @ª|`@®| @²{h@¶zì@ºzè@¾zl@Âzh@Æyì@Êyè@Îyl@Ò È@×=Ì@Ú ü@ß><uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Istanbul0000644000175000017500000000155111564260550023673 0ustar ebourgebourgCTRTLMTTRSTEESTEETIMTpÿ€€(€(¿V¶ÈØ€h€h¿‹õ˜~QD¨~T¡ ~pŸˆ~uB,~xÆh~|ËŒ~€žˆ~„ìÌ~‘¼h~”ÕL~™~~œÚl2èTL•( ¬!Bè%öl9]ˆ=„lB´(Eb,IÍM}ÌQ̈U}LY¤¨]|ÌaÜhe£¬iòhm¨ÌÄ(Åò ÒÌèÕÚŒ@­È@Ì@ ­H@L@Ô(@6,@qd@Óà@"À@&ÓØ@* È@.ªÌ@3zè@6Ѭ@:4(@>‚l@B3¨@Fì@N†Ð@RZ€@V†P@Z2 @^…Ð@b2 @f…P@lõ¬@nWÐ@zÈ@~Ql@‚W€@†W@@ŠW@ŽVÀ@’V€@–V@@šV@žUÀ@¢U€@¦| @ª|$@®{ä@²{¤@¶{d@º{$@¾zä@Âz¤@Æzd@Êz$@Îyä@Ò¡@×>D@Ú „@ß=Ä@â @ç=D@Ꞔ@ïd$@òŸ@÷c¤@úž„@ÿc$AÅdAb¤A ÄäAb$AÄdA‰AÃäAˆ„A"ÃdA'ˆA*Ã\A/‡üuÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Europe/Simferopol0000644000175000017500000000061511564260550024231 0ustar ebourgebourgCLMTCESTMSKEESTCETEETMSDSMT+ÿ€€ø€ø¿V¶Ä@ˆ@ˆ~‘~x~¼(ñL%üü)7Ü-^ü1^¼1–H@ZBÌ@^Gð@bGì@fM@jM @nR0@rWÌ@vX@zWÄ@~W„@‚WD@†W@ŠVÄ@ŽV„@’VD@–V@šUÄ@žU„@¤|„@²{h@¶zì@ºzè@¾zl@Âzh@Ã? @Æy°@Êy¬@Îy0@Ò Œ@×>€@Ú ü@ß><@â |uÿEESTu ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/PST8PDT0000644000175000017500000000126011564260550021756 0ustar ebourgebourgCPWTPDTPSTPPTZÿ€00~`£X20~e@\00~h¢Ø20~m?Ü00 &Ø20Óü00@BÓø20@FÓ|00@JÓx20@NÒü00@RÒø20@VÒ|00@ZÒx20@^Ñü00@bÑø20@føÜ00@jÑx20@nø\00@røX20@v÷Ü00@z÷Ø20@~÷\00@‚÷X20@†öÜ00@Š€¸20@Žö\00@’€820@—<00@š¸20@Ÿ¼00@¢820@§<00@ª¦20@¯¼00@²¥˜20@·<00@º¥20@¿B00@¤˜20@ÇAœ00@ʤ20@ÏA00@ÒÊø20@×@œ00@ÚÊx20@ß@00@âÉø20@ç?œ00@êÉx20@ïf|00@òÈø20@÷eü00@úÈx20@ÿe|00AïX20Adü00A îØ20Ad|00AîX20A‹\00AíØ20AŠÜ00A"íX20A'Š\00A*v¸20A/±<000wPDTw PSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/EST0000644000175000017500000000001011564260550021273 0ustar ebourgebourgFEST66joda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/0000755000175000017500000000000012205344143022771 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Macquarie0000644000175000017500000000127511564260547024644 0ustar ebourgebourgCzzzMISTEST`ÿ€~&}@~TŸà~XxG@!0d%0`)/ä-W@1/díèÀñè€ö…Àùqàþ…@@q`@„À@ ˜@@« @I@« @oà@ª @!o`@&ª @)nà@.© @1•À@6Ѐ@9•@@>Ð@A”À@FÏ€@I”@@NÏ@Q“À@V΀@Y“@@^Î@b0@@fôà@j/À@nô`@q¹ @vóà@y¸ @~ó`@¸ @†Ë€@Š`@Žò`@’-@@—@@š,À@ŸÀ@¢,@@§@@ªz€@®¡ @²z@¶¡ @ºy€@¾  @Ây@Æ  @Êx€@Ο @ÒŸ`@ÖÆ€@Úžà@ÞÆ@âž`@æÅ€@êà@îÅ@ò`@õÿ @úœà@þë`AÃÀAêàA Ã@Aê`AÂÀAéàAÂ@Aé`A"é A&èàA*Á@A/ÀA3€A7@A;A?ÀAC€joda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Davis0000644000175000017500000000010211564260547023767 0ustar ebourgebourgCzzzDAVTÿ€—ðÖ‡üø©@A?^4 ABˆpjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Palmer0000644000175000017500000000064711564260547024157 0ustar ebourgebourgCCLTARSTARTzzzCLST3ÿ€×àÀ:8Ù-T88Þ0:8á2t88æ50:8éë”88íë:8òt88öp:8úô88þð::@ –”<:@"½˜::@bò88@f:8@iã”88@n:8@qã88@v§ð:8@yâ”88@~§p:8@â88@†¦ð:8@Цt88@ަp:8@’t88@–~:8@šô88@žÌÐ:8@¢.Ô88@¦.Ð:8@ªô88@®ËÐ:8@²-Ô88@¶ËP:8@º-T88@¾ÊÐ:8@Â,Ô88@ÆÊP:8@Ê,T88@Îñ0:8@Ò+Ô88@Öð°:8@Ú¡t88@Þð0:8@âR488@æ ð:8@êÇÔ88@îï0:8@òQ4888u CLSTu CLTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/McMurdo0000644000175000017500000000104311564260547024274 0ustar ebourgebourgCNZSTzzzNZDTFÿ€¡À@&Ñ@)G@.©(@1•H@6Ð@9”È@>ψ@A”H@FÏ@I“È@NΈ@Q“H@VÎ@Y’È@^͈@a¹¨@fôh@i¹(@nóè@q¸¨@vóh@y¸(@~òè@·¨@†òh@‰·(@Žñè@‘Þ@—È@™Ýˆ@ž¢(@¢+È@¦¡¨@ª+H@®¡(@²*È@¶ ¨@ºQ¨@¾ (@ÂQ(@ÆŸ¨@ÊP¨@Ο(@ÒP(@ÖÆ@ÚO¨@Þň@âO(@æÅ@êv@îĈ@òuˆ@öÄ@úu@þêèAtˆAêhA tAéèAšèAéhAšhAèèA"™èA&èhA*™hA.çèA3s ÿNZDTsNZSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Casey0000644000175000017500000000007111564260547023772 0ustar ebourgebourgCCASTWSTzzzÿ€÷úàA?]øABe„joda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Vostok0000644000175000017500000000004611564260547024215 0ustar ebourgebourgPzzzVOSTÿ€ŸW  joda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/DumontDUrville0000644000175000017500000000007111564260547025643 0ustar ebourgebourgPPMTzzzDDUTÿ€Gh`oÎh–U`joda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Rothera0000644000175000017500000000004611564260547024334 0ustar ebourgebourgPzzzROTTÿ€@7€À::joda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Syowa0000644000175000017500000000004611564260547024032 0ustar ebourgebourgPSYOTzzzÿ€˜Jjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Antarctica/Mawson0000644000175000017500000000005511564260547024174 0ustar ebourgebourgPMAWTzzzÿ€€‰` A?^p joda-time-2.3/src/tz-data/org/joda/time/tz/data/CET0000644000175000017500000000066311564260550021271 0ustar ebourgebourgCCESTCET7ÿ€~QD¨~T¡„~Xö~\X\~`õœ~dWÜ9\%üü)7Ü-^ü1^¼5^|9^<= œ@:4Ü@> <@B4\@F4@J3Ü@N3œ@RZ¼@V3@Z2Ü@^2œ@b2\@f2@j1Ü@n1œ@r1\@vX|@zX<@~Wü@‚W¼@†W|@ŠW<@ŽVü@’V¼@–V|@šV<@žUü@¢U¼@¦|Ü@ª|œ@®|\@²|@¶{Ü@º{œ@¾{\@Â{@ÆzÜ@Êzœ@Îz\@Ò¡|@×>¼sÿCESTs ÿCETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/0000755000175000017500000000000012205344143022256 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Marquesas0000644000175000017500000000005411564260550024147 0ustar ebourgebourgPLMTMARTÿ€ÿýÒÿýÒ~4‰Î--joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Rarotonga0000644000175000017500000000035311564260550024144 0ustar ebourgebourgCLMTCKHSTCKTÿ€¿ÿÿj8¿ÿÿj8¿~7JÈ++@G"–-,@I˜Z,,@NÓ8-,@Q—Ú,,@VÒ¸-,@Y—Z,,@^Ò8-,@a¾:,,@fù-,@i½º,,@nø˜-,@q½:,,@vø-,@y¼º,,@~÷˜-,@¼:,,@†÷-,@‰»º,,@Žö˜-,@‘âš,,@—x-,@™â,,@Ÿø-,@¡áš,,@§x-,@©á,,joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Pohnpei0000644000175000017500000000005711564260550023613 0ustar ebourgebourgPLMTPONTÿ€€”T€”T¿~6 ¬joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Wallis0000644000175000017500000000005611564260550023443 0ustar ebourgebourgPLMTWFTÿ€€¬X€¬X¿~6¨joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Guadalcanal0000644000175000017500000000005611564260550024404 0ustar ebourgebourgPLMTSBTÿ€€•ô€•ô¿”O3Œjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Kosrae0000644000175000017500000000007511564260550023435 0ustar ebourgebourgPLMTKOSTÿ€€˜Ì€˜Ì¿~64ý÷ì@è¹0joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Nauru0000644000175000017500000000011011564260550023271 0ustar ebourgebourgPLMTJSTNRTÿ€€œ|€œ|¿£ç+ á4N$@JÙ®joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Tahiti0000644000175000017500000000005711564260550023433 0ustar ebourgebourgPTAHTLMTÿ€¿ÿÿsÈ¿ÿÿsÈ¿”PU¸,,joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Kwajalein0000644000175000017500000000010211564260550024105 0ustar ebourgebourgPLMTKWATMHTÿ€€œà€œà¿~6 ý÷ì((@½­Ðjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Kiritimati0000644000175000017500000000010311564260550024307 0ustar ebourgebourgPLMTLINTÿ€¿ÿÿl€¿ÿÿl€¿~7H€ÿý€ÿý€@N;€,,@Ȥ8joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Midway0000644000175000017500000000013111564260550023434 0ustar ebourgebourgCNSTNDTLMTBSTSSTÿ€¿ÿÿY¸¿ÿÿY¸¿~7[H**“”,*•8**éçÔ**@o§4**joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Norfolk0000644000175000017500000000010011564260550023610 0ustar ebourgebourgPLMTNFTNMTÿ€€x€x¿~6ˆ@ @ gàjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Chatham0000644000175000017500000000172711564260550023563 0ustar ebourgebourgCLMTCHASTCHADTFÿ€€«ü€«ü¿ç‹Â@ý@ý@&Ñ@9@ý@)G@ý@ý@.©(@9@ý@1•H@ý@ý@6Ð@9@ý@9”È@ý@ý@>ψ@9@ý@A”H@ý@ý@FÏ@9@ý@I“È@ý@ý@NΈ@9@ý@Q“H@ý@ý@VÎ@9@ý@Y’È@ý@ý@^͈@9@ý@a¹¨@ý@ý@fôh@9@ý@i¹(@ý@ý@nóè@9@ý@q¸¨@ý@ý@vóh@9@ý@y¸(@ý@ý@~òè@9@ý@·¨@ý@ý@†òh@9@ý@‰·(@ý@ý@Žñè@9@ý@‘Þ@ý@ý@—È@9@ý@™Ýˆ@ý@ý@ž¢(@9@ý@¢+È@ý@ý@¦¡¨@9@ý@ª+H@ý@ý@®¡(@9@ý@²*È@ý@ý@¶ ¨@9@ý@ºQ¨@ý@ý@¾ (@9@ý@ÂQ(@ý@ý@ÆŸ¨@9@ý@ÊP¨@ý@ý@Ο(@9@ý@ÒP(@ý@ý@ÖÆ@9@ý@ÚO¨@ý@ý@Þň@9@ý@âO(@ý@ý@æÅ@9@ý@êv@ý@ý@îĈ@9@ý@òuˆ@ý@ý@öÄ@9@ý@úu@ý@ý@þêè@9@ýAtˆ@ý@ýAêh@9@ýA t@ý@ýAéè@9@ýAšè@ý@ýAéh@9@ýAšh@ý@ýAèè@9@ýA"™è@ý@ýA&èh@9@ýA*™h@ý@ýA.çè@9@ýA3@ý@ý@ýs ÿ@¥CHADTs@¥CHASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Tongatapu0000644000175000017500000000015311564260550024150 0ustar ebourgebourgCLMTTOTTOST ÿ€€­H€­H¿~6¸@ä@äA@îÚÌ@òuL@÷ˆ¬@ù`ð@ÿˆ,A`pjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Efate0000644000175000017500000000030011564260550023224 0ustar ebourgebourgCLMTVUSTVUTÿ€€Ì€Ì¿’õ´@n.Ì@r.P@v× @z-Ð@~U,@‚-P@†T¬@ŠT0@ŽT,@’S°@–S¬@šS0@žS,@¢R°@¦R¬@ªR0@®yŒ@±°@·Œ@¹0joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Gambier0000644000175000017500000000005711564260550023557 0ustar ebourgebourgPLMTGAMTÿ€¿ÿÿ|¿ÿÿ|¿”PH..joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Auckland0000644000175000017500000000135711564260550023737 0ustar ebourgebourgCNZSTLMTNZDTNZMTaÿ€€£Ø€£Ø¿A·L¨~­­¦~°JÊ~µ7~¸™(~½6†~À˜¨~Å6~Ș(~Í5†~п~Õ5~ؾˆ~Ý4†~áªH~å ¦~é©È~í &~ñ©H~õ ¦~ù¨È~ý &¨H ¦ Ï( &Ψ1@&Ñ@)G@.©(@1•H@6Ð@9”È@>ψ@A”H@FÏ@I“È@NΈ@Q“H@VÎ@Y’È@^͈@a¹¨@fôh@i¹(@nóè@q¸¨@vóh@y¸(@~òè@·¨@†òh@‰·(@Žñè@‘Þ@—È@™Ýˆ@ž¢(@¢+È@¦¡¨@ª+H@®¡(@²*È@¶ ¨@ºQ¨@¾ (@ÂQ(@ÆŸ¨@ÊP¨@Ο(@ÒP(@ÖÆ@ÚO¨@Þň@âO(@æÅ@êv@îĈ@òuˆ@öÄ@úu@þêèAtˆAêhA tAéèAšèAéhAšhAèèA"™èA&èhA*™hA.çèA3s ÿNZDTsNZSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Palau0000644000175000017500000000005611564260550023252 0ustar ebourgebourgPLMTPWTÿ€€~€~¿~66ìjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Fiji0000644000175000017500000000015411564260550023070 0ustar ebourgebourgCFJTLMTFJST ÿ€€§D€§D¿š²<@çbˆ@éÿè@ï‰h@ñÿhA@IHABæ¨AGƒèAJpjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Pitcairn0000644000175000017500000000007211564260550023757 0ustar ebourgebourgPLMTPSTPNTÿ€¿ÿÿ† ¿ÿÿ† ¿~7.ô//@ãE^00joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Chuuk0000644000175000017500000000005711564260550023270 0ustar ebourgebourgPLMTCHUTÿ€€ŽL€ŽL¿~6&´joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Wake0000644000175000017500000000005711564260550023100 0ustar ebourgebourgPLMTWAKTÿ€€œ4€œ4¿~6Ìjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Noumea0000644000175000017500000000013611564260550023433 0ustar ebourgebourgCLMTNCTNCSTÿ€€œ €œ ¿’õÄt@?”,@Ar@G“¬@Iw0@ØD@Ú$joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Saipan0000644000175000017500000000011411564260550023416 0ustar ebourgebourgPChSTLMTMPTÿ€ÿü§ÿü§|ÔY@G@G}Ö\°42@A¾´22@Fƒ42@I¾422@Nƒ42@Q½´22@V‚42@Yä”22@^‚42@aä44@f64@iã”44@n64@qã44@v§ð64@yâ”44@~§p64@â44@†¦ð64@Цt44@ަp64@’t44@–~64@šô44@žÌÐ64@¢.Ô44@¦.Ð64@ªô44@®ËÐ64@²-Ô44@¶ËP64@º-T44@¾ÊÐ64@Â,Ô44@ÆÊP64@Ê,T44@Îñ064@Ò+Ô44@Öð°64@Ú¡t44@Þð064@âR444@æ ð64@êÇÔ44@îï064@òQ444@÷64@úP´44@ÿ64AP444A64A O´44A64Av”44A64Av44A64A"u”44A':p64A*u44A/9ð64A2ê´44A79p64A:›t44A?8ð64AC44AG8p64AJšt444u EASSTu EASTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Niue0000644000175000017500000000010211564260550023100 0ustar ebourgebourgPLMTNUTÿ€¿ÿÿ`´¿ÿÿ`´¿~7TLÿýXÿýXg…())@F6’**joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Galapagos0000644000175000017500000000007311564260551024106 0ustar ebourgebourgPLMTECTGALTÿ€¿ÿÿ¬¿ÿÿ¬¿¶¤L€66@€i¬44joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Port_Moresby0000644000175000017500000000010411564260550024626 0ustar ebourgebourgPLMTPGTPMMTÿ€€‰ø€‰ø¿V¶Z€‰ð€‰ð¿rí¤joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Enderbury0000644000175000017500000000007511564260550024150 0ustar ebourgebourgPLMTPHOTÿ€¿ÿÿ_œ¿ÿÿ_œ¿~7Ud((@N;Ð**@Ȥtjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Funafuti0000644000175000017500000000005611564260550023771 0ustar ebourgebourgPLMTTVTÿ€€¨€¨¿~6 üjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Johnston0000644000175000017500000000001011564260550024000 0ustar ebourgebourgFHST,,joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Fakaofo0000644000175000017500000000005611564260550023556 0ustar ebourgebourgPLMTTKTÿ€¿ÿÿ_x¿ÿÿ_x¿~7Uˆ,,joda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Majuro0000644000175000017500000000006511564260550023445 0ustar ebourgebourgPLMTMHTÿ€€ €€ €¿~6€ý÷ìjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Pacific/Honolulu0000644000175000017500000000014711564260551024017 0ustar ebourgebourgCHSTLMTHWTHPTHDTÿ€¿ÿÿl¿ÿÿl¿|V¾>++~Ù°-+~Ú%ò++ 'n-+>joda-time-2.3/src/tz-data/org/joda/time/tz/data/ZoneInfoMap0000644000175000017500000002630311564260551023043 0ustar ebourgebourg7Africa/Abidjan Africa/AccraAfrica/Addis_AbabaAfrica/Algiers Africa/Asmara Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/BissauAfrica/BlantyreAfrica/BrazzavilleAfrica/Bujumbura Africa/CairoAfrica/Casablanca Africa/CeutaAfrica/Conakry Africa/DakarAfrica/Dar_es_SalaamAfrica/Djibouti Africa/DoualaAfrica/El_AaiunAfrica/FreetownAfrica/Gaborone Africa/HarareAfrica/JohannesburgAfrica/KampalaAfrica/Khartoum Africa/KigaliAfrica/Kinshasa Africa/LagosAfrica/Libreville Africa/Lome Africa/LuandaAfrica/Lubumbashi Africa/Lusaka Africa/Malabo Africa/Maputo Africa/MaseruAfrica/MbabaneAfrica/MogadishuAfrica/MonroviaAfrica/NairobiAfrica/Ndjamena Africa/NiameyAfrica/NouakchottAfrica/OuagadougouAfrica/Porto-NovoAfrica/Sao_TomeAfrica/TimbuktuAfrica/Tripoli Africa/TunisAfrica/Windhoek America/AdakAmerica/AnchorageAmerica/AnguillaAmerica/AntiguaAmerica/AraguainaAmerica/Argentina/Buenos_AiresAmerica/Argentina/Catamarca America/Argentina/ComodRivadaviaAmerica/Argentina/CordobaAmerica/Argentina/JujuyAmerica/Argentina/La_RiojaAmerica/Argentina/MendozaAmerica/Argentina/Rio_GallegosAmerica/Argentina/SaltaAmerica/Argentina/San_JuanAmerica/Argentina/San_LuisAmerica/Argentina/TucumanAmerica/Argentina/Ushuaia America/ArubaAmerica/AsuncionAmerica/Atikokan America/Atka America/BahiaAmerica/Bahia_BanderasAmerica/Barbados America/BelemAmerica/BelizeAmerica/Blanc-SablonAmerica/Boa_VistaAmerica/Bogota America/BoiseAmerica/Buenos_AiresAmerica/Cambridge_BayAmerica/Campo_GrandeAmerica/CancunAmerica/CaracasAmerica/CatamarcaAmerica/CayenneAmerica/CaymanAmerica/ChicagoAmerica/ChihuahuaAmerica/Coral_HarbourAmerica/CordobaAmerica/Costa_RicaAmerica/CuiabaAmerica/CuracaoAmerica/DanmarkshavnAmerica/DawsonAmerica/Dawson_CreekAmerica/DenverAmerica/DetroitAmerica/DominicaAmerica/EdmontonAmerica/EirunepeAmerica/El_SalvadorAmerica/EnsenadaAmerica/TijuanaAmerica/Fort_WayneAmerica/Indiana/IndianapolisAmerica/FortalezaAmerica/Glace_BayAmerica/GodthabAmerica/Goose_BayAmerica/Grand_TurkAmerica/GrenadaAmerica/GuadeloupeAmerica/GuatemalaAmerica/GuayaquilAmerica/GuyanaAmerica/HalifaxAmerica/HavanaAmerica/HermosilloAmerica/Indiana/KnoxAmerica/Indiana/MarengoAmerica/Indiana/PetersburgAmerica/Indiana/Tell_CityAmerica/Indiana/VevayAmerica/Indiana/VincennesAmerica/Indiana/WinamacAmerica/IndianapolisAmerica/InuvikAmerica/IqaluitAmerica/Jamaica America/JujuyAmerica/JuneauAmerica/Kentucky/LouisvilleAmerica/Kentucky/MonticelloAmerica/Knox_INAmerica/La_Paz America/LimaAmerica/Los_AngelesAmerica/LouisvilleAmerica/MaceioAmerica/ManaguaAmerica/ManausAmerica/MarigotAmerica/MartiniqueAmerica/MatamorosAmerica/MazatlanAmerica/MendozaAmerica/MenomineeAmerica/MeridaAmerica/Mexico_CityAmerica/MiquelonAmerica/MonctonAmerica/MonterreyAmerica/MontevideoAmerica/MontrealAmerica/MontserratAmerica/NassauAmerica/New_YorkAmerica/Nipigon America/NomeAmerica/NoronhaAmerica/North_Dakota/CenterAmerica/North_Dakota/New_SalemAmerica/OjinagaAmerica/PanamaAmerica/PangnirtungAmerica/ParamariboAmerica/PhoenixAmerica/Port-au-PrinceAmerica/Port_of_SpainAmerica/Porto_AcreAmerica/Rio_BrancoAmerica/Porto_VelhoAmerica/Puerto_RicoAmerica/Rainy_RiverAmerica/Rankin_InletAmerica/RecifeAmerica/ReginaAmerica/ResoluteAmerica/RosarioAmerica/Santa_IsabelAmerica/SantaremAmerica/SantiagoAmerica/Santo_DomingoAmerica/Sao_PauloAmerica/ScoresbysundAmerica/ShiprockAmerica/St_BarthelemyAmerica/St_JohnsAmerica/St_KittsAmerica/St_LuciaAmerica/St_ThomasAmerica/St_VincentAmerica/Swift_CurrentAmerica/Tegucigalpa America/ThuleAmerica/Thunder_BayAmerica/TorontoAmerica/TortolaAmerica/VancouverAmerica/VirginAmerica/WhitehorseAmerica/WinnipegAmerica/YakutatAmerica/YellowknifeAntarctica/CaseyAntarctica/DavisAntarctica/DumontDUrvilleAntarctica/MacquarieAntarctica/MawsonAntarctica/McMurdoAntarctica/PalmerAntarctica/RotheraAntarctica/South_PoleAntarctica/SyowaAntarctica/VostokArctic/Longyearbyen Europe/Oslo Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau Asia/Aqtobe Asia/AshgabatAsia/Ashkhabad Asia/Baghdad Asia/Bahrain Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei Asia/Calcutta Asia/KolkataAsia/ChoibalsanAsia/ChongqingAsia/Chungking Asia/Colombo Asia/Dacca Asia/Dhaka Asia/Damascus Asia/Dili Asia/Dubai Asia/Dushanbe Asia/Gaza Asia/HarbinAsia/Ho_Chi_MinhAsia/Hong_Kong Asia/Hovd Asia/Irkutsk Asia/IstanbulEurope/Istanbul Asia/Jakarta Asia/JayapuraAsia/Jerusalem Asia/KabulAsia/Kamchatka Asia/Karachi Asia/KashgarAsia/Kathmandu Asia/KatmanduAsia/KrasnoyarskAsia/Kuala_Lumpur Asia/Kuching Asia/Kuwait Asia/Macao Asia/Macau Asia/Magadan Asia/Makassar Asia/Manila Asia/Muscat Asia/NicosiaAsia/NovokuznetskAsia/Novosibirsk Asia/Omsk Asia/OralAsia/Phnom_PenhAsia/PontianakAsia/Pyongyang Asia/QatarAsia/Qyzylorda Asia/Rangoon Asia/Riyadh Asia/Saigon Asia/SakhalinAsia/Samarkand Asia/Seoul Asia/ShanghaiAsia/Singapore Asia/Taipei Asia/Tashkent Asia/Tbilisi Asia/Tehran Asia/Tel_Aviv Asia/Thimbu Asia/Thimphu Asia/TokyoAsia/Ujung_PandangAsia/UlaanbaatarAsia/Ulan_Bator Asia/UrumqiAsia/VientianeAsia/Vladivostok Asia/YakutskAsia/Yekaterinburg Asia/YerevanAtlantic/AzoresAtlantic/BermudaAtlantic/CanaryAtlantic/Cape_VerdeAtlantic/FaeroeAtlantic/FaroeAtlantic/Jan_MayenAtlantic/MadeiraAtlantic/ReykjavikAtlantic/South_GeorgiaAtlantic/St_HelenaAtlantic/Stanley Australia/ACTAustralia/SydneyAustralia/AdelaideAustralia/BrisbaneAustralia/Broken_HillAustralia/CanberraAustralia/CurrieAustralia/DarwinAustralia/EuclaAustralia/Hobart Australia/LHIAustralia/Lord_HoweAustralia/LindemanAustralia/MelbourneAustralia/North Australia/NSWAustralia/PerthAustralia/QueenslandAustralia/SouthAustralia/TasmaniaAustralia/VictoriaAustralia/WestAustralia/Yancowinna Brazil/AcreBrazil/DeNoronha Brazil/East Brazil/WestCanada/AtlanticCanada/CentralCanada/East-SaskatchewanCanada/EasternCanada/MountainCanada/NewfoundlandCanada/PacificCanada/Saskatchewan Canada/YukonCETChile/ContinentalChile/EasterIslandPacific/EasterCST6CDTCubaEETEgyptEire Europe/DublinESTEST5EDTEtc/GMT Etc/GMT+0 Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12 Etc/GMT+2 Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7 Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Etc/GMT-10 Etc/GMT-11 Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2 Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6 Etc/GMT-7 Etc/GMT-8 Etc/GMT-9Etc/GMT0 Etc/GreenwichEtc/UCT Etc/UniversalEtc/UTCEtc/ZuluEurope/AmsterdamEurope/Andorra Europe/AthensEurope/Belfast Europe/LondonEurope/Belgrade Europe/BerlinEurope/Bratislava Europe/PragueEurope/BrusselsEurope/BucharestEurope/BudapestEurope/ChisinauEurope/CopenhagenEurope/GibraltarEurope/GuernseyEurope/HelsinkiEurope/Isle_of_Man Europe/JerseyEurope/Kaliningrad Europe/Kiev Europe/LisbonEurope/LjubljanaEurope/Luxembourg Europe/Madrid Europe/MaltaEurope/Mariehamn Europe/Minsk Europe/Monaco Europe/MoscowEurope/Nicosia Europe/ParisEurope/Podgorica Europe/Riga Europe/Rome Europe/SamaraEurope/San_MarinoEurope/SarajevoEurope/Simferopol Europe/Skopje Europe/SofiaEurope/StockholmEurope/Tallinn Europe/TiraneEurope/TiraspolEurope/Uzhgorod Europe/VaduzEurope/Vatican Europe/ViennaEurope/VilniusEurope/Volgograd Europe/Warsaw Europe/ZagrebEurope/Zaporozhye Europe/ZurichGBGB-EireGMTGMT+0GMT-0GMT0 GreenwichHongkongHSTIcelandIndian/Antananarivo Indian/ChagosIndian/Christmas Indian/Cocos Indian/ComoroIndian/Kerguelen Indian/MaheIndian/MaldivesIndian/MauritiusIndian/MayotteIndian/ReunionIranIsraelJamaicaJapan KwajaleinPacific/KwajaleinLibyaMETMexico/BajaNorteMexico/BajaSurMexico/GeneralMSTMST7MDTNavajoNZPacific/AucklandNZ-CHATPacific/Chatham Pacific/Apia Pacific/Chuuk Pacific/EfatePacific/EnderburyPacific/Fakaofo Pacific/FijiPacific/FunafutiPacific/GalapagosPacific/GambierPacific/Guadalcanal Pacific/GuamPacific/HonoluluPacific/JohnstonPacific/KiritimatiPacific/KosraePacific/MajuroPacific/MarquesasPacific/Midway Pacific/Nauru Pacific/NiuePacific/NorfolkPacific/NoumeaPacific/Pago_Pago Pacific/PalauPacific/PitcairnPacific/PohnpeiPacific/PonapePacific/Port_MoresbyPacific/RarotongaPacific/Saipan Pacific/SamoaPacific/TahitiPacific/TarawaPacific/Tongatapu Pacific/Truk Pacific/WakePacific/Wallis Pacific/YapPolandPortugalPRCPST8PDTROCROK SingaporeTurkeyUCT Universal US/Alaska US/Aleutian US/Arizona US/CentralUS/East-Indiana US/Eastern US/HawaiiUS/Indiana-Starke US/Michigan US/Mountain US/PacificUS/Pacific-NewUS/SamoaUTCW-SUWETZulu7  !!""##$$%%&&''(())**++,,--..//0012233445566778899::;;<;==>>??@@AABBCCDDEEFFGGHHIIJ5KKLLMMNNOOPPQQRRSST:UUVVWWXXY;ZZ[[\\]]^I_=``aabbccddeeffgghhiijjkklmnoppqqrrssttuuvvwwxxyyzz{{||oo}}~~€€‚‚ƒƒ„o……††‡‡ˆ>‰‰ŠŠ‹‹Œ}ŽŽŠ‘‘’’““”v••––——˜@™™šš››œœžžŸŸ  ¡¡¢¢££¤¤¥¥¦¦§§¨¨©©ªª««¬¬­­®®¯¯°±²²³³´´µµ¶¶··¸¸±±¹=ºº»»¼¼½½¾¾¿¿ÀfÁvÂÂÃÃÄÄÅÅÆÆÇÇÈÈÉÉÊÊmmËËÌÌÍÍÎÅÏÏÐÐÑÑÒÒÓÓÔÔÕÕÖÖ×רØÙÙÚÚÛØÜÜÝÝÞßààááââããääååææçæèèééêêëëììííîîïðññòòóòôôõö÷÷ööøøùùúúûûüüýýþþÿÿ      ðð      !!"ý##$$%%&&''(())**++,-...//0112133445566778899::;;<<=>>>?ß@@AABBCCDDEFGGHHIIJFKKLLMMNNOPQQPPRRSLTFUUVHWGFFXNYRZU[I\±]¦^¾_“`zaÐb·cËdieÂfÍg·hÏiij¼klmmn{oop qrssttuuvuwwxxyyzz{{||}}~~€€‚‚ƒu„„……††‡‡ˆˆ‰‰ŠŠ‹‹ŒŒŽŽ‘‘’u“u””•–––—–˜˜™™šš›œžžŸ ¡¡¢¢££¤¤¥¥rr¦¦§œ¨¨©œªœ««¬¬­­®œœ¯¯°°±±²¨³³´´µµ¶ßß··¸  ¹¹ºº»»¼º½¾¾¿ÀÀÁÁÂÂÃÃĤÅÅÆÆÇºÈÈÉÉÊÊËËÌÍÍÎÎϜМÑuÒuÓuÔuÕuÖþ×רAÙÙÚÚÛÛÜÜÝÝÞÞßßààááââããä+忇ç/èéê2ëëìmí—î›ïïððñfòóôõööóóõõ÷÷lløøùùúúûûüüýýþþÿÿéé           ÷÷Ë­& (!%"'#$”%–&6'5(­)\*o+£,-}.g/f012 3–4µ556–joda-time-2.3/src/tz-data/org/joda/time/tz/data/CST6CDT0000644000175000017500000000126011564260550021722 0ustar ebourgebourgCCSTCPTCWTCDTZÿ€44~`¢à64~e?ä44~h¢`64~m?d44 &`64Ó„44@BÓ€64@FÓ44@JÓ64@NÒ„44@RÒ€64@VÒ44@ZÒ64@^Ñ„44@bÑ€64@fød44@jÑ64@n÷ä44@r÷à64@v÷d44@z÷`64@~öä44@‚öà64@†öd44@Š€@64@Žõä44@’À64@—Ä44@š@64@ŸD44@¢~À64@§Ä44@ª¥ 64@¯D44@²¥ 64@·Ä44@º¤ 64@¿A¤44@¤ 64@ÇA$44@Ê£ 64@Ï@¤44@ÒÊ€64@×@$44@ÚÊ64@ß?¤44@âÉ€64@ç?$44@êÉ64@ïf44@òÈ€64@÷e„44@úÈ64@ÿe44Aîà64Ad„44A î`64Ad44Aíà64AŠä44Aí`64AŠd44A"ìà64A'‰ä44A*v@64A/°Ä444wCDTw CSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/MST0000644000175000017500000000001011564260550021303 0ustar ebourgebourgFMST22joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/0000755000175000017500000000000012205344143021575 5ustar ebourgebourgjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Hong_Kong0000644000175000017500000000102511564260550023375 0ustar ebourgebourgCLMTHKTHKSTJSTFÿ€€k€k¿…iZü=2<¶à=¤AÇRF¸¶I¥O`öR²V6Y|²^¶a|2f6i{²n¶q¢’v–y¢~?RÒ†>–‰RRŽev‘QÒ–dö™x²ždv¡x2¦cö©w²®cv±w2¶ŠV¹v²¾‰ÖÁv2ƉVÉΈÖÑœ’ÖˆVÚ9’Þ9â9æ8–ê8’î_vò_rö^öú^òþ^v@^r@]ö@ ]ò@]v@]r@„V@„R@ƒÖ@ Ò@&ƒV@*ƒR@.‚Ö@2‚Ò@6‚V@KÒ@N¨6joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Baku0000644000175000017500000000045511564260547022422 0ustar ebourgebourgCLMTAZTBAKSTAZSTBAKT ÿ€€.¼€.¼¿ª•D˜÷¬@ZB @^G´@bG° @fLÔ@jLÐ @nQô@rW @vWÈ@zWˆ @~WH@‚W @†VÈ@ŠVˆ @ŽVH@’V @–UÈ@šUˆ @žUH@¢U @¦|(@ª{è@­Òp@®{ä@²zð@¶zt@Ò¡| @×>¼@Ú À @ß>wÿAZSTw ÿ AZTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Vientiane0000644000175000017500000000012111564260550023442 0ustar ebourgebourgCLMTICTSMTÿ€€`0€`0¿ˆoFP€cì€cì¿‘_îÐ~1)\~É¡joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Novosibirsk0000644000175000017500000000050711564260550024040 0ustar ebourgebourgCLMTNOVTNOVST%ÿ€€M¼€M¼¿¡Û$ ~»8@ZAÜ@^G@bFü@fL @jL@nQ@@rVÜ@vW@zVÔ@~V”@‚VT@†V@ŠUÔ@ŽU”@’UT@–U@šTÔ@žT”@¢TT@¦{t@ª{p @®{0 @°ñ0@²z@¶y„@ºz4@»´€ @¾z0 @Âyð @Æy° @Êyp @Îy0 @Ò P @×=  sÿNOVSTs ÿNOVTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Tehran0000644000175000017500000000137011564260550022750 0ustar ebourgebourgCLMTIRSTTMTIRDTeÿ€€08€08¿šl}È€08€08¿ÒÛÈ@>ÜN@Aï° @F£4@H8p@Iôî @Môr@Qÿ® @V²@«5. @®S²@²S® @¶^r@ºXÎ @¾c’@Â]î @Æh²@Êc @ÎmÒ@Òh. @Örò@Úrî @Þ}²@âx @æ‚Ò@ê}. @î‡ò@ò‚N @ö@ú @þ—ÒA’. AœòA —N A¢Aœn A§2A§. A±òA2¶Ž A6ÁRA:ÁN A>ÌABÆn AFÑ2AJËŽ ANÖRARЮ AVÛrAZÛn A^æ2AbàŽ AfëRAjå® AnðrArêÎ Avõ’AzõŽ ARA‚ú® A‡rAŠÿÎ A ’A“î A—²A›® AŸrA£Î A§’A«î A¯$²A³ A·)ÒA»)Î A¿4’AÃ.î AÇ9²AË4 AÏ>ÒAÓ9. A×CòAÛ>N AßIAãI AçSÒAëN. AïXòAóSN A÷^AûXn Aÿc2Bc. BmòB hN BsBmn Bx2BrŽ B}Rjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Dili0000644000175000017500000000012411564260550022404 0ustar ebourgebourgPLMTJSTCITTLTÿ€€u¼€u¼¿’æÄ k„=.¤@2Ö$@öuÀjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Novokuznetsk0000644000175000017500000000102111564260550024240 0ustar ebourgebourgCKRASTKRATNOVTNOVSTNMT@ÿ€€QÀ€QÀ¿¡ù@ ~»8@ZAÜ@^G@bFü@fL @jL@nQ@@rVÜ@vW@zVÔ@~V”@‚VT@†V@ŠUÔ@ŽU”@’UT@–U@šTÔ@žT”@¢TT@¦{t@ª{p @®{0 @°ñ0@²z@¶y„@ºz4@¾yô@Ây´@Æyt@Êy4@Îxô@Ò @×=T@ÚŸ”@ß<Ô@âŸ@ç@pàjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Muscat0000644000175000017500000000005611564260550022763 0ustar ebourgebourgPLMTGSTÿ€€6ì€6ì¿¡ò–”joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Amman0000644000175000017500000000072611564260550022564 0ustar ebourgebourgCLMTEESTEET:ÿ€€!°€!°¿¶£ÖÐ@‚@ì@"¼¨@& @*ÁÈ@.,@2̈@6×L@:Ѩ@>. @BÑ(@F-Œ@z](@~bL@‚s(@†r¬@Šr¨@Žr,@’r(@–™ @›Gh@ž˜Œ@£¨@¦˜ @ªÛˆ@®p,@²¾è@¶— @º—@¾–Œ@–ˆ@ÆGL@ʽh@ÎG@Ò¼è@Ömè@Ú¼h@Þmh@â»è@ælè@쵨@î“È@òµH@öº¨@ú´È@þº(A¹èA¹¨A ¹hAV¨A¸èA.ÈAßÈA߈A"ßHA'|ˆwEESTs ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Magadan0000644000175000017500000000050011564260550023051 0ustar ebourgebourgCLMTMAGSTMAGT$ÿ€€`€`¿ª6 ~ºH@Z@ì@^F@bF @fK0@jK,@nPP@rUì@vV$@zUä@~U¤@‚Ud@†U$@ŠTä@ŽT¤@’Td@–T$@šSä@žS¤@¢Sd@¦z„@ªz€@®z@@°ð@@²y@¶x”@ºyD@¾y@ÂxÄ@Æx„@ÊxD@Îx@ÒŸ$@× €> ¿ª…`~»° @ZBT @^Gx @bGt @fL˜ @jL” @nQ¸ @rWT @vWŒ @zWL @~W @‚VÌ @†VŒ @ŠVL @ŽV @’UÌ @–UŒ @šUL @žU @¢TÌ @¦{ì @ª{¬ @­Ý8 @®{l joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Aqtau0000644000175000017500000000064011564260550022601 0ustar ebourgebourgCLMTAQTTSHETAQTSTFORTSHEST3ÿ€€/ €/ ¿ª”à~»° ÇÏ´ @^G´ @bGt @fL˜ @jL” @nQ¸ @rWT @vWŒ @zWL @~W @‚VÌ @†VŒ @ŠVL @ŽV @’UÌ @–UŒ @šUL @žU @¢TÌ @¦{ì @°1´ @²zx @¶yü @ºz¬ @¾zl @Âz, @Æyì @Êyè @Îy¨@Ò È @×>@Ú H @ß=ˆ@âŸÈ @ç=@êŸH @ïcè@òžÈ @÷ch@úžH @ÿbèAÅ( AbhA Ĩ AaèAÄ( AˆÈA° joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Yekaterinburg0000644000175000017500000000051511564260550024342 0ustar ebourgebourgCLMTSVESTYEKSTYEKTSVET$ÿ€€8Ѐ8п¡­ð~»° @ZBT @^Gx @bGt @fL˜ @jL” @nQ¸ @rWT @vWŒ @zWL @~W @‚VÌ @†VŒ @ŠVL @ŽV @’UÌ @–UŒ @šUL @žU @¢TÌ @¦{ì @ª{è @®{¨@°ñ¨ @²zx @¶yü @ºz¬ @¾zl @Âz, @Æyì @Êy¬ @Îyl @Ò Œ @×=Ì  sÿYEKSTs ÿYEKTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Kuwait0000644000175000017500000000005611564260550022773 0ustar ebourgebourgPLMTASTÿ€€,ü€,ü¿Úa5„joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Sakhalin0000644000175000017500000000053711564260550023265 0ustar ebourgebourgCLMTSAKSTCJTJSTSAKT'ÿ€€…È€…È¿†ð͸~ÿ,ä<‹„@Z@ì@^F@bF @fK0@jK,@nPP@rUì@vV$@zUä@~U¤@‚Ud@†U$@ŠTä@ŽT¤@’Td@–T$@šSä@žS¤@¢Sd@¦z„@ªz€@®z@@°ð@@²y@¶x”@ºyD@¾y@ÂxÄ@Æx„@ÊxD@Îx@ÒŸ$@×@Ú H @ß=ˆ@âŸÈ @ç=@êŸH @ïcè@òžÈ @÷ch@úžH @ÿbèAÅ( AbhA Ĩ AaèAÄ( AˆÈA° joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Bishkek0000644000175000017500000000064611564260550023114 0ustar ebourgebourgCLMTKGSTKGTFRUSTFRUT5ÿ€€Eð€Eð¿ª~ ~»t @ZB @^G< @bG8 @fL\ @jLX @nQ| @rW @vWP @zW @~VÐ @‚V @†VP @ŠV @ŽUÐ @’U @–UP @šU @žTÐ @¢T @¦{° @ª{p @­Ø @²Ét @¶z8 @ºÈô @¾y¸ @ÂÈt @Æy8 @ÊÇô @Îx¸ @ÒÇt @ÖŸ˜ @Ú * @ß=. @⟪ @ç<® @êŸ* @ïcŽ @òžª @÷c @úž* @ÿbŽ AÅ Ab A ÄŠ AaŽ AÄ Aˆn AÊ AÊø joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Singapore0000644000175000017500000000021711564260550023455 0ustar ebourgebourgCLMTMALSTJSTMALTSGTSMT ÿ€€a]€a]¿~6S£€a]€a]¿†ƒ…£~×@¸~ïh@¸@¸™( J<ðÄÜ´~@`Lžjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Pyongyang0000644000175000017500000000011611564260550023477 0ustar ebourgebourgPLMTKSTÿ€@÷@÷}}ù)}õ¨‚~®èÄ~ÏQļŸàjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Colombo0000644000175000017500000000017011564260550023116 0ustar ebourgebourgCLKTLMTIHSTISTMMT ÿ€€JÜ€JÜ¿V¶™$€Jä€J俇½ ^V $ž˜ =± @ÓÕV @×7x A#2Ö joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Tbilisi0000644000175000017500000000066511564260550023134 0ustar ebourgebourgCGESTTBISTLMTGETTBITTBMT5ÿ€€*€*¿V¶¹ü€*€*¿ª™ü˜÷¬@ZB @^G´@bG° @fLÔ@jLÐ @nQô@rW @vWÈ@zWˆ @~WH@‚W @†VÈ@ŠVˆ @ŽVH@’V @–UÈ@šUˆ @žUH@¢U @¦|(@ª{è@ª®@®{ä@²{,@¶z°@ºz¬@¾z0@Âz,@Æy°@Êyp @Îxô@Ò P @ß<Ô@âŸP @ç äA±àFŒš¨«l¢T(¥°ŒªY„­°À²dDµ»€ºid½À Ân„ÅÅÀÊs¤ÍÊàÒ~dÕÕ Úƒ„ÝÚÀ∤åå€êÄëR,@$5ˆ@&\Œ@*ƒè@-oÌ@z¦H@~L@ƒj¨@…àl@ж(@ŽL@’Ÿ(@•ÙÌ@›h@Þì@¢U@¥· @ªTˆ@­Ýì@²{h@¶Ì@º—@¾L@–ˆ@ÅÜl@Ê–@ÎL@Цˆ@Ò¼è@Ömè@Ú¼h@Þmh@â»è@ælè@ë (@ï ¬@ó1@÷0Œ@û0ˆ@ÿ0 A0A/ŒA /ˆA/ A/AàA.ˆAöDA"äèA&·lA*êA.ŠdA2ôÈA6@ÄA:ÝÈA>g¤ABâéAEåLAJâiwÿ@EESTw EETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Harbin0000644000175000017500000000025111564260547022735 0ustar ebourgebourgCCSTLMTCDTCHATÿ€€vÄ€vÄ¿°þ•¼~ÐT‚7`â†Ä@Rå"@ƒ€@†d@Š£à@Žä@’£`@–d@šÊ@@ž,D@¢ÉÀ@¦+Ä@ªÉ@@®+Djoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Qatar0000644000175000017500000000007211564260550022575 0ustar ebourgebourgPLMTASTGSTÿ€€0P€0P¿¡ò0@`Pjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Makassar0000644000175000017500000000012611564260550023267 0ustar ebourgebourgPLMTMMTJSTCITÿ€€oð€oð¿¡ò]€oð€oð¿ºÕ " =.¤joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Choibalsan0000644000175000017500000000057311564260550023576 0ustar ebourgebourgCCHOSTLMTCHOTULAT0ÿ€@Ê@Ê}úÿ–@@2œ@jKà@nPÈ@rVd@vUè@zUä@~Uh@‚Ud@†Tè@ŠTä@ŽTh@’Td@–Sè@šSä@žSh@¢Sd@¦zH@ªzD@®yÈ@²yÄ@¶yH@ºyD@¾xÈ@ÂxÄ@ÆxH@ÊxD@ÎwÈ@ÒŸ$@Öž¨@Úž¤@Þž(@âž$@æ¨@û\\@þ¾`A¾\A½àA ½ÜA½`A½\A¼àA¼ÜA¼`A"¼\A&ã@A2í„joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Dushanbe0000644000175000017500000000033411564260550023257 0ustar ebourgebourgCLMTDUSTTJTDUSSTÿ€€@€€@€¿ªƒ€ ~»t @ZB @^G< @bG8 @fL\ @jLX @nQ| @rW @vWP @zW @~VÐ @‚V @†VP @ŠV @ŽUÐ @’U @–UP @šU @žTÐ @¢T @¦{° @ª{p @® ì joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Ho_Chi_Minh0000644000175000017500000000012111564260550023624 0ustar ebourgebourgCLMTICTSMTÿ€€d€d¿ˆoB€€cì€cì¿‘_îÐ~1)\~É¡joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Jayapura0000644000175000017500000000010111564260550023272 0ustar ebourgebourgPCSTLMTEITÿ€€ƒè€ƒè¿ºÁ˜4­ÄÏÓÆjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Taipei0000644000175000017500000000051011564260550022735 0ustar ebourgebourgCCSTLMTCDT*ÿ€@æ@æ}®š9ÿ@=[¤B`E`ÄJ €MeäR@Up¤Z`]uÄb€ezäj# m€p×@v9$yŠÀ~>Dà†Cd‰•š$‘ŸÀ•¤ä™¤àª¡ª¥¯$©¯ ­´D³µ¿» ½Ä$@"€@&¤@* @.Ä@L,@N1Djoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Shanghai0000644000175000017500000000024311564260550023247 0ustar ebourgebourgCCSTLMTCDTÿ€€qà€qà¿°þ𠙠܀>Ü¿‰~ü¤ $ž¶ =ªú m{6 @ Üt AëÕ AëY A4K4 A7§˜ A;Gô A?¬¸ joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Kamchatka0000644000175000017500000000100411564260550023405 0ustar ebourgebourgCLMTPETTPETST@ÿ€€”¼€”¼¿§R–Ä~º @Z@°@^EÔ@bEÐ@fJô@jJð@nP@rU°@vUè@zU¨@~Uh@‚U(@†Tè@ŠT¨@ŽTh@’T(@–Sè@šS¨@žSh@¢S(@¦zH@ªzD@®z@°ð@²xÔ@¶xX@ºy@¾xÈ@Âxˆ@ÆxH@Êx@ÎwÈ@Òžè@×<(@Úžh@ß;¨@âè@ç;(@êh@ïb@òœè@÷aˆ@úœh@ÿaAÃHA`ˆA ÂÈA`AÂHA†èAÁÈA†hA"ÁHA'…èA*ÀÈA/…hA2ç¨A7„èA:ç(A?„hABæäAG«„sÿPETSTs ÿPETTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Chongqing0000644000175000017500000000022411564260550023441 0ustar ebourgebourgCCSTLONTLMTCDTÿ€€cì€cì¿°þ¨”@Rå|@ƒ€@†d@Š£à@Žä@’£`@–d@šÊ@@ž,D@¢ÉÀ@¦+Ä@ªÉ@@®+Djoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Thimphu0000644000175000017500000000007211564260547023151 0ustar ebourgebourgPLMTBTTISTÿ€€T €T ¿Õæt @Žkö joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Yakutsk0000644000175000017500000000050011564260550023154 0ustar ebourgebourgCYAKSTLMTYAKT$ÿ€€y€y¿¡Ûêp~ºÀ@ZAd@^Fˆ@bF„@fK¨@jK¤@nPÈ@rVd@vVœ@zV\@~V@‚UÜ@†Uœ@ŠU\@ŽU@’TÜ@–Tœ@šT\@žT@¢SÜ@¦zü@ªzø@®z¸@°ð¸@²yˆ@¶y @ºy¼@¾y|@Ây<@Æxü@Êx¼@Îx|@ÒŸœ@×<ÜsÿYAKSTs ÿYAKTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Riyadh0000644000175000017500000000005611564260550022747 0ustar ebourgebourgPLMTASTÿ€€+Ì€+Ì¿Úa6´joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Kabul0000644000175000017500000000006511564260547022573 0ustar ebourgebourgPLMTAFTÿ€€@à€@à¿i†š 7]0 joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Urumqi0000644000175000017500000000022411564260550023006 0ustar ebourgebourgCCSTLMTCDTURUTÿ€€R€R¿°þºd @Rå¸@ƒ€@†d@Š£à@Žä@’£`@–d@šÊ@@ž,D@¢ÉÀ@¦+Ä@ªÉ@@®+Djoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Bahrain0000644000175000017500000000007211564260547023077 0ustar ebourgebourgPLMTASTGSTÿ€€/l€/l¿¡òž@`Pjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Tokyo0000644000175000017500000000017511564260550022636 0ustar ebourgebourgCLMTJDTCJTJST ÿ€€ƒ€ƒ}mé$}®d~ÿ,äRU`Y|\ÿàb@|dÿ`j?ülþàjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Baghdad0000644000175000017500000000066411564260550023046 0ustar ebourgebourgCLMTASTBMTADT7ÿ€€)¤€)¤¿i†±Ü€) €) ¿ž0<à@bð¬@fM@jGl@nR0@rWÌ@v\ð@z\ì@~WH@‚W@†VÈ@ŠVˆ@ŽVH@’V@–UÈ@šUˆ@žUH@¢U@¦|(@ª‚@®‡`@²ŒÀ@¶’ @º‘à@¾—@@—@Æœ`@Êœ @Ρ€@Ò¦à@Ö¬@@Ú¬@Þ±`@â± @æ¶€@ê¶@@î» @òÁ@öÆ`@úÆ @þË€AË@AРA Ð`AÕÀAÛ Aà€Aà@Aå A"å`A&êÀA*ê€A.ïàjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Kuching0000644000175000017500000000032411564260550023115 0ustar ebourgebourgCMYTLMTBORTBORTSTJSTÿ€€gp€gp¿­Š~× þ~ì¸ @ô~î·ì~ôÂà@ô~ö¬~üÈ@ô~þÇÌÍ @ôÌì Ò@@ôÒ Ý@ôÜÌâ @ôáì J<ðÄ@`L€joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Kolkata0000644000175000017500000000013611564260550023114 0ustar ebourgebourgCBURTLMTISTHMTÿ€€RØ€RØ¿V¶‘(€RЀRпÊÛ†° "9Z $ž¶ =ªú joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Macau0000644000175000017500000000053011564260550022552 0ustar ebourgebourgCCSTLMTMOTMOST+ÿ€€j|€j|¿’æ$¹v²¾‰ÖÁv2ƉVÉtàΈÖÑœ’ÖˆVÙ›@Þ‡â9æ8–ê8’î_vò_rö^öú^òþ^v@^r@]ö@ ]ò@]v@\ @\$@\ @ƒ@"ƒ@&ƒV@*ƒR@.‚Ö@2‚Ò@6‚V@:‚R@>Ö@B@F€„@J€€@N§d@R§`@V¦ä@ð{Àjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Hovd0000644000175000017500000000056111564260550022430 0ustar ebourgebourgCHOVTLMTHOVST/ÿ€€Uì€U쿆Óü” @@2Ø@jL@nQ@@rVÜ@vV`@zV\@~Uà@‚UÜ@†U`@ŠU\@ŽTà@’TÜ@–T`@šT\@žSà@¢SÜ@¦zÀ@ªz¼@®z@@²z<@¶yÀ@ºy¼@¾y@@Ây<@ÆxÀ@Êx¼@Îx@@ÒŸœ@ÖŸ @ÚŸ@Þž @âžœ@æž @û\Ô@þ¾ØA¾ÔA¾XA ¾TA½ØA½ÔA½XA½TA¼ØA"¼ÔA&ã¸joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Qyzylorda0000644000175000017500000000063211564260550023525 0ustar ebourgebourgCQYZTLMTQYZSTKIZTKIZST3ÿ€€=`€=`¿ª† ~»° @ZBT @^Gx @bGt @fL˜ @jL” @nQ¸ @rWT @vWŒ @zWL @~W @‚VÌ @†VŒ @ŠVL @ŽV @’UÌ @–UŒ @šUL @žU @¢TÌ @¦{ì @°1´ @°ñl @²z< @¶yÀ @ºzp @¾z0 @Âyð @Æy° @Êyp @Îy0 @Ò P @×= @ÚŸÐ @ß= @âŸP @ç< @êžÐ @ïcp @òžP @÷bð @úÐ @ÿbp Aİ Aað A Ä0 Aap Að AˆP joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Jakarta0000644000175000017500000000017511564260550023106 0ustar ebourgebourgCLMTWITJMTJSTJAVT ÿ€€d €d ¿?fI`€d €d ~ŽÏ@¸@¸~Õ¶è!þ=.¤R^b€ÏÔ>joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Seoul0000644000175000017500000000020711564260550022614 0ustar ebourgebourgCLMTKSTKDTÿ€€w€w¿i†dx}õ¨‚~®èÄ~ÏQIJ±`µYļŸàõób@‹A$@Ž£(@“@¤@–¢¨joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Kashgar0000644000175000017500000000023311564260550023104 0ustar ebourgebourgCCSTLMTCDTKASTÿ€€G<€G<¿°þÅD 7ö @Råô@ƒ€@†d@Š£à@Žä@’£`@–d@šÊ@@ž,D@¢ÉÀ@¦+Ä@ªÉ@@®+Djoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Ashgabat0000644000175000017500000000035211564260550023240 0ustar ebourgebourgCLMTTMTASHSTASHTÿ€€6¼€6¼¿ªD~»° @ZBT @^Gx @bGt @fL˜ @jL” @nQ¸ @rWT @vWŒ @zWL @~W @‚VÌ @†VŒ @ŠVL @ŽV @’UÌ @–UŒ @šUL @žU @¢TÌ @¦{ì @ª{è @®{¨@¯°@°ñ¨ joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Damascus0000644000175000017500000000134711564260550023273 0ustar ebourgebourgCLMTEESTEETaÿ€€"€"¿¡ò«x~q ~tÆä~y ~|Æd~ ~„Åä~‰ ~ŒìÄÂc€ÅË$ÊsàÍʤÒ~ ÕÛÚƒÀÝÚ„âa€ååDêŽíêdò˜Àõõ$úàýúD@£@ÿd@ ¨ @„@²à@D@¸@d@"½ @&„@*Â@@.¤@2Í@6)d@:Ò @=…Ä@B×@@EŠä@jzÀ@nRä@r…€@v]¤@k@@†”ä@‰¹€@Ä@’@— „@šr @ž|ä@¢|à@¦|d@ªˆ@®†¬@²³¨@¶‘l@ºo¨@¾tÌ@–ˆ@Æ›¬@Ê›¨@ΠÌ@Ò¦h@Ö«Œ@Ú¥è@Þ°¬@â¥h@æµÌ@êµÈ@îºì@òÀˆ@öŬ@úŨ@þÊÌAÊÈAÏìA ÏèAÕ AÚ¨AßÌAßÈAäìA"äèA&·lA*ÞÈA/£,A3¨A7¨LA:ÝÈA?¢,AC¨wEESTw ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Manila0000644000175000017500000000017311564260550022730 0ustar ebourgebourgCPHTLMTPHSTJST ÿ€ÿüDÿüD|Ô¼@ä@ä}É Ü~õÐà~÷Ö$!ê@6äÍÀƒ„@Aô`@Eù„joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Rangoon0000644000175000017500000000013411564260547023135 0ustar ebourgebourgPBURTLMTRMTMMTJSTÿ€€Z(€Z(¿V¶‰Ø€Z$€Z$¿¡òs\ !êš: D joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Dubai0000644000175000017500000000005611564260550022553 0ustar ebourgebourgPLMTGSTÿ€€3Ø€3Ø¿¡ò™¨joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Bangkok0000644000175000017500000000010311564260550023074 0ustar ebourgebourgPLMTICTBMTÿ€€^<€^<¿V¶…Ä€^<€^<¿¢jgÄjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Beirut0000644000175000017500000000101311564260550022753 0ustar ebourgebourgCLMTEESTEETBÿ€@Ž@Ž}-¶r~pŸˆ~uB,~xÆh~|ËŒ~€žˆ~„ìÌ~‰;ˆ~Œv,šO«l¢T(¥°ŒªYH­µ¬²dµÀlºi(½ÅŒ@Öè@Ì@·ˆ@ì@"¼¨@& @*ÁÈ@.,@2̈@6(ì@:Ѩ@>. @BÑ(@F-Œ@sÈ@v±Œ@{è@~¶¬@ƒ @†»Ì@‹(@ŽÀì@“ÉH@–ˬ@›R¨@žÐÌ@£%(@¦Õì@«*H@®Û @³5@¶¢L@ºzè@¾zl@Âzh@Æyì@Êyè@Îyl@Ò È@Ö L@Ú H@ÞŸÌ@âŸÈ@æŸL@êŸH@ïc¬wÿEESTw ÿEETjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Omsk0000644000175000017500000000050011564260550022432 0ustar ebourgebourgCLMTOMSSTOMST$ÿ€€DЀDп¡³@° ~»t @ZB @^G< @bG8 @fL\ @jLX @nQ| @rW @vWP @zW @~VÐ @‚V @†VP @ŠV @ŽUÐ @’U @–UP @šU @žTÐ @¢T @¦{° @ª{¬ @®{l @°ñl @²z< @¶yÀ @ºzp @¾z0 @Âyð @Æy° @Êyp @Îy0 @Ò P @×=  sÿOMSSTs ÿOMSTjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Jerusalem0000644000175000017500000000205111564260550023453 0ustar ebourgebourgCLMTISTIDTJMTIDDTÿ€€!€!¿V¶Âø€ ø€ ø¿ž0EˆÈ%öl)H€-ûŒ1RÈ6L9¬H> äA±àFŒR‘hTÉV äZÈ^&aˈe#i|HnhÀqò`uò yÊ€},Àƒ+è…+Œ‹&@+ “ˆ•¡`šD@xÌ@$5ˆ@&\Œ@*ƒè@-oÌ@z¦H@~L@ƒj¨@…àl@ж(@ŽL@’Ÿ(@•ÙÌ@›h@Þì@¢U@¥· @ªTˆ@­Ýì@²{h@¶Ì@º—@¾L@–ˆ@ÅÜl@Ê–@ÎL@ÒFÈ@ÖW,@Úm¨@ÞQ @âm(@æ),@ê»à@îä@ó @öâ@úòä@þ£¨Aº$AñèA ¹¤AàˆAü¤A­hAà@AdA"ßÀA&ê„A*ß@A.›DA2ÞÀA7äA:Þ@A>éABÝÀAF™ÄAK AOdAS AVç„A[ A^˜DAc Ag äAk AnæAs)€Aw[¤A{)A dAƒ(€A†ä„A‹(AZ$A“'€A—2DA›'AžãA£MàA§X¤A«M`A¯0ÄA³LàA·A»L`A¿W$AÃKàAÇ/DAËK`AϤäAÓr@A×U¤AÛqÀAß-ÄAãq@Aç£dAëpÀAïT$Aóp@A÷,DAû— Aÿ¡äB– BR¤B – BÈDB• B dB• BQ$joda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Vladivostok0000644000175000017500000000051011564260550024027 0ustar ebourgebourgCLMTVLASTVLATVLASST$ÿ€€{°€{°¿§YGP~º„@ZA(@^FL@bFH@fKl@jKh@nPŒ@rV(@vV`@zV @~Uà@‚U @†U`@ŠU @ŽTà@’T @–T`@šT @žSà@¢S @¦zÀ@ªz¼@®z|@°ð|@²yL@¶xÐ@ºy€@¾y@@Ây@ÆxÀ@Êx€@Îx@@ÒŸ`@×< sÿVLASTs ÿVLATjoda-time-2.3/src/tz-data/org/joda/time/tz/data/Asia/Nicosia0000644000175000017500000000064511564260550023120 0ustar ebourgebourgCLMTEESTEET3ÿ€€H€H¿¥w¸@*\ˆ@.\ @3H@6a,@:4(@> L@B3¨@F8Ì@J3(@N2¬@RZ@V2,@Z2(@^1¬@b1¨@f1,@j1(@n0¬@r0¨@vWŒ@zWˆ@~W @‚W@†VŒ@ŠVˆ@ŽV @’V@–UŒ@šUˆ@žU @¢U@¦{ì@ª{è@®{l@²{h@¶zì@ºzè@¾zl@Âzh@Æyì@Êyè@Îyl@Ò È@Ö L@Ú H@ÞŸÌ@âŸÈ@ç=¼@êŸüuÿEESTu ÿEETjoda-time-2.3/src/main/0000755000175000017500000000000012203430131014257 5ustar ebourgebourgjoda-time-2.3/src/main/assembly/0000755000175000017500000000000012205344143016107 5ustar ebourgebourgjoda-time-2.3/src/main/assembly/dist.xml0000644000175000017500000000167411564257304017615 0ustar ebourgebourg dist tar.gz zip ${artifactId}-${version} build.xml checkstyle.xml LICENSE.txt NOTICE.txt pom.xml RELEASE-NOTES.txt ToDo.txt src target *.jar joda-time-2.3/src/main/checkstyle/0000755000175000017500000000000012205344143016426 5ustar ebourgebourgjoda-time-2.3/src/main/checkstyle/checkstyle.xml0000644000175000017500000001066512203434337021321 0ustar ebourgebourg joda-time-2.3/src/main/java/0000755000175000017500000000000012203442052015205 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/0000755000175000017500000000000012073523032015777 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/0000755000175000017500000000000012073523032016714 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/0000755000175000017500000000000012205344143017653 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/Duration.java0000644000175000017500000004316511577621372022331 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import org.joda.convert.FromString; import org.joda.time.base.BaseDuration; import org.joda.time.field.FieldUtils; /** * An immutable duration specifying a length of time in milliseconds. *

* A duration is defined by a fixed number of milliseconds. * There is no concept of fields, such as days or seconds, as these fields can vary in length. * A duration may be converted to a {@link Period} to obtain field values. * This conversion will typically cause a loss of precision however. *

* Duration is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class Duration extends BaseDuration implements ReadableDuration, Serializable { /** Constant representing zero millisecond duration */ public static final Duration ZERO = new Duration(0L); /** Serialization version */ private static final long serialVersionUID = 2471658376918L; //----------------------------------------------------------------------- /** * Parses a {@code Duration} from the specified string. *

* This parses the format {@code PTa.bS}, as per {@link #toString()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static Duration parse(String str) { return new Duration(str); } //----------------------------------------------------------------------- /** * Create a duration with the specified number of days assuming that * there are the standard number of milliseconds in a day. *

* This method assumes that there are 24 hours in a day, * 60 minutes in an hour, 60 seconds in a minute and 1000 milliseconds in * a second. This will be true for most days, however days with Daylight * Savings changes will not have 24 hours, so use this method with care. *

* A Duration is a representation of an amount of time. If you want to express * the concepts of 'days' you should consider using the {@link Days} class. * * @param days the number of standard days in this duration * @return the duration, never null * @throws ArithmeticException if the days value is too large * @since 1.6 */ public static Duration standardDays(long days) { if (days == 0) { return ZERO; } return new Duration(FieldUtils.safeMultiply(days, DateTimeConstants.MILLIS_PER_DAY)); } /** * Create a duration with the specified number of hours assuming that * there are the standard number of milliseconds in an hour. *

* This method assumes that there are 60 minutes in an hour, * 60 seconds in a minute and 1000 milliseconds in a second. * All currently supplied chronologies use this definition. *

* A Duration is a representation of an amount of time. If you want to express * the concepts of 'hours' you should consider using the {@link Hours} class. * * @param hours the number of standard hours in this duration * @return the duration, never null * @throws ArithmeticException if the hours value is too large * @since 1.6 */ public static Duration standardHours(long hours) { if (hours == 0) { return ZERO; } return new Duration(FieldUtils.safeMultiply(hours, DateTimeConstants.MILLIS_PER_HOUR)); } /** * Create a duration with the specified number of minutes assuming that * there are the standard number of milliseconds in a minute. *

* This method assumes that there are 60 seconds in a minute and * 1000 milliseconds in a second. * All currently supplied chronologies use this definition. *

* A Duration is a representation of an amount of time. If you want to express * the concepts of 'minutes' you should consider using the {@link Minutes} class. * * @param minutes the number of standard minutes in this duration * @return the duration, never null * @throws ArithmeticException if the minutes value is too large * @since 1.6 */ public static Duration standardMinutes(long minutes) { if (minutes == 0) { return ZERO; } return new Duration(FieldUtils.safeMultiply(minutes, DateTimeConstants.MILLIS_PER_MINUTE)); } /** * Create a duration with the specified number of seconds assuming that * there are the standard number of milliseconds in a second. *

* This method assumes that there are 1000 milliseconds in a second. * All currently supplied chronologies use this definition. *

* A Duration is a representation of an amount of time. If you want to express * the concepts of 'seconds' you should consider using the {@link Seconds} class. * * @param seconds the number of standard seconds in this duration * @return the duration, never null * @throws ArithmeticException if the seconds value is too large * @since 1.6 */ public static Duration standardSeconds(long seconds) { if (seconds == 0) { return ZERO; } return new Duration(FieldUtils.safeMultiply(seconds, DateTimeConstants.MILLIS_PER_SECOND)); } /** * Create a duration with the specified number of milliseconds. * * @param millis the number of standard milliseconds in this duration * @return the duration, never null * @since 2.0 */ public static Duration millis(long millis) { if (millis == 0) { return ZERO; } return new Duration(millis); } //----------------------------------------------------------------------- /** * Creates a duration from the given millisecond duration. * * @param duration the duration, in milliseconds */ public Duration(long duration) { super(duration); } /** * Creates a duration from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @throws ArithmeticException if the duration exceeds a 64 bit long */ public Duration(long startInstant, long endInstant) { super(startInstant, endInstant); } /** * Creates a duration from the given interval endpoints. * * @param start interval start, null means now * @param end interval end, null means now * @throws ArithmeticException if the duration exceeds a 64 bit long */ public Duration(ReadableInstant start, ReadableInstant end) { super(start, end); } /** * Creates a duration from the specified object using the * {@link org.joda.time.convert.ConverterManager ConverterManager}. * * @param duration duration to convert * @throws IllegalArgumentException if duration is invalid */ public Duration(Object duration) { super(duration); } //----------------------------------------------------------------------- /** * Gets the length of this duration in days assuming that there are the * standard number of milliseconds in a day. *

* This method assumes that there are 24 hours in a day, * 60 minutes in an hour, 60 seconds in a minute and 1000 milliseconds in * a second. This will be true for most days, however days with Daylight * Savings changes will not have 24 hours, so use this method with care. *

* This returns getMillis() / MILLIS_PER_DAY. * The result is an integer division, thus excess milliseconds are truncated. * * @return the length of the duration in standard seconds * @since 2.0 */ public long getStandardDays() { return getMillis() / DateTimeConstants.MILLIS_PER_DAY; } /** * Gets the length of this duration in hours assuming that there are the * standard number of milliseconds in an hour. *

* This method assumes that there are 60 minutes in an hour, * 60 seconds in a minute and 1000 milliseconds in a second. * All currently supplied chronologies use this definition. *

* This returns getMillis() / MILLIS_PER_HOUR. * The result is an integer division, thus excess milliseconds are truncated. * * @return the length of the duration in standard seconds * @since 2.0 */ public long getStandardHours() { return getMillis() / DateTimeConstants.MILLIS_PER_HOUR; } /** * Gets the length of this duration in minutes assuming that there are the * standard number of milliseconds in a minute. *

* This method assumes that there are 60 seconds in a minute and * 1000 milliseconds in a second. * All currently supplied chronologies use this definition. *

* This returns getMillis() / 60000. * The result is an integer division, thus excess milliseconds are truncated. * * @return the length of the duration in standard seconds * @since 2.0 */ public long getStandardMinutes() { return getMillis() / DateTimeConstants.MILLIS_PER_MINUTE; } /** * Gets the length of this duration in seconds assuming that there are the * standard number of milliseconds in a second. *

* This method assumes that there are 1000 milliseconds in a second. * All currently supplied chronologies use this definition. *

* This returns getMillis() / 1000. * The result is an integer division, so 2999 millis returns 2 seconds. * * @return the length of the duration in standard seconds * @since 1.6 */ public long getStandardSeconds() { return getMillis() / DateTimeConstants.MILLIS_PER_SECOND; } //----------------------------------------------------------------------- /** * Get this duration as an immutable Duration object * by returning this. * * @return this */ public Duration toDuration() { return this; } /** * Converts this duration to a period in days assuming that there are the * standard number of milliseconds in a day. *

* This method assumes that there are 24 hours in a day, * 60 minutes in an hour, 60 seconds in a minute and 1000 milliseconds in * a second. This will be true for most days, however days with Daylight * Savings changes will not have 24 hours, so use this method with care. * * @return a period representing the number of standard days in this period, never null * @throws ArithmeticException if the number of days is too large to be represented * @since 2.0 */ public Days toStandardDays() { long days = getStandardDays(); return Days.days(FieldUtils.safeToInt(days)); } /** * Converts this duration to a period in hours assuming that there are the * standard number of milliseconds in an hour. *

* This method assumes that there are 60 minutes in an hour, * 60 seconds in a minute and 1000 milliseconds in a second. * All currently supplied chronologies use this definition. * * @return a period representing the number of standard hours in this period, never null * @throws ArithmeticException if the number of hours is too large to be represented * @since 2.0 */ public Hours toStandardHours() { long hours = getStandardHours(); return Hours.hours(FieldUtils.safeToInt(hours)); } /** * Converts this duration to a period in minutes assuming that there are the * standard number of milliseconds in a minute. *

* This method assumes that there are 60 seconds in a minute and * 1000 milliseconds in a second. * All currently supplied chronologies use this definition. * * @return a period representing the number of standard minutes in this period, never null * @throws ArithmeticException if the number of minutes is too large to be represented * @since 2.0 */ public Minutes toStandardMinutes() { long minutes = getStandardMinutes(); return Minutes.minutes(FieldUtils.safeToInt(minutes)); } /** * Converts this duration to a period in seconds assuming that there are the * standard number of milliseconds in a second. *

* This method assumes that there are 1000 milliseconds in a second. * All currently supplied chronologies use this definition. * * @return a period representing the number of standard seconds in this period, never null * @throws ArithmeticException if the number of seconds is too large to be represented * @since 1.6 */ public Seconds toStandardSeconds() { long seconds = getStandardSeconds(); return Seconds.seconds(FieldUtils.safeToInt(seconds)); } //----------------------------------------------------------------------- /** * Creates a new Duration instance with a different milisecond length. * * @param duration the new length of the duration * @return the new duration instance */ public Duration withMillis(long duration) { if (duration == getMillis()) { return this; } return new Duration(duration); } /** * Returns a new duration with this length plus that specified multiplied by the scalar. * This instance is immutable and is not altered. *

* If the addition is zero, this instance is returned. * * @param durationToAdd the duration to add to this one * @param scalar the amount of times to add, such as -1 to subtract once * @return the new duration instance */ public Duration withDurationAdded(long durationToAdd, int scalar) { if (durationToAdd == 0 || scalar == 0) { return this; } long add = FieldUtils.safeMultiply(durationToAdd, scalar); long duration = FieldUtils.safeAdd(getMillis(), add); return new Duration(duration); } /** * Returns a new duration with this length plus that specified multiplied by the scalar. * This instance is immutable and is not altered. *

* If the addition is zero, this instance is returned. * * @param durationToAdd the duration to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return the new duration instance */ public Duration withDurationAdded(ReadableDuration durationToAdd, int scalar) { if (durationToAdd == null || scalar == 0) { return this; } return withDurationAdded(durationToAdd.getMillis(), scalar); } //----------------------------------------------------------------------- /** * Returns a new duration with this length plus that specified. * This instance is immutable and is not altered. *

* If the addition is zero, this instance is returned. * * @param amount the duration to add to this one * @return the new duration instance */ public Duration plus(long amount) { return withDurationAdded(amount, 1); } /** * Returns a new duration with this length plus that specified. * This instance is immutable and is not altered. *

* If the amount is zero, this instance is returned. * * @param amount the duration to add to this one, null means zero * @return the new duration instance */ public Duration plus(ReadableDuration amount) { if (amount == null) { return this; } return withDurationAdded(amount.getMillis(), 1); } /** * Returns a new duration with this length minus that specified. * This instance is immutable and is not altered. *

* If the addition is zero, this instance is returned. * * @param amount the duration to take away from this one * @return the new duration instance */ public Duration minus(long amount) { return withDurationAdded(amount, -1); } /** * Returns a new duration with this length minus that specified. * This instance is immutable and is not altered. *

* If the amount is zero, this instance is returned. * * @param amount the duration to take away from this one, null means zero * @return the new duration instance */ public Duration minus(ReadableDuration amount) { if (amount == null) { return this; } return withDurationAdded(amount.getMillis(), -1); } } joda-time-2.3/src/main/java/org/joda/time/DateTimeConstants.java0000644000175000017500000001610411564251363024121 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * DateTimeConstants is a non-instantiable class of constants used in * the date time system. These are the ISO8601 constants, but should be * used by all chronologies. *

* DateTimeConstants is thread-safe and immutable. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public class DateTimeConstants { // These are ints not enumerations as they represent genuine int values /** Constant (1) representing January, the first month (ISO) */ public static final int JANUARY = 1; /** Constant (2) representing February, the second month (ISO) */ public static final int FEBRUARY = 2; /** Constant (3) representing March, the third month (ISO) */ public static final int MARCH = 3; /** Constant (4) representing April, the fourth month (ISO) */ public static final int APRIL = 4; /** Constant (5) representing May, the fifth month (ISO) */ public static final int MAY = 5; /** Constant (6) representing June, the sixth month (ISO) */ public static final int JUNE = 6; /** Constant (7) representing July, the seventh month (ISO) */ public static final int JULY = 7; /** Constant (8) representing August, the eighth month (ISO) */ public static final int AUGUST = 8; /** Constant (9) representing September, the nineth month (ISO) */ public static final int SEPTEMBER = 9; /** Constant (10) representing October, the tenth month (ISO) */ public static final int OCTOBER = 10; /** Constant (11) representing November, the eleventh month (ISO) */ public static final int NOVEMBER = 11; /** Constant (12) representing December, the twelfth month (ISO) */ public static final int DECEMBER = 12; // These are ints not enumerations as they represent genuine int values /** Constant (1) representing Monday, the first day of the week (ISO) */ public static final int MONDAY = 1; /** Constant (2) representing Tuesday, the second day of the week (ISO) */ public static final int TUESDAY = 2; /** Constant (3) representing Wednesday, the third day of the week (ISO) */ public static final int WEDNESDAY = 3; /** Constant (4) representing Thursday, the fourth day of the week (ISO) */ public static final int THURSDAY = 4; /** Constant (5) representing Friday, the fifth day of the week (ISO) */ public static final int FRIDAY = 5; /** Constant (6) representing Saturday, the sixth day of the week (ISO) */ public static final int SATURDAY = 6; /** Constant (7) representing Sunday, the seventh day of the week (ISO) */ public static final int SUNDAY = 7; /** Constant (0) representing AM, the morning (from Calendar) */ public static final int AM = 0; /** Constant (1) representing PM, the afternoon (from Calendar) */ public static final int PM = 1; /** Constant (0) representing BC, years before zero (from Calendar) */ public static final int BC = 0; /** Alternative constant (0) representing BCE, Before Common Era (secular) */ public static final int BCE = 0; /** * Constant (1) representing AD, years after zero (from Calendar). *

* All new chronologies with differrent Era values should try to assign * eras as follows. The era that was in force at 1970-01-01 (ISO) is assigned * the value 1. Earlier eras are assigned sequentially smaller numbers. * Later eras are assigned sequentially greater numbers. */ public static final int AD = 1; /** * Alternative constant (1) representing CE, Common Era (secular). *

* All new chronologies with differrent Era values should try to assign * eras as follows. The era that was in force at 1970-01-01 (ISO) is assigned * the value 1. Earlier eras are assigned sequentially smaller numbers. * Later eras are assigned sequentially greater numbers. */ public static final int CE = 1; /** Milliseconds in one second (1000) (ISO) */ public static final int MILLIS_PER_SECOND = 1000; /** Seconds in one minute (60) (ISO) */ public static final int SECONDS_PER_MINUTE = 60; /** Milliseconds in one minute (ISO) */ public static final int MILLIS_PER_MINUTE = MILLIS_PER_SECOND * SECONDS_PER_MINUTE; /** Minutes in one hour (ISO) */ public static final int MINUTES_PER_HOUR = 60; /** Seconds in one hour (ISO) */ public static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; /** Milliseconds in one hour (ISO) */ public static final int MILLIS_PER_HOUR = MILLIS_PER_MINUTE * MINUTES_PER_HOUR; /** Hours in a typical day (24) (ISO). Due to time zone offset changes, the * number of hours per day can vary. */ public static final int HOURS_PER_DAY = 24; /** Minutes in a typical day (ISO). Due to time zone offset changes, the number * of minutes per day can vary. */ public static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY; /** Seconds in a typical day (ISO). Due to time zone offset changes, the number * of seconds per day can vary. */ public static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY; /** Milliseconds in a typical day (ISO). Due to time zone offset changes, the * number of milliseconds per day can vary. */ public static final int MILLIS_PER_DAY = MILLIS_PER_HOUR * HOURS_PER_DAY; /** Days in one week (7) (ISO) */ public static final int DAYS_PER_WEEK = 7; /** Hours in a typical week. Due to time zone offset changes, the number of * hours per week can vary. */ public static final int HOURS_PER_WEEK = HOURS_PER_DAY * DAYS_PER_WEEK; /** Minutes in a typical week (ISO). Due to time zone offset changes, the number * of minutes per week can vary. */ public static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * DAYS_PER_WEEK; /** Seconds in a typical week (ISO). Due to time zone offset changes, the number * of seconds per week can vary. */ public static final int SECONDS_PER_WEEK = SECONDS_PER_DAY * DAYS_PER_WEEK; /** Milliseconds in a typical week (ISO). Due to time zone offset changes, the * number of milliseconds per week can vary. */ public static final int MILLIS_PER_WEEK = MILLIS_PER_DAY * DAYS_PER_WEEK; /** * Restrictive constructor */ protected DateTimeConstants() { } } joda-time-2.3/src/main/java/org/joda/time/YearMonthDay.java0000644000175000017500000012535711616003375023103 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.joda.time.base.BasePartial; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractPartialFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISODateTimeFormat; /** * YearMonthDay is an immutable partial supporting the year, monthOfYear * and dayOfMonth fields. *

* NOTE: This class only supports the three fields listed above. Thus, you * cannot query the dayOfWeek or centuryOfEra fields for example. * The new LocalDate class removes this restriction. *

* Calculations on YearMonthDay are performed using a {@link Chronology}. * This chronology is set to be in the UTC time zone for all calculations. *

* Each individual field can be queried in two ways: *

    *
  • getMonthOfYear() *
  • monthOfYear().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value - monthOfYear().get() *
  • text value - monthOfYear().getAsText() *
  • short text value - monthOfYear().getAsShortText() *
  • maximum/minimum values - monthOfYear().getMaximumValue() *
  • add/subtract - monthOfYear().addToCopy() *
  • set - monthOfYear().setCopy() *
*

* YearMonthDay is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @since 1.0 * @deprecated Use LocalDate which has a much better internal implementation and * has been available since 1.3 */ @Deprecated public final class YearMonthDay extends BasePartial implements ReadablePartial, Serializable { /** Serialization version */ private static final long serialVersionUID = 797544782896179L; /** The singleton set of field types */ private static final DateTimeFieldType[] FIELD_TYPES = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth(), }; /** The index of the year field in the field array */ public static final int YEAR = 0; /** The index of the monthOfYear field in the field array */ public static final int MONTH_OF_YEAR = 1; /** The index of the dayOfMonth field in the field array */ public static final int DAY_OF_MONTH = 2; //----------------------------------------------------------------------- /** * Constructs a YearMonthDay from a java.util.Calendar * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Calendar and assigned to the YearMonthDay. * This is useful if you have been using the Calendar as a local date, * ignoing the zone. *

* This factory method ignores the type of the calendar and always * creates a YearMonthDay with ISO chronology. It is expected that you * will only pass in instances of GregorianCalendar however * this is not validated. * * @param calendar the Calendar to extract fields from * @return the created YearMonthDay * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology * @since 1.2 */ public static YearMonthDay fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } return new YearMonthDay( calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH) ); } /** * Constructs a YearMonthDay from a java.util.Date * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Date and assigned to the YearMonthDay. * This is useful if you have been using the Date as a local date, * ignoing the zone. *

* This factory method always creates a YearMonthDay with ISO chronology. * * @param date the Date to extract fields from * @return the created YearMonthDay * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology * @since 1.2 */ public static YearMonthDay fromDateFields(Date date) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } return new YearMonthDay( date.getYear() + 1900, date.getMonth() + 1, date.getDate() ); } //----------------------------------------------------------------------- /** * Constructs a YearMonthDay with the current date, using ISOChronology in * the default zone to extract the fields. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). */ public YearMonthDay() { super(); } /** * Constructs a YearMonthDay with the current date, using ISOChronology in * the specified zone to extract the fields. *

* The constructor uses the specified time zone to obtain the current date. * Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param zone the zone to use, null means default zone * @since 1.1 */ public YearMonthDay(DateTimeZone zone) { super(ISOChronology.getInstance(zone)); } /** * Constructs a YearMonthDay with the current date, using the specified chronology * and zone to extract the fields. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param chronology the chronology, null means ISOChronology in the default zone */ public YearMonthDay(Chronology chronology) { super(chronology); } /** * Constructs a YearMonthDay extracting the partial fields from the specified * milliseconds using the ISOChronology in the default zone. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public YearMonthDay(long instant) { super(instant); } /** * Constructs a YearMonthDay extracting the partial fields from the specified * milliseconds using the chronology provided. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in the default zone */ public YearMonthDay(long instant, Chronology chronology) { super(instant, chronology); } /** * Constructs a YearMonthDay from an Object that represents a time. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateOptionalTimeParser()}. *

* The chronology used will be derived from the object, defaulting to ISO. *

* NOTE: Prior to v1.3 the string format was described by * {@link ISODateTimeFormat#dateTimeParser()}. Time ony strings are now rejected. * * @param instant the datetime object, null means now * @throws IllegalArgumentException if the instant is invalid */ public YearMonthDay(Object instant) { super(instant, null, ISODateTimeFormat.dateOptionalTimeParser()); } /** * Constructs a YearMonthDay from an Object that represents a time, using the * specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateOptionalTimeParser()}. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * The specified chronology overrides that of the object. *

* NOTE: Prior to v1.3 the string format was described by * {@link ISODateTimeFormat#dateTimeParser()}. Time only strings are now rejected. * * @param instant the datetime object, null means now * @param chronology the chronology, null means ISO default * @throws IllegalArgumentException if the instant is invalid */ public YearMonthDay(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology), ISODateTimeFormat.dateOptionalTimeParser()); } /** * Constructs a YearMonthDay with specified time field values * using ISOChronology in the default zone. *

* The constructor uses the no time zone initialising the fields as provided. * Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month */ public YearMonthDay(int year, int monthOfYear, int dayOfMonth) { this(year, monthOfYear, dayOfMonth, null); } /** * Constructs a YearMonthDay with specified time field values. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param chronology the chronology, null means ISOChronology in the default zone */ public YearMonthDay(int year, int monthOfYear, int dayOfMonth, Chronology chronology) { super(new int[] {year, monthOfYear, dayOfMonth}, chronology); } /** * Constructs a YearMonthDay with chronology from this instance and new values. * * @param partial the partial to base this new instance on * @param values the new set of values */ YearMonthDay(YearMonthDay partial, int[] values) { super(partial, values); } /** * Constructs a YearMonthDay with values from this instance and a new chronology. * * @param partial the partial to base this new instance on * @param chrono the new chronology */ YearMonthDay(YearMonthDay partial, Chronology chrono) { super(partial, chrono); } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial. * * @return the field count */ public int size() { return 3; } /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field */ protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case YEAR: return chrono.year(); case MONTH_OF_YEAR: return chrono.monthOfYear(); case DAY_OF_MONTH: return chrono.dayOfMonth(); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public DateTimeFieldType getFieldType(int index) { return FIELD_TYPES[index]; } /** * Gets an array of the field type of each of the fields that this partial supports. *

* The fields are returned largest to smallest, Year, Month, Day * * @return the array of field types (cloned), largest to smallest */ public DateTimeFieldType[] getFieldTypes() { return (DateTimeFieldType[]) FIELD_TYPES.clone(); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified chronology. * This instance is immutable and unaffected by this method call. *

* This method retains the values of the fields, thus the result will * typically refer to a different instant. *

* The time zone of the specified chronology is ignored, as YearMonthDay * operates without a time zone. * * @param newChronology the new chronology, null means ISO * @return a copy of this datetime with a different chronology * @throws IllegalArgumentException if the values are invalid for the new chronology */ public YearMonthDay withChronologyRetainFields(Chronology newChronology) { newChronology = DateTimeUtils.getChronology(newChronology); newChronology = newChronology.withUTC(); if (newChronology == getChronology()) { return this; } else { YearMonthDay newYearMonthDay = new YearMonthDay(this, newChronology); newChronology.validate(newYearMonthDay, getValues()); return newYearMonthDay; } } /** * Returns a copy of this date with the specified field set to a new value. *

* For example, if the field type is dayOfMonth then the day * would be changed in the returned instance. *

* These three lines are equivalent: *

     * YearMonthDay updated = ymd.withField(DateTimeFieldType.dayOfMonth(), 6);
     * YearMonthDay updated = ymd.dayOfMonth().setCopy(6);
     * YearMonthDay updated = ymd.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this instance with the field set * @throws IllegalArgumentException if the value is null or invalid */ public YearMonthDay withField(DateTimeFieldType fieldType, int value) { int index = indexOfSupported(fieldType); if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new YearMonthDay(this, newValues); } /** * Returns a copy of this date with the value of the specified field increased. *

* If the addition is zero, then this is returned. *

* These three lines are equivalent: *

     * YearMonthDay added = ymd.withFieldAdded(DurationFieldType.days(), 6);
     * YearMonthDay added = ymd.plusDays(6);
     * YearMonthDay added = ymd.dayOfMonth().addToCopy(6);
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this instance with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new datetime exceeds the capacity */ public YearMonthDay withFieldAdded(DurationFieldType fieldType, int amount) { int index = indexOfSupported(fieldType); if (amount == 0) { return this; } int[] newValues = getValues(); newValues = getField(index).add(this, index, newValues, amount); return new YearMonthDay(this, newValues); } /** * Returns a copy of this date with the specified period added. *

* If the addition is zero, then this is returned. * Fields in the period that aren't present in the partial are ignored. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusYears(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this instance with the period added * @throws ArithmeticException if the new datetime exceeds the capacity */ public YearMonthDay withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } int[] newValues = getValues(); for (int i = 0; i < period.size(); i++) { DurationFieldType fieldType = period.getFieldType(i); int index = indexOf(fieldType); if (index >= 0) { newValues = getField(index).add(this, index, newValues, FieldUtils.safeMultiply(period.getValue(i), scalar)); } } return new YearMonthDay(this, newValues); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified period added. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusYears(int)}. * * @param period the duration to add to this one, null means zero * @return a copy of this instance with the period added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public YearMonthDay plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this date plus the specified number of years. *

* This date instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonthDay added = dt.plusYears(6);
     * YearMonthDay added = dt.plus(Period.years(6));
     * YearMonthDay added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * 
* * @param years the amount of years to add, may be negative * @return the new date plus the increased years * @since 1.1 */ public YearMonthDay plusYears(int years) { return withFieldAdded(DurationFieldType.years(), years); } /** * Returns a copy of this date plus the specified number of months. *

* This date instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonthDay added = dt.plusMonths(6);
     * YearMonthDay added = dt.plus(Period.months(6));
     * YearMonthDay added = dt.withFieldAdded(DurationFieldType.months(), 6);
     * 
* * @param months the amount of months to add, may be negative * @return the new date plus the increased months * @since 1.1 */ public YearMonthDay plusMonths(int months) { return withFieldAdded(DurationFieldType.months(), months); } /** * Returns a copy of this date plus the specified number of days. *

* This date instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonthDay added = dt.plusDays(6);
     * YearMonthDay added = dt.plus(Period.days(6));
     * YearMonthDay added = dt.withFieldAdded(DurationFieldType.days(), 6);
     * 
* * @param days the amount of days to add, may be negative * @return the new date plus the increased days * @since 1.1 */ public YearMonthDay plusDays(int days) { return withFieldAdded(DurationFieldType.days(), days); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified period taken away. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusYears(int)}. * * @param period the period to reduce this instant by * @return a copy of this instance with the period taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public YearMonthDay minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this date minus the specified number of years. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonthDay subtracted = dt.minusYears(6);
     * YearMonthDay subtracted = dt.minus(Period.years(6));
     * YearMonthDay subtracted = dt.withFieldAdded(DurationFieldType.years(), -6);
     * 
* * @param years the amount of years to subtract, may be negative * @return the new datetime minus the increased years * @since 1.1 */ public YearMonthDay minusYears(int years) { return withFieldAdded(DurationFieldType.years(), FieldUtils.safeNegate(years)); } /** * Returns a copy of this date minus the specified number of months. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonthDay subtracted = dt.minusMonths(6);
     * YearMonthDay subtracted = dt.minus(Period.months(6));
     * YearMonthDay subtracted = dt.withFieldAdded(DurationFieldType.months(), -6);
     * 
* * @param months the amount of months to subtract, may be negative * @return the new datetime minus the increased months * @since 1.1 */ public YearMonthDay minusMonths(int months) { return withFieldAdded(DurationFieldType.months(), FieldUtils.safeNegate(months)); } /** * Returns a copy of this date minus the specified number of days. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonthDay subtracted = dt.minusDays(6);
     * YearMonthDay subtracted = dt.minus(Period.days(6));
     * YearMonthDay subtracted = dt.withFieldAdded(DurationFieldType.days(), -6);
     * 
* * @param days the amount of days to subtract, may be negative * @return the new datetime minus the increased days * @since 1.1 */ public YearMonthDay minusDays(int days) { return withFieldAdded(DurationFieldType.days(), FieldUtils.safeNegate(days)); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains * many useful methods. * * @param type the field type to get the property for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType type) { return new Property(this, indexOfSupported(type)); } //----------------------------------------------------------------------- /** * Converts this object to a LocalDate with the same date and chronology. * * @return a LocalDate with the same date and chronology * @since 1.3 */ public LocalDate toLocalDate() { return new LocalDate(getYear(), getMonthOfYear(), getDayOfMonth(), getChronology()); } //----------------------------------------------------------------------- /** * Converts this YearMonthDay to a full datetime at midnight using the * default time zone. * * @return this date as a datetime at midnight */ public DateTime toDateTimeAtMidnight() { return toDateTimeAtMidnight(null); } /** * Converts this YearMonthDay to a full datetime at midnight using the * specified time zone. *

* This method uses the chronology from this instance plus the time zone * specified. * * @param zone the zone to use, null means default * @return this date as a datetime at midnight */ public DateTime toDateTimeAtMidnight(DateTimeZone zone) { Chronology chrono = getChronology().withZone(zone); return new DateTime(getYear(), getMonthOfYear(), getDayOfMonth(), 0, 0, 0, 0, chrono); } //----------------------------------------------------------------------- /** * Converts this partial to a full datetime using the default time zone * setting the date fields from this instance and the time fields from * the current time. * * @return this date as a datetime with the time as the current time */ public DateTime toDateTimeAtCurrentTime() { return toDateTimeAtCurrentTime(null); } /** * Converts this partial to a full datetime using the specified time zone * setting the date fields from this instance and the time fields from * the current time. *

* This method uses the chronology from this instance plus the time zone * specified. * * @param zone the zone to use, null means default * @return this date as a datetime with the time as the current time */ public DateTime toDateTimeAtCurrentTime(DateTimeZone zone) { Chronology chrono = getChronology().withZone(zone); long instantMillis = DateTimeUtils.currentTimeMillis(); long resolved = chrono.set(this, instantMillis); return new DateTime(resolved, chrono); } //----------------------------------------------------------------------- /** * Converts this object to a DateMidnight in the default time zone. * * @return the DateMidnight instance in the default zone */ public DateMidnight toDateMidnight() { return toDateMidnight(null); } /** * Converts this object to a DateMidnight. * * @param zone the zone to get the DateMidnight in, null means default * @return the DateMidnight instance */ public DateMidnight toDateMidnight(DateTimeZone zone) { Chronology chrono = getChronology().withZone(zone); return new DateMidnight(getYear(), getMonthOfYear(), getDayOfMonth(), chrono); } //----------------------------------------------------------------------- /** * Converts this object to a DateTime using a TimeOfDay to fill in the * missing fields and using the default time zone. * This instance is immutable and unaffected by this method call. *

* The resulting chronology is determined by the chronology of this * YearMonthDay plus the time zone. * The chronology of the time is ignored - only the field values are used. * * @param time the time of day to use, null means current time * @return the DateTime instance */ public DateTime toDateTime(TimeOfDay time) { return toDateTime(time, null); } /** * Converts this object to a DateTime using a TimeOfDay to fill in the * missing fields. * This instance is immutable and unaffected by this method call. *

* The resulting chronology is determined by the chronology of this * YearMonthDay plus the time zone. * The chronology of the time is ignored - only the field values are used. * * @param time the time of day to use, null means current time * @param zone the zone to get the DateTime in, null means default * @return the DateTime instance */ public DateTime toDateTime(TimeOfDay time, DateTimeZone zone) { Chronology chrono = getChronology().withZone(zone); long instant = DateTimeUtils.currentTimeMillis(); instant = chrono.set(this, instant); if (time != null) { instant = chrono.set(time, instant); } return new DateTime(instant, chrono); } //----------------------------------------------------------------------- /** * Converts this object to an Interval representing the whole day * in the default time zone. * * @return a interval over the day */ public Interval toInterval() { return toInterval(null); } /** * Converts this object to an Interval representing the whole day. * * @param zone the zone to get the Interval in, null means default * @return a interval over the day */ public Interval toInterval(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); return toDateMidnight(zone).toInterval(); } //----------------------------------------------------------------------- /** * Get the year field value. * * @return the year */ public int getYear() { return getValue(YEAR); } /** * Get the month of year field value. * * @return the month of year */ public int getMonthOfYear() { return getValue(MONTH_OF_YEAR); } /** * Get the day of month field value. * * @return the day of month */ public int getDayOfMonth() { return getValue(DAY_OF_MONTH); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the year field updated. *

* YearMonthDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year changed. * * @param year the year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public YearMonthDay withYear(int year) { int[] newValues = getValues(); newValues = getChronology().year().set(this, YEAR, newValues, year); return new YearMonthDay(this, newValues); } /** * Returns a copy of this date with the month of year field updated. *

* YearMonthDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public YearMonthDay withMonthOfYear(int monthOfYear) { int[] newValues = getValues(); newValues = getChronology().monthOfYear().set(this, MONTH_OF_YEAR, newValues, monthOfYear); return new YearMonthDay(this, newValues); } /** * Returns a copy of this date with the day of month field updated. *

* YearMonthDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of month changed. * * @param dayOfMonth the day of month to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public YearMonthDay withDayOfMonth(int dayOfMonth) { int[] newValues = getValues(); newValues = getChronology().dayOfMonth().set(this, DAY_OF_MONTH, newValues, dayOfMonth); return new YearMonthDay(this, newValues); } //----------------------------------------------------------------------- /** * Get the year field property which provides access to advanced functionality. * * @return the year property */ public Property year() { return new Property(this, YEAR); } /** * Get the month of year field property which provides access to advanced functionality. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, MONTH_OF_YEAR); } /** * Get the day of month field property which provides access to advanced functionality. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, DAY_OF_MONTH); } //----------------------------------------------------------------------- /** * Output the date in the ISO8601 format YYYY-MM-DD. * * @return ISO8601 formatted string */ public String toString() { return ISODateTimeFormat.yearMonthDay().print(this); } //----------------------------------------------------------------------- /** * The property class for YearMonthDay. *

* This class binds a YearMonthDay to a DateTimeField. * * @author Stephen Colebourne * @since 1.0 * @deprecated Use LocalDate which has a much better internal implementation */ @Deprecated public static class Property extends AbstractPartialFieldProperty implements Serializable { /** Serialization version */ private static final long serialVersionUID = 5727734012190224363L; /** The partial */ private final YearMonthDay iYearMonthDay; /** The field index */ private final int iFieldIndex; /** * Constructs a property. * * @param partial the partial instance * @param fieldIndex the index in the partial */ Property(YearMonthDay partial, int fieldIndex) { super(); iYearMonthDay = partial; iFieldIndex = fieldIndex; } /** * Gets the field that this property uses. * * @return the field */ public DateTimeField getField() { return iYearMonthDay.getField(iFieldIndex); } /** * Gets the partial that this property belongs to. * * @return the partial */ protected ReadablePartial getReadablePartial() { return iYearMonthDay; } /** * Gets the partial that this property belongs to. * * @return the partial */ public YearMonthDay getYearMonthDay() { return iYearMonthDay; } /** * Gets the value of this field. * * @return the field value */ public int get() { return iYearMonthDay.getValue(iFieldIndex); } //----------------------------------------------------------------------- /** * Adds to the value of this field in a copy of this YearMonthDay. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it will affect larger fields. * Smaller fields are unaffected. *

* If the result would be too large, beyond the maximum year, then an * IllegalArgumentException is thrown. *

* The YearMonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the YearMonthDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public YearMonthDay addToCopy(int valueToAdd) { int[] newValues = iYearMonthDay.getValues(); newValues = getField().add(iYearMonthDay, iFieldIndex, newValues, valueToAdd); return new YearMonthDay(iYearMonthDay, newValues); } /** * Adds to the value of this field in a copy of this YearMonthDay wrapping * within this field if the maximum value is reached. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps within this field. * Other fields are unaffected. *

* For example, * 2004-12-20 addWrapField one month returns 2004-01-20. *

* The YearMonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the YearMonthDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public YearMonthDay addWrapFieldToCopy(int valueToAdd) { int[] newValues = iYearMonthDay.getValues(); newValues = getField().addWrapField(iYearMonthDay, iFieldIndex, newValues, valueToAdd); return new YearMonthDay(iYearMonthDay, newValues); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the YearMonthDay. *

* The YearMonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param value the value to set the field in the copy to * @return a copy of the YearMonthDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public YearMonthDay setCopy(int value) { int[] newValues = iYearMonthDay.getValues(); newValues = getField().set(iYearMonthDay, iFieldIndex, newValues, value); return new YearMonthDay(iYearMonthDay, newValues); } /** * Sets this field in a copy of the YearMonthDay to a parsed text value. *

* The YearMonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the YearMonthDay with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public YearMonthDay setCopy(String text, Locale locale) { int[] newValues = iYearMonthDay.getValues(); newValues = getField().set(iYearMonthDay, iFieldIndex, newValues, text, locale); return new YearMonthDay(iYearMonthDay, newValues); } /** * Sets this field in a copy of the YearMonthDay to a parsed text value. *

* The YearMonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @return a copy of the YearMonthDay with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public YearMonthDay setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new YearMonthDay with this field set to the maximum value * for this field. *

* This operation is useful for obtaining a DateTime on the last day * of the month, as month lengths vary. *

         * YearMonthDay lastDayOfMonth = dt.dayOfMonth().withMaximumValue();
         * 
*

* The YearMonthDay attached to this property is unchanged by this call. * * @return a copy of the YearMonthDay with this field set to its maximum * @since 1.2 */ public YearMonthDay withMaximumValue() { return setCopy(getMaximumValue()); } /** * Returns a new YearMonthDay with this field set to the minimum value * for this field. *

* The YearMonthDay attached to this property is unchanged by this call. * * @return a copy of the YearMonthDay with this field set to its minimum * @since 1.2 */ public YearMonthDay withMinimumValue() { return setCopy(getMinimumValue()); } } } joda-time-2.3/src/main/java/org/joda/time/ReadableInstant.java0000644000175000017500000001522611564251363023574 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines an instant in the datetime continuum. * This interface expresses the datetime as milliseconds from 1970-01-01T00:00:00Z. *

* The implementation of this interface may be mutable or immutable. * This interface only gives access to retrieve data, never to change it. *

* Methods in your application should be defined using ReadableInstant * as a parameter if the method only wants to read the instant without needing to know * the specific datetime fields. *

* The {@code compareTo} method is no longer defined in this class in version 2.0. * Instead, the definition is simply inherited from the {@code Comparable} interface. * This approach is necessary to preserve binary compatibility. * The definition of the comparison is ascending order by millisecond instant. * Implementors are recommended to extend {@code AbstractInstant} instead of this interface. * * @author Stephen Colebourne * @since 1.0 */ public interface ReadableInstant extends Comparable { /** * Get the value as the number of milliseconds since * the epoch, 1970-01-01T00:00:00Z. * * @return the value as milliseconds */ long getMillis(); /** * Gets the chronology of the instant. *

* The {@link Chronology} provides conversion from the millisecond * value to meaningful fields in a particular calendar system. * * @return the Chronology, never null */ Chronology getChronology(); /** * Gets the time zone of the instant from the chronology. * * @return the DateTimeZone that the instant is using, never null */ DateTimeZone getZone(); /** * Get the value of one of the fields of a datetime. *

* This method uses the chronology of the instant to obtain the value. * * @param type a field type, usually obtained from DateTimeFieldType, not null * @return the value of that field * @throws IllegalArgumentException if the field type is null */ int get(DateTimeFieldType type); /** * Checks whether the field type specified is supported by this implementation. * * @param field the field type to check, may be null which returns false * @return true if the field is supported */ boolean isSupported(DateTimeFieldType field); //----------------------------------------------------------------------- /** * Get the value as a simple immutable Instant object. *

* This can be useful if you don't trust the implementation * of the interface to be well-behaved, or to get a guaranteed * immutable object. * * @return the value as an Instant object */ Instant toInstant(); //----------------------------------------------------------------------- // Method is no longer defined here as that would break generic backwards compatibility // /** // * Compares this object with the specified object for ascending // * millisecond instant order. This ordering is inconsistent with // * equals, as it ignores the Chronology. // *

// * All ReadableInstant instances are accepted. // * // * @param readableInstant a readable instant to check against // * @return negative value if this is less, 0 if equal, or positive value if greater // * @throws NullPointerException if the object is null // * @throws ClassCastException if the object type is not supported // */ // int compareTo(ReadableInstant readableInstant); //----------------------------------------------------------------------- /** * Is this instant equal to the instant passed in * comparing solely by millisecond. * * @param instant an instant to check against, null means now * @return true if the instant is equal to the instant passed in */ boolean isEqual(ReadableInstant instant); /** * Is this instant after the instant passed in * comparing solely by millisecond. * * @param instant an instant to check against, null means now * @return true if the instant is after the instant passed in */ boolean isAfter(ReadableInstant instant); /** * Is this instant before the instant passed in * comparing solely by millisecond. * * @param instant an instant to check against, null means now * @return true if the instant is before the instant passed in */ boolean isBefore(ReadableInstant instant); //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the millisecond instant and the Chronology. All ReadableInstant * instances are accepted. *

* To compare two instants for absolute time (ie. UTC milliseconds * ignoring the chronology), use {@link #isEqual(ReadableInstant)} or * {@link #compareTo(Object)}. * * @param readableInstant a readable instant to check against * @return true if millisecond and chronology are equal, false if * not or the instant is null or of an incorrect type */ boolean equals(Object readableInstant); /** * Gets a hash code for the instant that is compatible with the * equals method. *

* The formula used must be as follows: *

     * ((int) (getMillis() ^ (getMillis() >>> 32))) +
     * (getChronology().hashCode())
     * 
* * @return a hash code as defined above */ int hashCode(); //----------------------------------------------------------------------- /** * Get the value as a String in a recognisable ISO8601 format. *

* The string output is in ISO8601 format to enable the String * constructor to correctly parse it. * * @return the value as an ISO8601 string */ String toString(); } joda-time-2.3/src/main/java/org/joda/time/MutableInterval.java0000644000175000017500000004051411564251363023630 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import org.joda.time.base.BaseInterval; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISOPeriodFormat; /** * MutableInterval is the standard implementation of a mutable time interval. *

* A time interval represents a period of time between two instants. * Intervals are inclusive of the start instant and exclusive of the end. * The end instant is always greater than or equal to the start instant. *

* Intervals have a fixed millisecond duration. * This is the difference between the start and end instants. * The duration is represented separately by {@link ReadableDuration}. * As a result, intervals are not comparable. * To compare the length of two intervals, you should compare their durations. *

* An interval can also be converted to a {@link ReadablePeriod}. * This represents the difference between the start and end points in terms of fields * such as years and days. *

* If performing significant calculations on an interval, it may be faster to * convert an Interval object to a MutableInterval one. *

* MutableInterval is mutable and not thread-safe, unless concurrent threads * are not invoking mutator methods. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public class MutableInterval extends BaseInterval implements ReadWritableInterval, Cloneable, Serializable { /** Serialization version */ private static final long serialVersionUID = -5982824024992428470L; //----------------------------------------------------------------------- /** * Parses a {@code MutableInterval} from the specified string. *

* The String formats are described by {@link ISODateTimeFormat#dateTimeParser()} * and {@link ISOPeriodFormat#standard()}, and may be 'datetime/datetime', * 'datetime/period' or 'period/datetime'. * * @param str the string to parse, not null * @since 2.0 */ public static MutableInterval parse(String str) { return new MutableInterval(str); } //----------------------------------------------------------------------- /** * Constructs a zero length time interval from 1970-01-01 to 1970-01-01. */ public MutableInterval() { super(0L, 0L, null); } /** * Constructs an interval from a start and end instant with the ISO default chronology. * * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @throws IllegalArgumentException if the end is before the start */ public MutableInterval(long startInstant, long endInstant) { super(startInstant, endInstant, null); } /** * Constructs an interval from a start and end instant with a chronology. * * @param chronology the chronology to use, null is ISO default * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @throws IllegalArgumentException if the end is before the start */ public MutableInterval(long startInstant, long endInstant, Chronology chronology) { super(startInstant, endInstant, chronology); } /** * Constructs an interval from a start and end instant. *

* The chronology used is that of the start instant. * * @param start start of this interval, null means now * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start */ public MutableInterval(ReadableInstant start, ReadableInstant end) { super(start, end); } /** * Constructs an interval from a start instant and a duration. * * @param start start of this interval, null means now * @param duration the duration of this interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ public MutableInterval(ReadableInstant start, ReadableDuration duration) { super(start, duration); } /** * Constructs an interval from a millisecond duration and an end instant. * * @param duration the duration of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ public MutableInterval(ReadableDuration duration, ReadableInstant end) { super(duration, end); } /** * Constructs an interval from a start instant and a time period. *

* When forming the interval, the chronology from the instant is used * if present, otherwise the chronology of the period is used. * * @param start start of this interval, null means now * @param period the period of this interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ public MutableInterval(ReadableInstant start, ReadablePeriod period) { super(start, period); } /** * Constructs an interval from a time period and an end instant. *

* When forming the interval, the chronology from the instant is used * if present, otherwise the chronology of the period is used. * * @param period the period of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ public MutableInterval(ReadablePeriod period, ReadableInstant end) { super(period, end); } /** * Constructs a time interval by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInterval and String. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()} * and {@link ISOPeriodFormat#standard()}, and may be 'datetime/datetime', * 'datetime/period' or 'period/datetime'. * * @param interval the time interval to copy * @throws IllegalArgumentException if the interval is invalid */ public MutableInterval(Object interval) { super(interval, null); } /** * Constructs a time interval by converting or copying from another object, * overriding the chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInterval and String. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()} * and {@link ISOPeriodFormat#standard()}, and may be 'datetime/datetime', * 'datetime/period' or 'period/datetime'. * * @param interval the time interval to copy * @param chronology the chronology to use, null means ISO default * @throws IllegalArgumentException if the interval is invalid */ public MutableInterval(Object interval, Chronology chronology) { super(interval, chronology); } //----------------------------------------------------------------------- /** * Sets this interval from two millisecond instants retaining the chronology. * * @param startInstant the start of the time interval * @param endInstant the start of the time interval * @throws IllegalArgumentException if the end is before the start */ public void setInterval(long startInstant, long endInstant) { super.setInterval(startInstant, endInstant, getChronology()); } /** * Sets this interval to be the same as another. * * @param interval the interval to copy * @throws IllegalArgumentException if the interval is null */ public void setInterval(ReadableInterval interval) { if (interval == null) { throw new IllegalArgumentException("Interval must not be null"); } long startMillis = interval.getStartMillis(); long endMillis = interval.getEndMillis(); Chronology chrono = interval.getChronology(); super.setInterval(startMillis, endMillis, chrono); } /** * Sets this interval from two instants, replacing the chronology with * that from the start instant. * * @param start the start of the time interval * @param end the start of the time interval * @throws IllegalArgumentException if the end is before the start */ public void setInterval(ReadableInstant start, ReadableInstant end) { if (start == null && end == null) { long now = DateTimeUtils.currentTimeMillis(); setInterval(now, now); } else { long startMillis = DateTimeUtils.getInstantMillis(start); long endMillis = DateTimeUtils.getInstantMillis(end); Chronology chrono = DateTimeUtils.getInstantChronology(start); super.setInterval(startMillis, endMillis, chrono); } } //----------------------------------------------------------------------- /** * Sets the chronology of this time interval. * * @param chrono the chronology to use, null means ISO default */ public void setChronology(Chronology chrono) { super.setInterval(getStartMillis(), getEndMillis(), chrono); } /** * Sets the start of this time interval. * * @param startInstant the start of the time interval, * millisecond instant from 1970-01-01T00:00:00Z * @throws IllegalArgumentException if the end is before the start */ public void setStartMillis(long startInstant) { super.setInterval(startInstant, getEndMillis(), getChronology()); } /** * Sets the start of this time interval as an Instant. * * @param start the start of the time interval, null means now * @throws IllegalArgumentException if the end is before the start */ public void setStart(ReadableInstant start) { long startMillis = DateTimeUtils.getInstantMillis(start); super.setInterval(startMillis, getEndMillis(), getChronology()); } /** * Sets the end of this time interval. * * @param endInstant the end of the time interval, * millisecond instant from 1970-01-01T00:00:00Z * @throws IllegalArgumentException if the end is before the start */ public void setEndMillis(long endInstant) { super.setInterval(getStartMillis(), endInstant, getChronology()); } /** * Sets the end of this time interval as an Instant. * * @param end the end of the time interval, null means now * @throws IllegalArgumentException if the end is before the start */ public void setEnd(ReadableInstant end) { long endMillis = DateTimeUtils.getInstantMillis(end); super.setInterval(getStartMillis(), endMillis, getChronology()); } //----------------------------------------------------------------------- /** * Sets the duration of this time interval, preserving the start instant. * * @param duration new duration for interval * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ public void setDurationAfterStart(long duration) { setEndMillis(FieldUtils.safeAdd(getStartMillis(), duration)); } /** * Sets the duration of this time interval, preserving the end instant. * * @param duration new duration for interval * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ public void setDurationBeforeEnd(long duration) { setStartMillis(FieldUtils.safeAdd(getEndMillis(), -duration)); } //----------------------------------------------------------------------- /** * Sets the duration of this time interval, preserving the start instant. * * @param duration new duration for interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ public void setDurationAfterStart(ReadableDuration duration) { long durationMillis = DateTimeUtils.getDurationMillis(duration); setEndMillis(FieldUtils.safeAdd(getStartMillis(), durationMillis)); } /** * Sets the duration of this time interval, preserving the end instant. * * @param duration new duration for interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ public void setDurationBeforeEnd(ReadableDuration duration) { long durationMillis = DateTimeUtils.getDurationMillis(duration); setStartMillis(FieldUtils.safeAdd(getEndMillis(), -durationMillis)); } //----------------------------------------------------------------------- /** * Sets the period of this time interval, preserving the start instant * and using the ISOChronology in the default zone for calculations. * * @param period new period for interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ public void setPeriodAfterStart(ReadablePeriod period) { if (period == null) { setEndMillis(getStartMillis()); } else { setEndMillis(getChronology().add(period, getStartMillis(), 1)); } } /** * Sets the period of this time interval, preserving the end instant * and using the ISOChronology in the default zone for calculations. * * @param period new period for interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ public void setPeriodBeforeEnd(ReadablePeriod period) { if (period == null) { setStartMillis(getEndMillis()); } else { setStartMillis(getChronology().add(period, getEndMillis(), -1)); } } //----------------------------------------------------------------------- /** * Clone this object without having to cast the returned object. * * @return a clone of the this object. */ public MutableInterval copy() { return (MutableInterval) clone(); } /** * Clone this object. * * @return a clone of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError("Clone error"); } } } joda-time-2.3/src/main/java/org/joda/time/MutablePeriod.java0000644000175000017500000011765011640072445023271 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import org.joda.convert.FromString; import org.joda.time.base.BasePeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * Standard mutable time period implementation. *

* A time period is divided into a number of fields, such as hours and seconds. * Which fields are supported is defined by the PeriodType class. * The default is the standard period type, which supports years, months, weeks, days, * hours, minutes, seconds and millis. *

* When this time period is added to an instant, the effect is of adding each field in turn. * As a result, this takes into account daylight savings time. * Adding a time period of 1 day to the day before daylight savings starts will only add * 23 hours rather than 24 to ensure that the time remains the same. * If this is not the behaviour you want, then see {@link Duration}. *

* The definition of a period also affects the equals method. A period of 1 * day is not equal to a period of 24 hours, nor 1 hour equal to 60 minutes. * This is because periods represent an abstracted definition of a time period * (eg. a day may not actually be 24 hours, it might be 23 or 25 at daylight * savings boundary). To compare the actual duration of two periods, convert * both to durations using toDuration, an operation that emphasises that the * result may differ according to the date you choose. *

* MutablePeriod is mutable and not thread-safe, unless concurrent threads * are not invoking mutator methods. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 * @see Period */ public class MutablePeriod extends BasePeriod implements ReadWritablePeriod, Cloneable, Serializable { /** Serialization version */ private static final long serialVersionUID = 3436451121567212165L; //----------------------------------------------------------------------- /** * Parses a {@code MutablePeriod} from the specified string. *

* This uses {@link ISOPeriodFormat#standard()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static MutablePeriod parse(String str) { return parse(str, ISOPeriodFormat.standard()); } /** * Parses a {@code MutablePeriod} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static MutablePeriod parse(String str, PeriodFormatter formatter) { return formatter.parsePeriod(str).toMutablePeriod(); } //----------------------------------------------------------------------- /** * Creates a zero-length period using the standard period type. */ public MutablePeriod() { super(0L, null, null); } /** * Creates a zero-length period using the specified period type. * * @param type which set of fields this period supports */ public MutablePeriod(PeriodType type) { super(0L, type, null); } /** * Create a period from a set of field values using the standard set of fields. * * @param hours amount of hours in this period * @param minutes amount of minutes in this period * @param seconds amount of seconds in this period * @param millis amount of milliseconds in this period */ public MutablePeriod(int hours, int minutes, int seconds, int millis) { super(0, 0, 0, 0, hours, minutes, seconds, millis, PeriodType.standard()); } /** * Create a period from a set of field values using the standard set of fields. * * @param years amount of years in this period * @param months amount of months in this period * @param weeks amount of weeks in this period * @param days amount of days in this period * @param hours amount of hours in this period * @param minutes amount of minutes in this period * @param seconds amount of seconds in this period * @param millis amount of milliseconds in this period */ public MutablePeriod(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { super(years, months, weeks, days, hours, minutes, seconds, millis, PeriodType.standard()); } /** * Create a period from a set of field values. * * @param years amount of years in this period, which must be zero if unsupported * @param months amount of months in this period, which must be zero if unsupported * @param weeks amount of weeks in this period, which must be zero if unsupported * @param days amount of days in this period, which must be zero if unsupported * @param hours amount of hours in this period, which must be zero if unsupported * @param minutes amount of minutes in this period, which must be zero if unsupported * @param seconds amount of seconds in this period, which must be zero if unsupported * @param millis amount of milliseconds in this period, which must be zero if unsupported * @param type which set of fields this period supports, null means AllType * @throws IllegalArgumentException if an unsupported field's value is non-zero */ public MutablePeriod(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis, PeriodType type) { super(years, months, weeks, days, hours, minutes, seconds, millis, type); } /** * Creates a period from the given millisecond duration using the standard * set of fields. *

* Only precise fields in the period type will be used. * For the standard period type this is the time fields only. * Thus the year, month, week and day fields will not be populated. *

* If the duration is small, less than one day, then this method will perform * as you might expect and split the fields evenly. *

* If the duration is larger than one day then all the remaining duration will * be stored in the largest available precise field, hours in this case. *

* For example, a duration equal to (365 + 60 + 5) days will be converted to * ((365 + 60 + 5) * 24) hours by this constructor. *

* For more control over the conversion process, you have two options: *

    *
  • convert the duration to an {@link Interval}, and from there obtain the period *
  • specify a period type that contains precise definitions of the day and larger * fields, such as the UTC or precise types. *
* * @param duration the duration, in milliseconds */ public MutablePeriod(long duration) { super(duration); } /** * Creates a period from the given millisecond duration. *

* Only precise fields in the period type will be used. * Imprecise fields will not be populated. *

* If the duration is small then this method will perform * as you might expect and split the fields evenly. *

* If the duration is large then all the remaining duration will * be stored in the largest available precise field. * For details as to which fields are precise, review the period type javadoc. * * @param duration the duration, in milliseconds * @param type which set of fields this period supports, null means standard */ public MutablePeriod(long duration, PeriodType type) { super(duration, type, null); } /** * Creates a period from the given millisecond duration using the standard * set of fields. *

* Only precise fields in the period type will be used. * Imprecise fields will not be populated. *

* If the duration is small then this method will perform * as you might expect and split the fields evenly. *

* If the duration is large then all the remaining duration will * be stored in the largest available precise field. * For details as to which fields are precise, review the period type javadoc. * * @param duration the duration, in milliseconds * @param chronology the chronology to use to split the duration, null means ISO default */ public MutablePeriod(long duration, Chronology chronology) { super(duration, null, chronology); } /** * Creates a period from the given millisecond duration. *

* Only precise fields in the period type will be used. * Imprecise fields will not be populated. *

* If the duration is small then this method will perform * as you might expect and split the fields evenly. *

* If the duration is large then all the remaining duration will * be stored in the largest available precise field. * For details as to which fields are precise, review the period type javadoc. * * @param duration the duration, in milliseconds * @param type which set of fields this period supports, null means standard * @param chronology the chronology to use to split the duration, null means ISO default */ public MutablePeriod(long duration, PeriodType type, Chronology chronology) { super(duration, type, chronology); } /** * Creates a period from the given interval endpoints using the standard * set of fields. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ public MutablePeriod(long startInstant, long endInstant) { super(startInstant, endInstant, null, null); } /** * Creates a period from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param type which set of fields this period supports, null means standard */ public MutablePeriod(long startInstant, long endInstant, PeriodType type) { super(startInstant, endInstant, type, null); } /** * Creates a period from the given interval endpoints using the standard * set of fields. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param chrono the chronology to use, null means ISO in default zone */ public MutablePeriod(long startInstant, long endInstant, Chronology chrono) { super(startInstant, endInstant, null, chrono); } /** * Creates a period from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param type which set of fields this period supports, null means standard * @param chrono the chronology to use, null means ISO in default zone */ public MutablePeriod(long startInstant, long endInstant, PeriodType type, Chronology chrono) { super(startInstant, endInstant, type, chrono); } /** * Creates a period from the given interval endpoints using the standard * set of fields. *

* The chronology of the start instant is used, unless that is null when the * chronology of the end instant is used instead. * * @param startInstant interval start, null means now * @param endInstant interval end, null means now */ public MutablePeriod(ReadableInstant startInstant, ReadableInstant endInstant) { super(startInstant, endInstant, null); } /** * Creates a period from the given interval endpoints. *

* The chronology of the start instant is used, unless that is null when the * chronology of the end instant is used instead. * * @param startInstant interval start, null means now * @param endInstant interval end, null means now * @param type which set of fields this period supports, null means AllType */ public MutablePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) { super(startInstant, endInstant, type); } /** * Creates a period from the given start point and the duration. * * @param startInstant the interval start, null means now * @param duration the duration of the interval, null means zero-length */ public MutablePeriod(ReadableInstant startInstant, ReadableDuration duration) { super(startInstant, duration, null); } /** * Creates a period from the given start point and the duration. * * @param startInstant the interval start, null means now * @param duration the duration of the interval, null means zero-length * @param type which set of fields this period supports, null means standard */ public MutablePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { super(startInstant, duration, type); } /** * Creates a period from the given duration and end point. * * @param duration the duration of the interval, null means zero-length * @param endInstant the interval end, null means now */ public MutablePeriod(ReadableDuration duration, ReadableInstant endInstant) { super(duration, endInstant, null); } /** * Creates a period from the given duration and end point. * * @param duration the duration of the interval, null means zero-length * @param endInstant the interval end, null means now * @param type which set of fields this period supports, null means standard */ public MutablePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) { super(duration, endInstant, type); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public MutablePeriod(Object period) { super(period, null, null); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @param type which set of fields this period supports, null means use converter * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public MutablePeriod(Object period, PeriodType type) { super(period, type, null); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @param chrono the chronology to use, null means ISO in default zone * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public MutablePeriod(Object period, Chronology chrono) { super(period, null, chrono); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @param type which set of fields this period supports, null means use converter * @param chrono the chronology to use, null means ISO in default zone * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public MutablePeriod(Object period, PeriodType type, Chronology chrono) { super(period, type, chrono); } //----------------------------------------------------------------------- /** * Clears the period, setting all values back to zero. */ public void clear() { super.setValues(new int[size()]); } /** * Sets the value of one of the fields by index. * * @param index the field index * @param value the new value for the field * @throws IndexOutOfBoundsException if the index is invalid */ public void setValue(int index, int value) { super.setValue(index, value); } /** * Sets the value of one of the fields. *

* The field type specified must be one of those that is supported by the period. * * @param field a DurationFieldType instance that is supported by this period, not null * @param value the new value for the field * @throws IllegalArgumentException if the field is null or not supported */ public void set(DurationFieldType field, int value) { super.setField(field, value); } /** * Sets all the fields in one go from another ReadablePeriod. * * @param period the period to set, null means zero length period * @throws IllegalArgumentException if an unsupported field's value is non-zero */ public void setPeriod(ReadablePeriod period) { super.setPeriod(period); } /** * Sets all the fields in one go. * * @param years amount of years in this period, which must be zero if unsupported * @param months amount of months in this period, which must be zero if unsupported * @param weeks amount of weeks in this period, which must be zero if unsupported * @param days amount of days in this period, which must be zero if unsupported * @param hours amount of hours in this period, which must be zero if unsupported * @param minutes amount of minutes in this period, which must be zero if unsupported * @param seconds amount of seconds in this period, which must be zero if unsupported * @param millis amount of milliseconds in this period, which must be zero if unsupported * @throws IllegalArgumentException if an unsupported field's value is non-zero */ public void setPeriod(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { super.setPeriod(years, months, weeks, days, hours, minutes, seconds, millis); } /** * Sets all the fields in one go from an interval using the ISO chronology * and dividing the fields using the period type. * * @param interval the interval to set, null means zero length * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(ReadableInterval interval) { if (interval == null) { setPeriod(0L); } else { Chronology chrono = DateTimeUtils.getChronology(interval.getChronology()); setPeriod(interval.getStartMillis(), interval.getEndMillis(), chrono); } } /** * Sets all the fields in one go from two instants representing an interval. *

* The chronology of the start instant is used, unless that is null when the * chronology of the end instant is used instead. * * @param start the start instant, null means now * @param end the end instant, null means now * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(ReadableInstant start, ReadableInstant end) { if (start == end) { setPeriod(0L); } else { long startMillis = DateTimeUtils.getInstantMillis(start); long endMillis = DateTimeUtils.getInstantMillis(end); Chronology chrono = DateTimeUtils.getIntervalChronology(start, end); setPeriod(startMillis, endMillis, chrono); } } /** * Sets all the fields in one go from a millisecond interval using ISOChronology * and dividing the fields using the period type. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(long startInstant, long endInstant) { setPeriod(startInstant, endInstant, null); } /** * Sets all the fields in one go from a millisecond interval. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param chrono the chronology to use, null means ISO chronology * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(long startInstant, long endInstant, Chronology chrono) { chrono = DateTimeUtils.getChronology(chrono); setValues(chrono.get(this, startInstant, endInstant)); } /** * Sets all the fields in one go from a duration dividing the * fields using the period type. *

* When dividing the duration, only precise fields in the period type will be used. * For large durations, all the remaining duration will be stored in the largest * available precise field. * * @param duration the duration to set, null means zero length * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(ReadableDuration duration) { setPeriod(duration, null); } /** * Sets all the fields in one go from a duration dividing the * fields using the period type. *

* When dividing the duration, only precise fields in the period type will be used. * For large durations, all the remaining duration will be stored in the largest * available precise field. * * @param duration the duration to set, null means zero length * @param chrono the chronology to use, null means ISO default * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(ReadableDuration duration, Chronology chrono) { long durationMillis = DateTimeUtils.getDurationMillis(duration); setPeriod(durationMillis, chrono); } /** * Sets all the fields in one go from a millisecond duration dividing the * fields using the period type. *

* When dividing the duration, only precise fields in the period type will be used. * For large durations, all the remaining duration will be stored in the largest * available precise field. * * @param duration the duration, in milliseconds * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(long duration) { setPeriod(duration, null); } /** * Sets all the fields in one go from a millisecond duration. *

* When dividing the duration, only precise fields in the period type will be used. * For large durations, all the remaining duration will be stored in the largest * available precise field. * * @param duration the duration, in milliseconds * @param chrono the chronology to use, null means ISO chronology * @throws ArithmeticException if the set exceeds the capacity of the period */ public void setPeriod(long duration, Chronology chrono) { chrono = DateTimeUtils.getChronology(chrono); setValues(chrono.get(this, duration)); } //----------------------------------------------------------------------- /** * Adds to the value of one of the fields. *

* The field type specified must be one of those that is supported by the period. * * @param field a DurationFieldType instance that is supported by this period, not null * @param value the value to add to the field * @throws IllegalArgumentException if the field is null or not supported */ public void add(DurationFieldType field, int value) { super.addField(field, value); } /** * Adds a period to this one by adding each field in turn. * * @param period the period to add, null means add nothing * @throws IllegalArgumentException if the period being added contains a field * not supported by this period * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void add(ReadablePeriod period) { super.addPeriod(period); } /** * Adds to each field of this period. * * @param years amount of years to add to this period, which must be zero if unsupported * @param months amount of months to add to this period, which must be zero if unsupported * @param weeks amount of weeks to add to this period, which must be zero if unsupported * @param days amount of days to add to this period, which must be zero if unsupported * @param hours amount of hours to add to this period, which must be zero if unsupported * @param minutes amount of minutes to add to this period, which must be zero if unsupported * @param seconds amount of seconds to add to this period, which must be zero if unsupported * @param millis amount of milliseconds to add to this period, which must be zero if unsupported * @throws IllegalArgumentException if the period being added contains a field * not supported by this period * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void add(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { setPeriod( FieldUtils.safeAdd(getYears(), years), FieldUtils.safeAdd(getMonths(), months), FieldUtils.safeAdd(getWeeks(), weeks), FieldUtils.safeAdd(getDays(), days), FieldUtils.safeAdd(getHours(), hours), FieldUtils.safeAdd(getMinutes(), minutes), FieldUtils.safeAdd(getSeconds(), seconds), FieldUtils.safeAdd(getMillis(), millis) ); } /** * Adds an interval to this one by dividing the interval into * fields and calling {@link #add(ReadablePeriod)}. * * @param interval the interval to add, null means add nothing * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void add(ReadableInterval interval) { if (interval != null) { add(interval.toPeriod(getPeriodType())); } } /** * Adds a duration to this one by dividing the duration into * fields and calling {@link #add(ReadablePeriod)}. * * @param duration the duration to add, null means add nothing * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void add(ReadableDuration duration) { if (duration != null) { add(new Period(duration.getMillis(), getPeriodType())); } } /** * Adds a millisecond duration to this one by dividing the duration into * fields and calling {@link #add(ReadablePeriod)}. *

* When dividing the duration, only precise fields in the period type will be used. * For large durations, all the remaining duration will be stored in the largest * available precise field. * * @param duration the duration, in milliseconds * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void add(long duration) { add(new Period(duration, getPeriodType())); } /** * Adds a millisecond duration to this one by dividing the duration into * fields and calling {@link #add(ReadablePeriod)}. *

* When dividing the duration, only precise fields in the period type will be used. * For large durations, all the remaining duration will be stored in the largest * available precise field. * * @param duration the duration, in milliseconds * @param chrono the chronology to use, null means ISO default * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void add(long duration, Chronology chrono) { add(new Period(duration, getPeriodType(), chrono)); } //----------------------------------------------------------------------- /** * Merges all the fields from the specified period into this one. *

* Fields that are not present in the specified period are left unaltered. * * @param period the period to set, null ignored * @throws IllegalArgumentException if an unsupported field's value is non-zero */ public void mergePeriod(ReadablePeriod period) { super.mergePeriod(period); } //----------------------------------------------------------------------- /** * Gets the years field part of the period. * * @return the number of years in the period, zero if unsupported */ public int getYears() { return getPeriodType().getIndexedField(this, PeriodType.YEAR_INDEX); } /** * Gets the months field part of the period. * * @return the number of months in the period, zero if unsupported */ public int getMonths() { return getPeriodType().getIndexedField(this, PeriodType.MONTH_INDEX); } /** * Gets the weeks field part of the period. * * @return the number of weeks in the period, zero if unsupported */ public int getWeeks() { return getPeriodType().getIndexedField(this, PeriodType.WEEK_INDEX); } /** * Gets the days field part of the period. * * @return the number of days in the period, zero if unsupported */ public int getDays() { return getPeriodType().getIndexedField(this, PeriodType.DAY_INDEX); } //----------------------------------------------------------------------- /** * Gets the hours field part of the period. * * @return the number of hours in the period, zero if unsupported */ public int getHours() { return getPeriodType().getIndexedField(this, PeriodType.HOUR_INDEX); } /** * Gets the minutes field part of the period. * * @return the number of minutes in the period, zero if unsupported */ public int getMinutes() { return getPeriodType().getIndexedField(this, PeriodType.MINUTE_INDEX); } /** * Gets the seconds field part of the period. * * @return the number of seconds in the period, zero if unsupported */ public int getSeconds() { return getPeriodType().getIndexedField(this, PeriodType.SECOND_INDEX); } /** * Gets the millis field part of the period. * * @return the number of millis in the period, zero if unsupported */ public int getMillis() { return getPeriodType().getIndexedField(this, PeriodType.MILLI_INDEX); } //----------------------------------------------------------------------- /** * Sets the number of years of the period. * * @param years the number of years * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setYears(int years) { super.setField(DurationFieldType.years(), years); } /** * Adds the specified years to the number of years in the period. * * @param years the number of years * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addYears(int years) { super.addField(DurationFieldType.years(), years); } //----------------------------------------------------------------------- /** * Sets the number of months of the period. * * @param months the number of months * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setMonths(int months) { super.setField(DurationFieldType.months(), months); } /** * Adds the specified months to the number of months in the period. * * @param months the number of months * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addMonths(int months) { super.addField(DurationFieldType.months(), months); } //----------------------------------------------------------------------- /** * Sets the number of weeks of the period. * * @param weeks the number of weeks * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setWeeks(int weeks) { super.setField(DurationFieldType.weeks(), weeks); } /** * Adds the specified weeks to the number of weeks in the period. * * @param weeks the number of weeks * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addWeeks(int weeks) { super.addField(DurationFieldType.weeks(), weeks); } //----------------------------------------------------------------------- /** * Sets the number of days of the period. * * @param days the number of days * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setDays(int days) { super.setField(DurationFieldType.days(), days); } /** * Adds the specified days to the number of days in the period. * * @param days the number of days * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addDays(int days) { super.addField(DurationFieldType.days(), days); } //----------------------------------------------------------------------- /** * Sets the number of hours of the period. * * @param hours the number of hours * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setHours(int hours) { super.setField(DurationFieldType.hours(), hours); } /** * Adds the specified hours to the number of hours in the period. * * @param hours the number of hours * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addHours(int hours) { super.addField(DurationFieldType.hours(), hours); } //----------------------------------------------------------------------- /** * Sets the number of minutes of the period. * * @param minutes the number of minutes * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setMinutes(int minutes) { super.setField(DurationFieldType.minutes(), minutes); } /** * Adds the specified minutes to the number of minutes in the period. * * @param minutes the number of minutes * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addMinutes(int minutes) { super.addField(DurationFieldType.minutes(), minutes); } //----------------------------------------------------------------------- /** * Sets the number of seconds of the period. * * @param seconds the number of seconds * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setSeconds(int seconds) { super.setField(DurationFieldType.seconds(), seconds); } /** * Adds the specified seconds to the number of seconds in the period. * * @param seconds the number of seconds * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addSeconds(int seconds) { super.addField(DurationFieldType.seconds(), seconds); } //----------------------------------------------------------------------- /** * Sets the number of millis of the period. * * @param millis the number of millis * @throws IllegalArgumentException if field is not supported and the value is non-zero */ public void setMillis(int millis) { super.setField(DurationFieldType.millis(), millis); } /** * Adds the specified millis to the number of millis in the period. * * @param millis the number of millis * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ public void addMillis(int millis) { super.addField(DurationFieldType.millis(), millis); } // Misc //----------------------------------------------------------------------- /** * Clone this object without having to cast the returned object. * * @return a clone of the this object. */ public MutablePeriod copy() { return (MutablePeriod) clone(); } /** * Clone this object. * * @return a clone of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError("Clone error"); } } } joda-time-2.3/src/main/java/org/joda/time/Interval.java0000644000175000017500000005051712137467134022324 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import org.joda.time.base.BaseInterval; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISOPeriodFormat; /** * Interval is the standard implementation of an immutable time interval. *

* A time interval represents a period of time between two instants. * Intervals are inclusive of the start instant and exclusive of the end. * The end instant is always greater than or equal to the start instant. *

* Intervals have a fixed millisecond duration. * This is the difference between the start and end instants. * The duration is represented separately by {@link ReadableDuration}. * As a result, intervals are not comparable. * To compare the length of two intervals, you should compare their durations. *

* An interval can also be converted to a {@link ReadablePeriod}. * This represents the difference between the start and end points in terms of fields * such as years and days. *

* Interval is thread-safe and immutable. * * @author Brian S O'Neill * @author Sean Geoghegan * @author Stephen Colebourne * @author Julen Parra * @since 1.0 */ public final class Interval extends BaseInterval implements ReadableInterval, Serializable { /** Serialization version */ private static final long serialVersionUID = 4922451897541386752L; //----------------------------------------------------------------------- /** * Parses a {@code Interval} from the specified string. *

* The String formats are described by {@link ISODateTimeFormat#dateTimeParser()} * and {@link ISOPeriodFormat#standard()}, and may be 'datetime/datetime', * 'datetime/period' or 'period/datetime'. * * @param str the string to parse, not null * @since 2.0 */ public static Interval parse(String str) { return new Interval(str); } //----------------------------------------------------------------------- /** * Constructs an interval from a start and end instant with the ISO * default chronology in the default time zone. * * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @throws IllegalArgumentException if the end is before the start */ public Interval(long startInstant, long endInstant) { super(startInstant, endInstant, null); } /** * Constructs an interval from a start and end instant with the ISO * default chronology in the specified time zone. * * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param zone the time zone to use, null means default zone * @throws IllegalArgumentException if the end is before the start * @since 1.5 */ public Interval(long startInstant, long endInstant, DateTimeZone zone) { super(startInstant, endInstant, ISOChronology.getInstance(zone)); } /** * Constructs an interval from a start and end instant with the * specified chronology. * * @param chronology the chronology to use, null is ISO default * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @throws IllegalArgumentException if the end is before the start */ public Interval(long startInstant, long endInstant, Chronology chronology) { super(startInstant, endInstant, chronology); } /** * Constructs an interval from a start and end instant. *

* The chronology used is that of the start instant. * * @param start start of this interval, null means now * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start */ public Interval(ReadableInstant start, ReadableInstant end) { super(start, end); } /** * Constructs an interval from a start instant and a duration. * * @param start start of this interval, null means now * @param duration the duration of this interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ public Interval(ReadableInstant start, ReadableDuration duration) { super(start, duration); } /** * Constructs an interval from a millisecond duration and an end instant. * * @param duration the duration of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ public Interval(ReadableDuration duration, ReadableInstant end) { super(duration, end); } /** * Constructs an interval from a start instant and a time period. *

* When forming the interval, the chronology from the instant is used * if present, otherwise the chronology of the period is used. * * @param start start of this interval, null means now * @param period the period of this interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ public Interval(ReadableInstant start, ReadablePeriod period) { super(start, period); } /** * Constructs an interval from a time period and an end instant. *

* When forming the interval, the chronology from the instant is used * if present, otherwise the chronology of the period is used. * * @param period the period of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ public Interval(ReadablePeriod period, ReadableInstant end) { super(period, end); } /** * Constructs a time interval by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInterval and String. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()} * and {@link ISOPeriodFormat#standard()}, and may be 'datetime/datetime', * 'datetime/period' or 'period/datetime'. * * @param interval the time interval to copy * @throws IllegalArgumentException if the interval is invalid */ public Interval(Object interval) { super(interval, null); } /** * Constructs a time interval by converting or copying from another object, * overriding the chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInterval and String. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()} * and {@link ISOPeriodFormat#standard()}, and may be 'datetime/datetime', * 'datetime/period' or 'period/datetime'. * * @param interval the time interval to copy * @param chronology the chronology to use, null means ISO default * @throws IllegalArgumentException if the interval is invalid */ public Interval(Object interval, Chronology chronology) { super(interval, chronology); } //----------------------------------------------------------------------- /** * Get this interval as an immutable Interval object * by returning this. * * @return this */ public Interval toInterval() { return this; } //----------------------------------------------------------------------- /** * Gets the overlap between this interval and another interval. *

* Intervals are inclusive of the start instant and exclusive of the end. * An interval overlaps another if it shares some common part of the * datetime continuum. This method returns the amount of the overlap, * only if the intervals actually do overlap. * If the intervals do not overlap, then null is returned. *

* When two intervals are compared the result is one of three states: * (a) they abut, (b) there is a gap between them, (c) they overlap. * The abuts state takes precedence over the other two, thus a zero duration * interval at the start of a larger interval abuts and does not overlap. *

* The chronology of the returned interval is the same as that of * this interval (the chronology of the interval parameter is not used). * Note that the use of the chronology was only correctly implemented * in version 1.3. * * @param interval the interval to examine, null means now * @return the overlap interval, null if no overlap * @since 1.1 */ public Interval overlap(ReadableInterval interval) { interval = DateTimeUtils.getReadableInterval(interval); if (overlaps(interval) == false) { return null; } long start = Math.max(getStartMillis(), interval.getStartMillis()); long end = Math.min(getEndMillis(), interval.getEndMillis()); return new Interval(start, end, getChronology()); } //----------------------------------------------------------------------- /** * Gets the gap between this interval and another interval. * The other interval can be either before or after this interval. *

* Intervals are inclusive of the start instant and exclusive of the end. * An interval has a gap to another interval if there is a non-zero * duration between them. This method returns the amount of the gap only * if the intervals do actually have a gap between them. * If the intervals overlap or abut, then null is returned. *

* When two intervals are compared the result is one of three states: * (a) they abut, (b) there is a gap between them, (c) they overlap. * The abuts state takes precedence over the other two, thus a zero duration * interval at the start of a larger interval abuts and does not overlap. *

* The chronology of the returned interval is the same as that of * this interval (the chronology of the interval parameter is not used). * Note that the use of the chronology was only correctly implemented * in version 1.3. * * @param interval the interval to examine, null means now * @return the gap interval, null if no gap * @since 1.1 */ public Interval gap(ReadableInterval interval) { interval = DateTimeUtils.getReadableInterval(interval); long otherStart = interval.getStartMillis(); long otherEnd = interval.getEndMillis(); long thisStart = getStartMillis(); long thisEnd = getEndMillis(); if (thisStart > otherEnd) { return new Interval(otherEnd, thisStart, getChronology()); } else if (otherStart > thisEnd) { return new Interval(thisEnd, otherStart, getChronology()); } else { return null; } } //----------------------------------------------------------------------- /** * Does this interval abut with the interval specified. *

* Intervals are inclusive of the start instant and exclusive of the end. * An interval abuts if it starts immediately after, or ends immediately * before this interval without overlap. * A zero duration interval abuts with itself. *

* When two intervals are compared the result is one of three states: * (a) they abut, (b) there is a gap between them, (c) they overlap. * The abuts state takes precedence over the other two, thus a zero duration * interval at the start of a larger interval abuts and does not overlap. *

* For example: *

     * [09:00 to 10:00) abuts [08:00 to 08:30)  = false (completely before)
     * [09:00 to 10:00) abuts [08:00 to 09:00)  = true
     * [09:00 to 10:00) abuts [08:00 to 09:01)  = false (overlaps)
     * 
     * [09:00 to 10:00) abuts [09:00 to 09:00)  = true
     * [09:00 to 10:00) abuts [09:00 to 09:01)  = false (overlaps)
     * 
     * [09:00 to 10:00) abuts [10:00 to 10:00)  = true
     * [09:00 to 10:00) abuts [10:00 to 10:30)  = true
     * 
     * [09:00 to 10:00) abuts [10:30 to 11:00)  = false (completely after)
     * 
     * [14:00 to 14:00) abuts [14:00 to 14:00)  = true
     * [14:00 to 14:00) abuts [14:00 to 15:00)  = true
     * [14:00 to 14:00) abuts [13:00 to 14:00)  = true
     * 
* * @param interval the interval to examine, null means now * @return true if the interval abuts * @since 1.1 */ public boolean abuts(ReadableInterval interval) { if (interval == null) { long now = DateTimeUtils.currentTimeMillis(); return (getStartMillis() == now || getEndMillis() == now); } else { return (interval.getEndMillis() == getStartMillis() || getEndMillis() == interval.getStartMillis()); } } //----------------------------------------------------------------------- /** * Creates a new interval with the same start and end, but a different chronology. * * @param chronology the chronology to use, null means ISO default * @return an interval with a different chronology */ public Interval withChronology(Chronology chronology) { if (getChronology() == chronology) { return this; } return new Interval(getStartMillis(), getEndMillis(), chronology); } /** * Creates a new interval with the specified start millisecond instant. * * @param startInstant the start instant for the new interval * @return an interval with the end from this interval and the specified start * @throws IllegalArgumentException if the resulting interval has end before start */ public Interval withStartMillis(long startInstant) { if (startInstant == getStartMillis()) { return this; } return new Interval(startInstant, getEndMillis(), getChronology()); } /** * Creates a new interval with the specified start instant. * * @param start the start instant for the new interval, null means now * @return an interval with the end from this interval and the specified start * @throws IllegalArgumentException if the resulting interval has end before start */ public Interval withStart(ReadableInstant start) { long startMillis = DateTimeUtils.getInstantMillis(start); return withStartMillis(startMillis); } /** * Creates a new interval with the specified start millisecond instant. * * @param endInstant the end instant for the new interval * @return an interval with the start from this interval and the specified end * @throws IllegalArgumentException if the resulting interval has end before start */ public Interval withEndMillis(long endInstant) { if (endInstant == getEndMillis()) { return this; } return new Interval(getStartMillis(), endInstant, getChronology()); } /** * Creates a new interval with the specified end instant. * * @param end the end instant for the new interval, null means now * @return an interval with the start from this interval and the specified end * @throws IllegalArgumentException if the resulting interval has end before start */ public Interval withEnd(ReadableInstant end) { long endMillis = DateTimeUtils.getInstantMillis(end); return withEndMillis(endMillis); } //----------------------------------------------------------------------- /** * Creates a new interval with the specified duration after the start instant. * * @param duration the duration to add to the start to get the new end instant, null means zero * @return an interval with the start from this interval and a calculated end * @throws IllegalArgumentException if the duration is negative */ public Interval withDurationAfterStart(ReadableDuration duration) { long durationMillis = DateTimeUtils.getDurationMillis(duration); if (durationMillis == toDurationMillis()) { return this; } Chronology chrono = getChronology(); long startMillis = getStartMillis(); long endMillis = chrono.add(startMillis, durationMillis, 1); return new Interval(startMillis, endMillis, chrono); } /** * Creates a new interval with the specified duration before the end instant. * * @param duration the duration to add to the start to get the new end instant, null means zero * @return an interval with the start from this interval and a calculated end * @throws IllegalArgumentException if the duration is negative */ public Interval withDurationBeforeEnd(ReadableDuration duration) { long durationMillis = DateTimeUtils.getDurationMillis(duration); if (durationMillis == toDurationMillis()) { return this; } Chronology chrono = getChronology(); long endMillis = getEndMillis(); long startMillis = chrono.add(endMillis, durationMillis, -1); return new Interval(startMillis, endMillis, chrono); } //----------------------------------------------------------------------- /** * Creates a new interval with the specified period after the start instant. * * @param period the period to add to the start to get the new end instant, null means zero * @return an interval with the start from this interval and a calculated end * @throws IllegalArgumentException if the period is negative */ public Interval withPeriodAfterStart(ReadablePeriod period) { if (period == null) { return withDurationAfterStart(null); } Chronology chrono = getChronology(); long startMillis = getStartMillis(); long endMillis = chrono.add(period, startMillis, 1); return new Interval(startMillis, endMillis, chrono); } /** * Creates a new interval with the specified period before the end instant. * * @param period the period to add to the start to get the new end instant, null means zero * @return an interval with the start from this interval and a calculated end * @throws IllegalArgumentException if the period is negative */ public Interval withPeriodBeforeEnd(ReadablePeriod period) { if (period == null) { return withDurationBeforeEnd(null); } Chronology chrono = getChronology(); long endMillis = getEndMillis(); long startMillis = chrono.add(period, endMillis, -1); return new Interval(startMillis, endMillis, chrono); } } joda-time-2.3/src/main/java/org/joda/time/DateTimeFieldType.java0000644000175000017500000005221411667411277024042 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; /** * Identifies a field, such as year or minuteOfHour, in a chronology-neutral way. *

* A field type defines the type of the field, such as hourOfDay. * If does not directly enable any calculations, however it does provide a * {@link #getField(Chronology)} method that returns the actual calculation engine * for a particular chronology. * It also provides access to the related {@link DurationFieldType}s. *

* Instances of DateTimeFieldType are singletons. * They can be compared using ==. *

* If required, you can create your own field, for example a quarterOfYear. * You must create a subclass of DateTimeFieldType that defines the field type. * This class returns the actual calculation engine from {@link #getField(Chronology)}. * The subclass should implement equals and hashCode. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public abstract class DateTimeFieldType implements Serializable { /** Serialization version */ private static final long serialVersionUID = -42615285973990L; /** Ordinal values for standard field types. */ static final byte ERA = 1, YEAR_OF_ERA = 2, CENTURY_OF_ERA = 3, YEAR_OF_CENTURY = 4, YEAR = 5, DAY_OF_YEAR = 6, MONTH_OF_YEAR = 7, DAY_OF_MONTH = 8, WEEKYEAR_OF_CENTURY = 9, WEEKYEAR = 10, WEEK_OF_WEEKYEAR = 11, DAY_OF_WEEK = 12, HALFDAY_OF_DAY = 13, HOUR_OF_HALFDAY = 14, CLOCKHOUR_OF_HALFDAY = 15, CLOCKHOUR_OF_DAY = 16, HOUR_OF_DAY = 17, MINUTE_OF_DAY = 18, MINUTE_OF_HOUR = 19, SECOND_OF_DAY = 20, SECOND_OF_MINUTE = 21, MILLIS_OF_DAY = 22, MILLIS_OF_SECOND = 23; /** The era field type. */ private static final DateTimeFieldType ERA_TYPE = new StandardDateTimeFieldType( "era", ERA, DurationFieldType.eras(), null); /** The yearOfEra field type. */ private static final DateTimeFieldType YEAR_OF_ERA_TYPE = new StandardDateTimeFieldType( "yearOfEra", YEAR_OF_ERA, DurationFieldType.years(), DurationFieldType.eras()); /** The centuryOfEra field type. */ private static final DateTimeFieldType CENTURY_OF_ERA_TYPE = new StandardDateTimeFieldType( "centuryOfEra", CENTURY_OF_ERA, DurationFieldType.centuries(), DurationFieldType.eras()); /** The yearOfCentury field type. */ private static final DateTimeFieldType YEAR_OF_CENTURY_TYPE = new StandardDateTimeFieldType( "yearOfCentury", YEAR_OF_CENTURY, DurationFieldType.years(), DurationFieldType.centuries()); /** The year field type. */ private static final DateTimeFieldType YEAR_TYPE = new StandardDateTimeFieldType( "year", YEAR, DurationFieldType.years(), null); /** The dayOfYear field type. */ private static final DateTimeFieldType DAY_OF_YEAR_TYPE = new StandardDateTimeFieldType( "dayOfYear", DAY_OF_YEAR, DurationFieldType.days(), DurationFieldType.years()); /** The monthOfYear field type. */ private static final DateTimeFieldType MONTH_OF_YEAR_TYPE = new StandardDateTimeFieldType( "monthOfYear", MONTH_OF_YEAR, DurationFieldType.months(), DurationFieldType.years()); /** The dayOfMonth field type. */ private static final DateTimeFieldType DAY_OF_MONTH_TYPE = new StandardDateTimeFieldType( "dayOfMonth", DAY_OF_MONTH, DurationFieldType.days(), DurationFieldType.months()); /** The weekyearOfCentury field type. */ private static final DateTimeFieldType WEEKYEAR_OF_CENTURY_TYPE = new StandardDateTimeFieldType( "weekyearOfCentury", WEEKYEAR_OF_CENTURY, DurationFieldType.weekyears(), DurationFieldType.centuries()); /** The weekyear field type. */ private static final DateTimeFieldType WEEKYEAR_TYPE = new StandardDateTimeFieldType( "weekyear", WEEKYEAR, DurationFieldType.weekyears(), null); /** The weekOfWeekyear field type. */ private static final DateTimeFieldType WEEK_OF_WEEKYEAR_TYPE = new StandardDateTimeFieldType( "weekOfWeekyear", WEEK_OF_WEEKYEAR, DurationFieldType.weeks(), DurationFieldType.weekyears()); /** The dayOfWeek field type. */ private static final DateTimeFieldType DAY_OF_WEEK_TYPE = new StandardDateTimeFieldType( "dayOfWeek", DAY_OF_WEEK, DurationFieldType.days(), DurationFieldType.weeks()); /** The halfday field type. */ private static final DateTimeFieldType HALFDAY_OF_DAY_TYPE = new StandardDateTimeFieldType( "halfdayOfDay", HALFDAY_OF_DAY, DurationFieldType.halfdays(), DurationFieldType.days()); /** The hourOfHalfday field type. */ private static final DateTimeFieldType HOUR_OF_HALFDAY_TYPE = new StandardDateTimeFieldType( "hourOfHalfday", HOUR_OF_HALFDAY, DurationFieldType.hours(), DurationFieldType.halfdays()); /** The clockhourOfHalfday field type. */ private static final DateTimeFieldType CLOCKHOUR_OF_HALFDAY_TYPE = new StandardDateTimeFieldType( "clockhourOfHalfday", CLOCKHOUR_OF_HALFDAY, DurationFieldType.hours(), DurationFieldType.halfdays()); /** The clockhourOfDay field type. */ private static final DateTimeFieldType CLOCKHOUR_OF_DAY_TYPE = new StandardDateTimeFieldType( "clockhourOfDay", CLOCKHOUR_OF_DAY, DurationFieldType.hours(), DurationFieldType.days()); /** The hourOfDay field type. */ private static final DateTimeFieldType HOUR_OF_DAY_TYPE = new StandardDateTimeFieldType( "hourOfDay", HOUR_OF_DAY, DurationFieldType.hours(), DurationFieldType.days()); /** The minuteOfDay field type. */ private static final DateTimeFieldType MINUTE_OF_DAY_TYPE = new StandardDateTimeFieldType( "minuteOfDay", MINUTE_OF_DAY, DurationFieldType.minutes(), DurationFieldType.days()); /** The minuteOfHour field type. */ private static final DateTimeFieldType MINUTE_OF_HOUR_TYPE = new StandardDateTimeFieldType( "minuteOfHour", MINUTE_OF_HOUR, DurationFieldType.minutes(), DurationFieldType.hours()); /** The secondOfDay field type. */ private static final DateTimeFieldType SECOND_OF_DAY_TYPE = new StandardDateTimeFieldType( "secondOfDay", SECOND_OF_DAY, DurationFieldType.seconds(), DurationFieldType.days()); /** The secondOfMinute field type. */ private static final DateTimeFieldType SECOND_OF_MINUTE_TYPE = new StandardDateTimeFieldType( "secondOfMinute", SECOND_OF_MINUTE, DurationFieldType.seconds(), DurationFieldType.minutes()); /** The millisOfDay field type. */ private static final DateTimeFieldType MILLIS_OF_DAY_TYPE = new StandardDateTimeFieldType( "millisOfDay", MILLIS_OF_DAY, DurationFieldType.millis(), DurationFieldType.days()); /** The millisOfSecond field type. */ private static final DateTimeFieldType MILLIS_OF_SECOND_TYPE = new StandardDateTimeFieldType( "millisOfSecond", MILLIS_OF_SECOND, DurationFieldType.millis(), DurationFieldType.seconds()); /** The name of the field. */ private final String iName; //----------------------------------------------------------------------- /** * Constructor. * * @param name the name to use */ protected DateTimeFieldType(String name) { super(); iName = name; } //----------------------------------------------------------------------- /** * Get the millis of second field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType millisOfSecond() { return MILLIS_OF_SECOND_TYPE; } /** * Get the millis of day field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType millisOfDay() { return MILLIS_OF_DAY_TYPE; } /** * Get the second of minute field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType secondOfMinute() { return SECOND_OF_MINUTE_TYPE; } /** * Get the second of day field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType secondOfDay() { return SECOND_OF_DAY_TYPE; } /** * Get the minute of hour field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType minuteOfHour() { return MINUTE_OF_HOUR_TYPE; } /** * Get the minute of day field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType minuteOfDay() { return MINUTE_OF_DAY_TYPE; } /** * Get the hour of day (0-23) field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType hourOfDay() { return HOUR_OF_DAY_TYPE; } /** * Get the hour of day (offset to 1-24) field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType clockhourOfDay() { return CLOCKHOUR_OF_DAY_TYPE; } /** * Get the hour of am/pm (0-11) field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType hourOfHalfday() { return HOUR_OF_HALFDAY_TYPE; } /** * Get the hour of am/pm (offset to 1-12) field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType clockhourOfHalfday() { return CLOCKHOUR_OF_HALFDAY_TYPE; } /** * Get the AM(0) PM(1) field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType halfdayOfDay() { return HALFDAY_OF_DAY_TYPE; } //----------------------------------------------------------------------- /** * Get the day of week field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType dayOfWeek() { return DAY_OF_WEEK_TYPE; } /** * Get the day of month field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType dayOfMonth() { return DAY_OF_MONTH_TYPE; } /** * Get the day of year field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType dayOfYear() { return DAY_OF_YEAR_TYPE; } /** * Get the week of a week based year field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType weekOfWeekyear() { return WEEK_OF_WEEKYEAR_TYPE; } /** * Get the year of a week based year field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType weekyear() { return WEEKYEAR_TYPE; } /** * Get the year of a week based year within a century field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType weekyearOfCentury() { return WEEKYEAR_OF_CENTURY_TYPE; } /** * Get the month of year field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType monthOfYear() { return MONTH_OF_YEAR_TYPE; } /** * Get the year field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType year() { return YEAR_TYPE; } /** * Get the year of era field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType yearOfEra() { return YEAR_OF_ERA_TYPE; } /** * Get the year of century field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType yearOfCentury() { return YEAR_OF_CENTURY_TYPE; } /** * Get the century of era field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType centuryOfEra() { return CENTURY_OF_ERA_TYPE; } /** * Get the era field type. * * @return the DateTimeFieldType constant */ public static DateTimeFieldType era() { return ERA_TYPE; } //----------------------------------------------------------------------- /** * Get the name of the field. *

* By convention, names follow a pattern of "dddOfRrr", where "ddd" represents * the (singular) duration unit field name and "Rrr" represents the (singular) * duration range field name. If the range field is not applicable, then * the name of the field is simply the (singular) duration field name. * * @return field name */ public String getName() { return iName; } /** * Get the duration unit of the field. * * @return duration unit of the field, never null */ public abstract DurationFieldType getDurationType(); /** * Get the duration range of the field. * * @return duration range of the field, null if unbounded */ public abstract DurationFieldType getRangeDurationType(); /** * Gets a suitable field for this type from the given Chronology. * * @param chronology the chronology to use, null means ISOChronology in default zone * @return a suitable field */ public abstract DateTimeField getField(Chronology chronology); /** * Checks whether this field supported in the given Chronology. * * @param chronology the chronology to use, null means ISOChronology in default zone * @return true if supported */ public boolean isSupported(Chronology chronology) { return getField(chronology).isSupported(); } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return getName(); } private static class StandardDateTimeFieldType extends DateTimeFieldType { /** Serialization version */ private static final long serialVersionUID = -9937958251642L; /** The ordinal of the standard field type, for switch statements */ private final byte iOrdinal; /** The unit duration of the field. */ private final transient DurationFieldType iUnitType; /** The range duration of the field. */ private final transient DurationFieldType iRangeType; /** * Constructor. * * @param name the name to use * @param ordinal the byte value for the oridinal index * @param unitType the unit duration type * @param rangeType the range duration type */ StandardDateTimeFieldType(String name, byte ordinal, DurationFieldType unitType, DurationFieldType rangeType) { super(name); iOrdinal = ordinal; iUnitType = unitType; iRangeType = rangeType; } /** @inheritdoc */ public DurationFieldType getDurationType() { return iUnitType; } /** @inheritdoc */ public DurationFieldType getRangeDurationType() { return iRangeType; } /** @inheritdoc */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof StandardDateTimeFieldType) { return iOrdinal == ((StandardDateTimeFieldType) obj).iOrdinal; } return false; } /** @inheritdoc */ @Override public int hashCode() { return (1 << iOrdinal); } /** @inheritdoc */ public DateTimeField getField(Chronology chronology) { chronology = DateTimeUtils.getChronology(chronology); switch (iOrdinal) { case ERA: return chronology.era(); case YEAR_OF_ERA: return chronology.yearOfEra(); case CENTURY_OF_ERA: return chronology.centuryOfEra(); case YEAR_OF_CENTURY: return chronology.yearOfCentury(); case YEAR: return chronology.year(); case DAY_OF_YEAR: return chronology.dayOfYear(); case MONTH_OF_YEAR: return chronology.monthOfYear(); case DAY_OF_MONTH: return chronology.dayOfMonth(); case WEEKYEAR_OF_CENTURY: return chronology.weekyearOfCentury(); case WEEKYEAR: return chronology.weekyear(); case WEEK_OF_WEEKYEAR: return chronology.weekOfWeekyear(); case DAY_OF_WEEK: return chronology.dayOfWeek(); case HALFDAY_OF_DAY: return chronology.halfdayOfDay(); case HOUR_OF_HALFDAY: return chronology.hourOfHalfday(); case CLOCKHOUR_OF_HALFDAY: return chronology.clockhourOfHalfday(); case CLOCKHOUR_OF_DAY: return chronology.clockhourOfDay(); case HOUR_OF_DAY: return chronology.hourOfDay(); case MINUTE_OF_DAY: return chronology.minuteOfDay(); case MINUTE_OF_HOUR: return chronology.minuteOfHour(); case SECOND_OF_DAY: return chronology.secondOfDay(); case SECOND_OF_MINUTE: return chronology.secondOfMinute(); case MILLIS_OF_DAY: return chronology.millisOfDay(); case MILLIS_OF_SECOND: return chronology.millisOfSecond(); default: // Shouldn't happen. throw new InternalError(); } } /** * Ensure a singleton is returned. * * @return the singleton type */ private Object readResolve() { switch (iOrdinal) { case ERA: return ERA_TYPE; case YEAR_OF_ERA: return YEAR_OF_ERA_TYPE; case CENTURY_OF_ERA: return CENTURY_OF_ERA_TYPE; case YEAR_OF_CENTURY: return YEAR_OF_CENTURY_TYPE; case YEAR: return YEAR_TYPE; case DAY_OF_YEAR: return DAY_OF_YEAR_TYPE; case MONTH_OF_YEAR: return MONTH_OF_YEAR_TYPE; case DAY_OF_MONTH: return DAY_OF_MONTH_TYPE; case WEEKYEAR_OF_CENTURY: return WEEKYEAR_OF_CENTURY_TYPE; case WEEKYEAR: return WEEKYEAR_TYPE; case WEEK_OF_WEEKYEAR: return WEEK_OF_WEEKYEAR_TYPE; case DAY_OF_WEEK: return DAY_OF_WEEK_TYPE; case HALFDAY_OF_DAY: return HALFDAY_OF_DAY_TYPE; case HOUR_OF_HALFDAY: return HOUR_OF_HALFDAY_TYPE; case CLOCKHOUR_OF_HALFDAY: return CLOCKHOUR_OF_HALFDAY_TYPE; case CLOCKHOUR_OF_DAY: return CLOCKHOUR_OF_DAY_TYPE; case HOUR_OF_DAY: return HOUR_OF_DAY_TYPE; case MINUTE_OF_DAY: return MINUTE_OF_DAY_TYPE; case MINUTE_OF_HOUR: return MINUTE_OF_HOUR_TYPE; case SECOND_OF_DAY: return SECOND_OF_DAY_TYPE; case SECOND_OF_MINUTE: return SECOND_OF_MINUTE_TYPE; case MILLIS_OF_DAY: return MILLIS_OF_DAY_TYPE; case MILLIS_OF_SECOND: return MILLIS_OF_SECOND_TYPE; default: // Shouldn't happen. return this; } } } } joda-time-2.3/src/main/java/org/joda/time/field/0000755000175000017500000000000012205344143020736 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/field/UnsupportedDurationField.java0000644000175000017500000001627111564251363026622 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.Serializable; import java.util.HashMap; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; /** * A placeholder implementation to use when a duration field is not supported. *

* UnsupportedDurationField is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public final class UnsupportedDurationField extends DurationField implements Serializable { /** Serialization lock. */ private static final long serialVersionUID = -6390301302770925357L; /** The cache of unsupported duration field instances */ private static HashMap cCache; /** * Gets an instance of UnsupportedDurationField for a specific named field. * The returned instance is cached. * * @param type the type to obtain * @return the instance */ public static synchronized UnsupportedDurationField getInstance(DurationFieldType type) { UnsupportedDurationField field; if (cCache == null) { cCache = new HashMap(7); field = null; } else { field = cCache.get(type); } if (field == null) { field = new UnsupportedDurationField(type); cCache.put(type, field); } return field; } /** The name of the field */ private final DurationFieldType iType; /** * Constructor. * * @param type the type to use */ private UnsupportedDurationField(DurationFieldType type) { iType = type; } //----------------------------------------------------------------------- // Design note: Simple Accessors return a suitable value, but methods // intended to perform calculations throw an UnsupportedOperationException. public final DurationFieldType getType() { return iType; } public String getName() { return iType.getName(); } /** * This field is not supported. * * @return false always */ public boolean isSupported() { return false; } /** * This field is precise. * * @return true always */ public boolean isPrecise() { return true; } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getValue(long duration) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long getValueAsLong(long duration) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getValue(long duration, long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long getValueAsLong(long duration, long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long getMillis(int value) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long getMillis(long value) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long getMillis(int value, long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long getMillis(long value, long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long add(long instant, int value) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long add(long instant, long value) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getDifference(long minuendInstant, long subtrahendInstant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { throw unsupported(); } /** * Always returns zero. * * @return zero always */ public long getUnitMillis() { return 0; } /** * Always returns zero, indicating that sort order is not relevent. * * @return zero always */ public int compareTo(DurationField durationField) { return 0; } //------------------------------------------------------------------------ /** * Compares this duration field to another. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof UnsupportedDurationField) { UnsupportedDurationField other = (UnsupportedDurationField) obj; if (other.getName() == null) { return (getName() == null); } return (other.getName().equals(getName())); } return false; } /** * Gets a suitable hashcode. * * @return the hashcode */ public int hashCode() { return getName().hashCode(); } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return "UnsupportedDurationField[" + getName() + ']'; } /** * Ensure proper singleton serialization */ private Object readResolve() { return getInstance(iType); } private UnsupportedOperationException unsupported() { return new UnsupportedOperationException(iType + " field is unsupported"); } } joda-time-2.3/src/main/java/org/joda/time/field/ImpreciseDateTimeField.java0000644000175000017500000001623412203435115026106 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; /** * Abstract datetime field class that defines its own DurationField, which * delegates back into this ImpreciseDateTimeField. *

* This DateTimeField is useful for defining DateTimeFields that are composed * of imprecise durations. If both duration fields are precise, then a * {@link PreciseDateTimeField} should be used instead. *

* When defining imprecise DateTimeFields where a matching DurationField is * already available, just extend BaseDateTimeField directly so as not to * create redundant DurationField instances. *

* ImpreciseDateTimeField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @see PreciseDateTimeField * @since 1.0 */ public abstract class ImpreciseDateTimeField extends BaseDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 7190739608550251860L; final long iUnitMillis; private final DurationField iDurationField; /** * Constructor. * * @param type the field type * @param unitMillis the average duration unit milliseconds */ public ImpreciseDateTimeField(DateTimeFieldType type, long unitMillis) { super(type); iUnitMillis = unitMillis; iDurationField = new LinkedDurationField(type.getDurationType()); } public abstract int get(long instant); public abstract long set(long instant, int value); public abstract long add(long instant, int value); public abstract long add(long instant, long value); /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *

     * long instant = ...
     * int v = ...
     * int age = getDifference(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. *

* The default implementation call getDifferenceAsLong and converts the * return value to an int. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public int getDifference(long minuendInstant, long subtrahendInstant) { return FieldUtils.safeToInt(getDifferenceAsLong(minuendInstant, subtrahendInstant)); } /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *

     * long instant = ...
     * long v = ...
     * long age = getDifferenceAsLong(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. *

* The default implementation performs a guess-and-check algorithm using * getDurationField().getUnitMillis() and the add() method. Subclasses are * encouraged to provide a more efficient implementation. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant < subtrahendInstant) { return -getDifferenceAsLong(subtrahendInstant, minuendInstant); } long difference = (minuendInstant - subtrahendInstant) / iUnitMillis; if (add(subtrahendInstant, difference) < minuendInstant) { do { difference++; } while (add(subtrahendInstant, difference) <= minuendInstant); difference--; } else if (add(subtrahendInstant, difference) > minuendInstant) { do { difference--; } while (add(subtrahendInstant, difference) > minuendInstant); } return difference; } public final DurationField getDurationField() { return iDurationField; } public abstract DurationField getRangeDurationField(); public abstract long roundFloor(long instant); protected final long getDurationUnitMillis() { return iUnitMillis; } private final class LinkedDurationField extends BaseDurationField { private static final long serialVersionUID = -203813474600094134L; LinkedDurationField(DurationFieldType type) { super(type); } public boolean isPrecise() { return false; } public long getUnitMillis() { return iUnitMillis; } public int getValue(long duration, long instant) { return ImpreciseDateTimeField.this .getDifference(instant + duration, instant); } public long getValueAsLong(long duration, long instant) { return ImpreciseDateTimeField.this .getDifferenceAsLong(instant + duration, instant); } public long getMillis(int value, long instant) { return ImpreciseDateTimeField.this.add(instant, value) - instant; } public long getMillis(long value, long instant) { return ImpreciseDateTimeField.this.add(instant, value) - instant; } public long add(long instant, int value) { return ImpreciseDateTimeField.this.add(instant, value); } public long add(long instant, long value) { return ImpreciseDateTimeField.this.add(instant, value); } public int getDifference(long minuendInstant, long subtrahendInstant) { return ImpreciseDateTimeField.this .getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return ImpreciseDateTimeField.this .getDifferenceAsLong(minuendInstant, subtrahendInstant); } } } joda-time-2.3/src/main/java/org/joda/time/field/DelegatedDateTimeField.java0000644000175000017500000002021711564251363026052 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.Serializable; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; /** * DelegatedDateTimeField delegates each method call to the * date time field it wraps. *

* DelegatedDateTimeField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @since 1.0 * @see DecoratedDateTimeField */ public class DelegatedDateTimeField extends DateTimeField implements Serializable { /** Serialization version */ private static final long serialVersionUID = -4730164440214502503L; /** The DateTimeField being wrapped */ private final DateTimeField iField; /** The override field type */ private final DateTimeFieldType iType; /** * Constructor. * * @param field the field being decorated */ public DelegatedDateTimeField(DateTimeField field) { this(field, null); } /** * Constructor. * * @param field the field being decorated * @param type the field type override */ public DelegatedDateTimeField(DateTimeField field, DateTimeFieldType type) { super(); if (field == null) { throw new IllegalArgumentException("The field must not be null"); } iField = field; iType = (type == null ? field.getType() : type); } /** * Gets the wrapped date time field. * * @return the wrapped DateTimeField */ public final DateTimeField getWrappedField() { return iField; } public DateTimeFieldType getType() { return iType; } public String getName() { return iType.getName(); } public boolean isSupported() { return iField.isSupported(); } public boolean isLenient() { return iField.isLenient(); } public int get(long instant) { return iField.get(instant); } public String getAsText(long instant, Locale locale) { return iField.getAsText(instant, locale); } public String getAsText(long instant) { return iField.getAsText(instant); } public String getAsText(ReadablePartial partial, int fieldValue, Locale locale) { return iField.getAsText(partial, fieldValue, locale); } public String getAsText(ReadablePartial partial, Locale locale) { return iField.getAsText(partial, locale); } public String getAsText(int fieldValue, Locale locale) { return iField.getAsText(fieldValue, locale); } public String getAsShortText(long instant, Locale locale) { return iField.getAsShortText(instant, locale); } public String getAsShortText(long instant) { return iField.getAsShortText(instant); } public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale) { return iField.getAsShortText(partial, fieldValue, locale); } public String getAsShortText(ReadablePartial partial, Locale locale) { return iField.getAsShortText(partial, locale); } public String getAsShortText(int fieldValue, Locale locale) { return iField.getAsShortText(fieldValue, locale); } public long add(long instant, int value) { return iField.add(instant, value); } public long add(long instant, long value) { return iField.add(instant, value); } public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { return iField.add(instant, fieldIndex, values, valueToAdd); } public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { return iField.addWrapPartial(instant, fieldIndex, values, valueToAdd); } public long addWrapField(long instant, int value) { return iField.addWrapField(instant, value); } public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { return iField.addWrapField(instant, fieldIndex, values, valueToAdd); } public int getDifference(long minuendInstant, long subtrahendInstant) { return iField.getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long set(long instant, int value) { return iField.set(instant, value); } public long set(long instant, String text, Locale locale) { return iField.set(instant, text, locale); } public long set(long instant, String text) { return iField.set(instant, text); } public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue) { return iField.set(instant, fieldIndex, values, newValue); } public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale) { return iField.set(instant, fieldIndex, values, text, locale); } public DurationField getDurationField() { return iField.getDurationField(); } public DurationField getRangeDurationField() { return iField.getRangeDurationField(); } public boolean isLeap(long instant) { return iField.isLeap(instant); } public int getLeapAmount(long instant) { return iField.getLeapAmount(instant); } public DurationField getLeapDurationField() { return iField.getLeapDurationField(); } public int getMinimumValue() { return iField.getMinimumValue(); } public int getMinimumValue(long instant) { return iField.getMinimumValue(instant); } public int getMinimumValue(ReadablePartial instant) { return iField.getMinimumValue(instant); } public int getMinimumValue(ReadablePartial instant, int[] values) { return iField.getMinimumValue(instant, values); } public int getMaximumValue() { return iField.getMaximumValue(); } public int getMaximumValue(long instant) { return iField.getMaximumValue(instant); } public int getMaximumValue(ReadablePartial instant) { return iField.getMaximumValue(instant); } public int getMaximumValue(ReadablePartial instant, int[] values) { return iField.getMaximumValue(instant, values); } public int getMaximumTextLength(Locale locale) { return iField.getMaximumTextLength(locale); } public int getMaximumShortTextLength(Locale locale) { return iField.getMaximumShortTextLength(locale); } public long roundFloor(long instant) { return iField.roundFloor(instant); } public long roundCeiling(long instant) { return iField.roundCeiling(instant); } public long roundHalfFloor(long instant) { return iField.roundHalfFloor(instant); } public long roundHalfCeiling(long instant) { return iField.roundHalfCeiling(instant); } public long roundHalfEven(long instant) { return iField.roundHalfEven(instant); } public long remainder(long instant) { return iField.remainder(instant); } public String toString() { return ("DateTimeField[" + getName() + ']'); } } joda-time-2.3/src/main/java/org/joda/time/field/SkipDateTimeField.java0000644000175000017500000000632411616003375025101 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.IllegalFieldValueException; /** * Wraps another field such that a certain value is skipped. *

* This is most useful for years where you want to skip zero, so the * sequence runs ...,2,1,-1,-2,... *

* SkipDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class SkipDateTimeField extends DelegatedDateTimeField { /** Serialization version. */ private static final long serialVersionUID = -8869148464118507846L; /** The chronology to wrap. */ private final Chronology iChronology; /** The value to skip. */ private final int iSkip; /** The calculated minimum value. */ private transient int iMinValue; /** * Constructor that skips zero. * * @param chronology the chronoogy to use * @param field the field to skip zero on */ public SkipDateTimeField(Chronology chronology, DateTimeField field) { this(chronology, field, 0); } /** * Constructor. * * @param chronology the chronoogy to use * @param field the field to skip zero on * @param skip the value to skip */ public SkipDateTimeField(Chronology chronology, DateTimeField field, int skip) { super(field); iChronology = chronology; int min = super.getMinimumValue(); if (min < skip) { iMinValue = min - 1; } else if (min == skip) { iMinValue = skip + 1; } else { iMinValue = min; } iSkip = skip; } //----------------------------------------------------------------------- public int get(long millis) { int value = super.get(millis); if (value <= iSkip) { value--; } return value; } public long set(long millis, int value) { FieldUtils.verifyValueBounds(this, value, iMinValue, getMaximumValue()); if (value <= iSkip) { if (value == iSkip) { throw new IllegalFieldValueException (DateTimeFieldType.year(), Integer.valueOf(value), null, null); } value++; } return super.set(millis, value); } public int getMinimumValue() { return iMinValue; } private Object readResolve() { return getType().getField(iChronology); } } joda-time-2.3/src/main/java/org/joda/time/field/ScaledDurationField.java0000644000175000017500000001167311564251363025466 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; /** * Scales a DurationField such that it's unit millis becomes larger in * magnitude. *

* ScaledDurationField is thread-safe and immutable. * * @see PreciseDurationField * * @author Brian S O'Neill * @since 1.0 */ public class ScaledDurationField extends DecoratedDurationField { private static final long serialVersionUID = -3205227092378684157L; private final int iScalar; /** * Constructor * * @param field the field to wrap, like "year()". * @param type the type this field will actually use * @param scalar scalar, such as 100 years in a century * @throws IllegalArgumentException if scalar is zero or one. */ public ScaledDurationField(DurationField field, DurationFieldType type, int scalar) { super(field, type); if (scalar == 0 || scalar == 1) { throw new IllegalArgumentException("The scalar must not be 0 or 1"); } iScalar = scalar; } public int getValue(long duration) { return getWrappedField().getValue(duration) / iScalar; } public long getValueAsLong(long duration) { return getWrappedField().getValueAsLong(duration) / iScalar; } public int getValue(long duration, long instant) { return getWrappedField().getValue(duration, instant) / iScalar; } public long getValueAsLong(long duration, long instant) { return getWrappedField().getValueAsLong(duration, instant) / iScalar; } public long getMillis(int value) { long scaled = ((long) value) * ((long) iScalar); return getWrappedField().getMillis(scaled); } public long getMillis(long value) { long scaled = FieldUtils.safeMultiply(value, iScalar); return getWrappedField().getMillis(scaled); } public long getMillis(int value, long instant) { long scaled = ((long) value) * ((long) iScalar); return getWrappedField().getMillis(scaled, instant); } public long getMillis(long value, long instant) { long scaled = FieldUtils.safeMultiply(value, iScalar); return getWrappedField().getMillis(scaled, instant); } public long add(long instant, int value) { long scaled = ((long) value) * ((long) iScalar); return getWrappedField().add(instant, scaled); } public long add(long instant, long value) { long scaled = FieldUtils.safeMultiply(value, iScalar); return getWrappedField().add(instant, scaled); } public int getDifference(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifference(minuendInstant, subtrahendInstant) / iScalar; } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant) / iScalar; } public long getUnitMillis() { return getWrappedField().getUnitMillis() * iScalar; } //----------------------------------------------------------------------- /** * Returns the scalar applied, in the field's units. * * @return the scalar */ public int getScalar() { return iScalar; } /** * Compares this duration field to another. * Two fields are equal if of the same type and duration. * * @param obj the object to compare to * @return if equal */ public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof ScaledDurationField) { ScaledDurationField other = (ScaledDurationField) obj; return (getWrappedField().equals(other.getWrappedField())) && (getType() == other.getType()) && (iScalar == other.iScalar); } return false; } /** * Gets a hash code for this instance. * * @return a suitable hashcode */ public int hashCode() { long scalar = iScalar; int hash = (int) (scalar ^ (scalar >>> 32)); hash += getType().hashCode(); hash += getWrappedField().hashCode(); return hash; } } joda-time-2.3/src/main/java/org/joda/time/field/FieldUtils.java0000644000175000017500000002727511747473253023701 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.IllegalFieldValueException; /** * General utilities that don't fit elsewhere. *

* FieldUtils is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.0 */ public class FieldUtils { /** * Restricted constructor. */ private FieldUtils() { super(); } //------------------------------------------------------------------------ /** * Negates the input throwing an exception if it can't negate it. * * @param value the value to negate * @return the negated value * @throws ArithmeticException if the value is Integer.MIN_VALUE * @since 1.1 */ public static int safeNegate(int value) { if (value == Integer.MIN_VALUE) { throw new ArithmeticException("Integer.MIN_VALUE cannot be negated"); } return -value; } /** * Add two values throwing an exception if overflow occurs. * * @param val1 the first value * @param val2 the second value * @return the new total * @throws ArithmeticException if the value is too big or too small */ public static int safeAdd(int val1, int val2) { int sum = val1 + val2; // If there is a sign change, but the two values have the same sign... if ((val1 ^ sum) < 0 && (val1 ^ val2) >= 0) { throw new ArithmeticException ("The calculation caused an overflow: " + val1 + " + " + val2); } return sum; } /** * Add two values throwing an exception if overflow occurs. * * @param val1 the first value * @param val2 the second value * @return the new total * @throws ArithmeticException if the value is too big or too small */ public static long safeAdd(long val1, long val2) { long sum = val1 + val2; // If there is a sign change, but the two values have the same sign... if ((val1 ^ sum) < 0 && (val1 ^ val2) >= 0) { throw new ArithmeticException ("The calculation caused an overflow: " + val1 + " + " + val2); } return sum; } /** * Subtracts two values throwing an exception if overflow occurs. * * @param val1 the first value, to be taken away from * @param val2 the second value, the amount to take away * @return the new total * @throws ArithmeticException if the value is too big or too small */ public static long safeSubtract(long val1, long val2) { long diff = val1 - val2; // If there is a sign change, but the two values have different signs... if ((val1 ^ diff) < 0 && (val1 ^ val2) < 0) { throw new ArithmeticException ("The calculation caused an overflow: " + val1 + " - " + val2); } return diff; } /** * Multiply two values throwing an exception if overflow occurs. * * @param val1 the first value * @param val2 the second value * @return the new total * @throws ArithmeticException if the value is too big or too small * @since 1.2 */ public static int safeMultiply(int val1, int val2) { long total = (long) val1 * (long) val2; if (total < Integer.MIN_VALUE || total > Integer.MAX_VALUE) { throw new ArithmeticException("Multiplication overflows an int: " + val1 + " * " + val2); } return (int) total; } /** * Multiply two values throwing an exception if overflow occurs. * * @param val1 the first value * @param val2 the second value * @return the new total * @throws ArithmeticException if the value is too big or too small * @since 1.2 */ public static long safeMultiply(long val1, int val2) { switch (val2) { case -1: if (val1 == Long.MIN_VALUE) { throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2); } return -val1; case 0: return 0L; case 1: return val1; } long total = val1 * val2; if (total / val2 != val1) { throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2); } return total; } /** * Multiply two values throwing an exception if overflow occurs. * * @param val1 the first value * @param val2 the second value * @return the new total * @throws ArithmeticException if the value is too big or too small */ public static long safeMultiply(long val1, long val2) { if (val2 == 1) { return val1; } if (val1 == 1) { return val2; } if (val1 == 0 || val2 == 0) { return 0; } long total = val1 * val2; if (total / val2 != val1 || val1 == Long.MIN_VALUE && val2 == -1 || val2 == Long.MIN_VALUE && val1 == -1) { throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2); } return total; } /** * Casts to an int throwing an exception if overflow occurs. * * @param value the value * @return the value as an int * @throws ArithmeticException if the value is too big or too small */ public static int safeToInt(long value) { if (Integer.MIN_VALUE <= value && value <= Integer.MAX_VALUE) { return (int) value; } throw new ArithmeticException("Value cannot fit in an int: " + value); } /** * Multiply two values to return an int throwing an exception if overflow occurs. * * @param val1 the first value * @param val2 the second value * @return the new total * @throws ArithmeticException if the value is too big or too small */ public static int safeMultiplyToInt(long val1, long val2) { long val = FieldUtils.safeMultiply(val1, val2); return FieldUtils.safeToInt(val); } //----------------------------------------------------------------------- /** * Verify that input values are within specified bounds. * * @param value the value to check * @param lowerBound the lower bound allowed for value * @param upperBound the upper bound allowed for value * @throws IllegalFieldValueException if value is not in the specified bounds */ public static void verifyValueBounds(DateTimeField field, int value, int lowerBound, int upperBound) { if ((value < lowerBound) || (value > upperBound)) { throw new IllegalFieldValueException (field.getType(), Integer.valueOf(value), Integer.valueOf(lowerBound), Integer.valueOf(upperBound)); } } /** * Verify that input values are within specified bounds. * * @param value the value to check * @param lowerBound the lower bound allowed for value * @param upperBound the upper bound allowed for value * @throws IllegalFieldValueException if value is not in the specified bounds * @since 1.1 */ public static void verifyValueBounds(DateTimeFieldType fieldType, int value, int lowerBound, int upperBound) { if ((value < lowerBound) || (value > upperBound)) { throw new IllegalFieldValueException (fieldType, Integer.valueOf(value), Integer.valueOf(lowerBound), Integer.valueOf(upperBound)); } } /** * Verify that input values are within specified bounds. * * @param value the value to check * @param lowerBound the lower bound allowed for value * @param upperBound the upper bound allowed for value * @throws IllegalFieldValueException if value is not in the specified bounds */ public static void verifyValueBounds(String fieldName, int value, int lowerBound, int upperBound) { if ((value < lowerBound) || (value > upperBound)) { throw new IllegalFieldValueException (fieldName, Integer.valueOf(value), Integer.valueOf(lowerBound), Integer.valueOf(upperBound)); } } /** * Utility method used by addWrapField implementations to ensure the new * value lies within the field's legal value range. * * @param currentValue the current value of the data, which may lie outside * the wrapped value range * @param wrapValue the value to add to current value before * wrapping. This may be negative. * @param minValue the wrap range minimum value. * @param maxValue the wrap range maximum value. This must be * greater than minValue (checked by the method). * @return the wrapped value * @throws IllegalArgumentException if minValue is greater * than or equal to maxValue */ public static int getWrappedValue(int currentValue, int wrapValue, int minValue, int maxValue) { return getWrappedValue(currentValue + wrapValue, minValue, maxValue); } /** * Utility method that ensures the given value lies within the field's * legal value range. * * @param value the value to fit into the wrapped value range * @param minValue the wrap range minimum value. * @param maxValue the wrap range maximum value. This must be * greater than minValue (checked by the method). * @return the wrapped value * @throws IllegalArgumentException if minValue is greater * than or equal to maxValue */ public static int getWrappedValue(int value, int minValue, int maxValue) { if (minValue >= maxValue) { throw new IllegalArgumentException("MIN > MAX"); } int wrapRange = maxValue - minValue + 1; value -= minValue; if (value >= 0) { return (value % wrapRange) + minValue; } int remByRange = (-value) % wrapRange; if (remByRange == 0) { return 0 + minValue; } return (wrapRange - remByRange) + minValue; } //----------------------------------------------------------------------- /** * Compares two objects as equals handling null. * * @param object1 the first object * @param object2 the second object * @return true if equal * @since 1.4 */ public static boolean equals(Object object1, Object object2) { if (object1 == object2) { return true; } if (object1 == null || object2 == null) { return false; } return object1.equals(object2); } } joda-time-2.3/src/main/java/org/joda/time/field/StrictDateTimeField.java0000644000175000017500000000440411564251363025444 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeField; /** * Converts a lenient DateTimeField into a strict one. By being strict, the set * throws an IllegalArgumentException if the value is out of bounds. *

* StrictDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @see org.joda.time.chrono.StrictChronology * @see LenientDateTimeField * @since 1.0 */ public class StrictDateTimeField extends DelegatedDateTimeField { private static final long serialVersionUID = 3154803964207950910L; /** * Returns a strict version of the given field. If it is already strict, * then it is returned as-is. Otherwise, a new StrictDateTimeField is * returned. */ public static DateTimeField getInstance(DateTimeField field) { if (field == null) { return null; } if (field instanceof LenientDateTimeField) { field = ((LenientDateTimeField)field).getWrappedField(); } if (!field.isLenient()) { return field; } return new StrictDateTimeField(field); } protected StrictDateTimeField(DateTimeField field) { super(field); } public final boolean isLenient() { return false; } /** * Does a bounds check before setting the value. * * @throws IllegalArgumentException if the value is invalid */ public long set(long instant, int value) { FieldUtils.verifyValueBounds (this, value, getMinimumValue(instant), getMaximumValue(instant)); return super.set(instant, value); } } joda-time-2.3/src/main/java/org/joda/time/field/SkipUndoDateTimeField.java0000644000175000017500000000572311564251363025735 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.Chronology; import org.joda.time.DateTimeField; /** * Wraps another field such that a certain value is added back into * the sequence of numbers. *

* This reverses the effect of SkipDateTimeField. This isn't very * elegant. *

* SkipUndoDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class SkipUndoDateTimeField extends DelegatedDateTimeField { /** Serialization version. */ private static final long serialVersionUID = -5875876968979L; /** The chronology to wrap. */ private final Chronology iChronology; /** The value to skip. */ private final int iSkip; /** The calculated minimum value. */ private transient int iMinValue; /** * Constructor that reinserts zero. * * @param chronology the chronoogy to use * @param field the field to skip zero on */ public SkipUndoDateTimeField(Chronology chronology, DateTimeField field) { this(chronology, field, 0); } /** * Constructor. * * @param chronology the chronoogy to use * @param field the field to skip zero on * @param skip the value to skip */ public SkipUndoDateTimeField(Chronology chronology, DateTimeField field, int skip) { super(field); iChronology = chronology; int min = super.getMinimumValue(); if (min < skip) { iMinValue = min + 1; } else if (min == skip + 1) { iMinValue = skip; } else { iMinValue = min; } iSkip = skip; } //----------------------------------------------------------------------- public int get(long millis) { int value = super.get(millis); if (value < iSkip) { value++; } return value; } public long set(long millis, int value) { FieldUtils.verifyValueBounds(this, value, iMinValue, getMaximumValue()); if (value <= iSkip) { value--; } return super.set(millis, value); } public int getMinimumValue() { return iMinValue; } private Object readResolve() { return getType().getField(iChronology); } } joda-time-2.3/src/main/java/org/joda/time/field/UnsupportedDateTimeField.java0000644000175000017500000003452611564251363026534 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; /** * A placeholder implementation to use when a datetime field is not supported. *

* UnsupportedDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public final class UnsupportedDateTimeField extends DateTimeField implements Serializable { /** Serialilzation version */ private static final long serialVersionUID = -1934618396111902255L; /** The cache of unsupported datetime field instances */ private static HashMap cCache; /** * Gets an instance of UnsupportedDateTimeField for a specific named field. * Names should be of standard format, such as 'monthOfYear' or 'hourOfDay'. * The returned instance is cached. * * @param type the type to obtain * @return the instance * @throws IllegalArgumentException if durationField is null */ public static synchronized UnsupportedDateTimeField getInstance( DateTimeFieldType type, DurationField durationField) { UnsupportedDateTimeField field; if (cCache == null) { cCache = new HashMap(7); field = null; } else { field = cCache.get(type); if (field != null && field.getDurationField() != durationField) { field = null; } } if (field == null) { field = new UnsupportedDateTimeField(type, durationField); cCache.put(type, field); } return field; } /** The field type */ private final DateTimeFieldType iType; /** The duration of the datetime field */ private final DurationField iDurationField; /** * Constructor. * * @param type the field type * @param durationField the duration to use */ private UnsupportedDateTimeField(DateTimeFieldType type, DurationField durationField) { if (type == null || durationField == null) { throw new IllegalArgumentException(); } iType = type; iDurationField = durationField; } //----------------------------------------------------------------------- // Design note: Simple accessors return a suitable value, but methods // intended to perform calculations throw an UnsupportedOperationException. public DateTimeFieldType getType() { return iType; } public String getName() { return iType.getName(); } /** * This field is not supported. * * @return false always */ public boolean isSupported() { return false; } /** * This field is not lenient. * * @return false always */ public boolean isLenient() { return false; } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int get(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsText(long instant, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsText(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsText(ReadablePartial partial, int fieldValue, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsText(ReadablePartial partial, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsText(int fieldValue, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsShortText(long instant, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsShortText(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsShortText(ReadablePartial partial, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public String getAsShortText(int fieldValue, Locale locale) { throw unsupported(); } /** * Delegates to the duration field. * * @throws UnsupportedOperationException if the duration is unsupported */ public long add(long instant, int value) { return getDurationField().add(instant, value); } /** * Delegates to the duration field. * * @throws UnsupportedOperationException if the duration is unsupported */ public long add(long instant, long value) { return getDurationField().add(instant, value); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long addWrapField(long instant, int value) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { throw unsupported(); } /** * Delegates to the duration field. * * @throws UnsupportedOperationException if the duration is unsupported */ public int getDifference(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifference(minuendInstant, subtrahendInstant); } /** * Delegates to the duration field. * * @throws UnsupportedOperationException if the duration is unsupported */ public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long set(long instant, int value) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long set(long instant, String text, Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long set(long instant, String text) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale) { throw unsupported(); } /** * Even though this DateTimeField is unsupported, the duration field might * be supported. * * @return a possibly supported DurationField */ public DurationField getDurationField() { return iDurationField; } /** * Always returns null. * * @return null always */ public DurationField getRangeDurationField() { return null; } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public boolean isLeap(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getLeapAmount(long instant) { throw unsupported(); } /** * Always returns null. * * @return null always */ public DurationField getLeapDurationField() { return null; } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMinimumValue() { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMinimumValue(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMinimumValue(ReadablePartial instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMinimumValue(ReadablePartial instant, int[] values) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMaximumValue() { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMaximumValue(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMaximumValue(ReadablePartial instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMaximumValue(ReadablePartial instant, int[] values) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMaximumTextLength(Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public int getMaximumShortTextLength(Locale locale) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long roundFloor(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long roundCeiling(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long roundHalfFloor(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long roundHalfCeiling(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long roundHalfEven(long instant) { throw unsupported(); } /** * Always throws UnsupportedOperationException * * @throws UnsupportedOperationException */ public long remainder(long instant) { throw unsupported(); } //------------------------------------------------------------------------ /** * Get a suitable debug string. * * @return debug string */ public String toString() { return "UnsupportedDateTimeField"; } /** * Ensure proper singleton serialization */ private Object readResolve() { return getInstance(iType, iDurationField); } private UnsupportedOperationException unsupported() { return new UnsupportedOperationException(iType + " field is unsupported"); } } joda-time-2.3/src/main/java/org/joda/time/field/RemainderDateTimeField.java0000644000175000017500000001453712203435134026101 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * Counterpart remainder datetime field to {@link DividedDateTimeField}. The * field's unit duration is unchanged, but the range duration is scaled * accordingly. *

* RemainderDateTimeField is thread-safe and immutable. * * @see DividedDateTimeField * * @author Brian S O'Neill * @since 1.0 */ public class RemainderDateTimeField extends DecoratedDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 5708241235177666790L; // Shared with DividedDateTimeField. final int iDivisor; final DurationField iRangeField; /** * Constructor. * * @param field the field to wrap, like "year()". * @param type the field type this field actually uses * @param divisor divisor, such as 100 years in a century * @throws IllegalArgumentException if divisor is less than two */ public RemainderDateTimeField(DateTimeField field, DateTimeFieldType type, int divisor) { super(field, type); if (divisor < 2) { throw new IllegalArgumentException("The divisor must be at least 2"); } DurationField rangeField = field.getDurationField(); if (rangeField == null) { iRangeField = null; } else { iRangeField = new ScaledDurationField( rangeField, type.getRangeDurationType(), divisor); } iDivisor = divisor; } /** * Construct a RemainderDateTimeField that compliments the given * DividedDateTimeField. * * @param dividedField complimentary divided field, like "century()". */ public RemainderDateTimeField(DividedDateTimeField dividedField) { this(dividedField, dividedField.getType()); } /** * Construct a RemainderDateTimeField that compliments the given * DividedDateTimeField. * * @param dividedField complimentary divided field, like "century()". * @param type the field type this field actually uses */ public RemainderDateTimeField(DividedDateTimeField dividedField, DateTimeFieldType type) { super(dividedField.getWrappedField(), type); iDivisor = dividedField.iDivisor; iRangeField = dividedField.iDurationField; } //----------------------------------------------------------------------- /** * Get the remainder from the specified time instant. * * @param instant the time instant in millis to query. * @return the remainder extracted from the input. */ public int get(long instant) { int value = getWrappedField().get(instant); if (value >= 0) { return value % iDivisor; } else { return (iDivisor - 1) + ((value + 1) % iDivisor); } } /** * Add the specified amount to the specified time instant, wrapping around * within the remainder range if necessary. The amount added may be * negative. * * @param instant the time instant in millis to update. * @param amount the amount to add (can be negative). * @return the updated time instant. */ public long addWrapField(long instant, int amount) { return set(instant, FieldUtils.getWrappedValue(get(instant), amount, 0, iDivisor - 1)); } /** * Set the specified amount of remainder units to the specified time instant. * * @param instant the time instant in millis to update. * @param value value of remainder units to set. * @return the updated time instant. * @throws IllegalArgumentException if value is too large or too small. */ public long set(long instant, int value) { FieldUtils.verifyValueBounds(this, value, 0, iDivisor - 1); int divided = getDivided(getWrappedField().get(instant)); return getWrappedField().set(instant, divided * iDivisor + value); } /** * Returns a scaled version of the wrapped field's unit duration field. */ public DurationField getRangeDurationField() { return iRangeField; } /** * Get the minimum value for the field, which is always zero. * * @return the minimum value of zero. */ public int getMinimumValue() { return 0; } /** * Get the maximum value for the field, which is always one less than the * divisor. * * @return the maximum value */ public int getMaximumValue() { return iDivisor - 1; } public long roundFloor(long instant) { return getWrappedField().roundFloor(instant); } public long roundCeiling(long instant) { return getWrappedField().roundCeiling(instant); } public long roundHalfFloor(long instant) { return getWrappedField().roundHalfFloor(instant); } public long roundHalfCeiling(long instant) { return getWrappedField().roundHalfCeiling(instant); } public long roundHalfEven(long instant) { return getWrappedField().roundHalfEven(instant); } public long remainder(long instant) { return getWrappedField().remainder(instant); } /** * Returns the divisor applied, in the field's units. * * @return the divisor */ public int getDivisor() { return iDivisor; } private int getDivided(int value) { if (value >= 0) { return value / iDivisor; } else { return ((value + 1) / iDivisor) - 1; } } } joda-time-2.3/src/main/java/org/joda/time/field/OffsetDateTimeField.java0000644000175000017500000001556512203435124025422 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * Generic offset adjusting datetime field. *

* OffsetDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public class OffsetDateTimeField extends DecoratedDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 3145790132623583142L; private final int iOffset; private final int iMin; private final int iMax; /** * Constructor. * * @param field the field to wrap, like "year()". * @param offset offset to add to field values * @throws IllegalArgumentException if offset is zero */ public OffsetDateTimeField(DateTimeField field, int offset) { this(field, (field == null ? null : field.getType()), offset, Integer.MIN_VALUE, Integer.MAX_VALUE); } /** * Constructor. * * @param field the field to wrap, like "year()". * @param type the field type this field actually uses * @param offset offset to add to field values * @throws IllegalArgumentException if offset is zero */ public OffsetDateTimeField(DateTimeField field, DateTimeFieldType type, int offset) { this(field, type, offset, Integer.MIN_VALUE, Integer.MAX_VALUE); } /** * Constructor. * * @param field the field to wrap, like "year()". * @param type the field type this field actually uses * @param offset offset to add to field values * @param minValue minimum allowed value * @param maxValue maximum allowed value * @throws IllegalArgumentException if offset is zero */ public OffsetDateTimeField(DateTimeField field, DateTimeFieldType type, int offset, int minValue, int maxValue) { super(field, type); if (offset == 0) { throw new IllegalArgumentException("The offset cannot be zero"); } iOffset = offset; if (minValue < (field.getMinimumValue() + offset)) { iMin = field.getMinimumValue() + offset; } else { iMin = minValue; } if (maxValue > (field.getMaximumValue() + offset)) { iMax = field.getMaximumValue() + offset; } else { iMax = maxValue; } } /** * Get the amount of offset units from the specified time instant. * * @param instant the time instant in millis to query. * @return the amount of units extracted from the input. */ public int get(long instant) { return super.get(instant) + iOffset; } /** * Add the specified amount of offset units to the specified time * instant. The amount added may be negative. * * @param instant the time instant in millis to update. * @param amount the amount of units to add (can be negative). * @return the updated time instant. */ public long add(long instant, int amount) { instant = super.add(instant, amount); FieldUtils.verifyValueBounds(this, get(instant), iMin, iMax); return instant; } /** * Add the specified amount of offset units to the specified time * instant. The amount added may be negative. * * @param instant the time instant in millis to update. * @param amount the amount of units to add (can be negative). * @return the updated time instant. */ public long add(long instant, long amount) { instant = super.add(instant, amount); FieldUtils.verifyValueBounds(this, get(instant), iMin, iMax); return instant; } /** * Add to the offset component of the specified time instant, * wrapping around within that component if necessary. * * @param instant the time instant in millis to update. * @param amount the amount of units to add (can be negative). * @return the updated time instant. */ public long addWrapField(long instant, int amount) { return set(instant, FieldUtils.getWrappedValue(get(instant), amount, iMin, iMax)); } /** * Set the specified amount of offset units to the specified time instant. * * @param instant the time instant in millis to update. * @param value value of units to set. * @return the updated time instant. * @throws IllegalArgumentException if value is too large or too small. */ public long set(long instant, int value) { FieldUtils.verifyValueBounds(this, value, iMin, iMax); return super.set(instant, value - iOffset); } public boolean isLeap(long instant) { return getWrappedField().isLeap(instant); } public int getLeapAmount(long instant) { return getWrappedField().getLeapAmount(instant); } public DurationField getLeapDurationField() { return getWrappedField().getLeapDurationField(); } /** * Get the minimum value for the field. * * @return the minimum value */ public int getMinimumValue() { return iMin; } /** * Get the maximum value for the field. * * @return the maximum value */ public int getMaximumValue() { return iMax; } public long roundFloor(long instant) { return getWrappedField().roundFloor(instant); } public long roundCeiling(long instant) { return getWrappedField().roundCeiling(instant); } public long roundHalfFloor(long instant) { return getWrappedField().roundHalfFloor(instant); } public long roundHalfCeiling(long instant) { return getWrappedField().roundHalfCeiling(instant); } public long roundHalfEven(long instant) { return getWrappedField().roundHalfEven(instant); } public long remainder(long instant) { return getWrappedField().remainder(instant); } /** * Returns the offset added to the field values. * * @return the offset */ public int getOffset() { return iOffset; } } joda-time-2.3/src/main/java/org/joda/time/field/DelegatedDurationField.java0000644000175000017500000001120711616003375026136 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.Serializable; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; /** * DelegatedDurationField delegates each method call to the * duration field it wraps. *

* DelegatedDurationField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @see DecoratedDurationField * @since 1.0 */ public class DelegatedDurationField extends DurationField implements Serializable { /** Serialization lock. */ private static final long serialVersionUID = -5576443481242007829L; /** The DurationField being wrapped */ private final DurationField iField; /** The field type */ private final DurationFieldType iType; /** * Constructor. * * @param field the base field */ protected DelegatedDurationField(DurationField field) { this(field, null); } /** * Constructor. * * @param field the base field * @param type the field type to use */ protected DelegatedDurationField(DurationField field, DurationFieldType type) { super(); if (field == null) { throw new IllegalArgumentException("The field must not be null"); } iField = field; iType = (type == null ? field.getType() : type); } //----------------------------------------------------------------------- /** * Gets the wrapped duration field. * * @return the wrapped DurationField */ public final DurationField getWrappedField() { return iField; } public DurationFieldType getType() { return iType; } public String getName() { return iType.getName(); } /** * Returns true if this field is supported. */ public boolean isSupported() { return iField.isSupported(); } public boolean isPrecise() { return iField.isPrecise(); } public int getValue(long duration) { return iField.getValue(duration); } public long getValueAsLong(long duration) { return iField.getValueAsLong(duration); } public int getValue(long duration, long instant) { return iField.getValue(duration, instant); } public long getValueAsLong(long duration, long instant) { return iField.getValueAsLong(duration, instant); } public long getMillis(int value) { return iField.getMillis(value); } public long getMillis(long value) { return iField.getMillis(value); } public long getMillis(int value, long instant) { return iField.getMillis(value, instant); } public long getMillis(long value, long instant) { return iField.getMillis(value, instant); } public long add(long instant, int value) { return iField.add(instant, value); } public long add(long instant, long value) { return iField.add(instant, value); } public int getDifference(long minuendInstant, long subtrahendInstant) { return iField.getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long getUnitMillis() { return iField.getUnitMillis(); } public int compareTo(DurationField durationField) { return iField.compareTo(durationField); } public boolean equals(Object obj) { if (obj instanceof DelegatedDurationField) { return iField.equals(((DelegatedDurationField) obj).iField); } return false; } public int hashCode() { return iField.hashCode() ^ iType.hashCode(); } public String toString() { return (iType == null) ? iField.toString() : ("DurationField[" + iType + ']'); } } joda-time-2.3/src/main/java/org/joda/time/field/ZeroIsMaxDateTimeField.java0000644000175000017500000001377712203435160026060 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; /** * Wraps another field such that zero values are replaced with one more than * it's maximum. This is particularly useful for implementing an clockhourOfDay * field, where the midnight value of 0 is replaced with 24. *

* ZeroIsMaxDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public final class ZeroIsMaxDateTimeField extends DecoratedDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 961749798233026866L; /** * Constructor. * * @param field the base field * @param type the field type this field will actually use * @throws IllegalArgumentException if wrapped field's minimum value is not zero */ public ZeroIsMaxDateTimeField(DateTimeField field, DateTimeFieldType type) { super(field, type); if (field.getMinimumValue() != 0) { throw new IllegalArgumentException("Wrapped field's minumum value must be zero"); } } public int get(long instant) { int value = getWrappedField().get(instant); if (value == 0) { value = getMaximumValue(); } return value; } public long add(long instant, int value) { return getWrappedField().add(instant, value); } public long add(long instant, long value) { return getWrappedField().add(instant, value); } public long addWrapField(long instant, int value) { return getWrappedField().addWrapField(instant, value); } public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { return getWrappedField().addWrapField(instant, fieldIndex, values, valueToAdd); } public int getDifference(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long set(long instant, int value) { int max = getMaximumValue(); FieldUtils.verifyValueBounds(this, value, 1, max); if (value == max) { value = 0; } return getWrappedField().set(instant, value); } public boolean isLeap(long instant) { return getWrappedField().isLeap(instant); } public int getLeapAmount(long instant) { return getWrappedField().getLeapAmount(instant); } public DurationField getLeapDurationField() { return getWrappedField().getLeapDurationField(); } /** * Always returns 1. * * @return the minimum value of 1 */ public int getMinimumValue() { return 1; } /** * Always returns 1. * * @return the minimum value of 1 */ public int getMinimumValue(long instant) { return 1; } /** * Always returns 1. * * @return the minimum value of 1 */ public int getMinimumValue(ReadablePartial instant) { return 1; } /** * Always returns 1. * * @return the minimum value of 1 */ public int getMinimumValue(ReadablePartial instant, int[] values) { return 1; } /** * Get the maximum value for the field, which is one more than the wrapped * field's maximum value. * * @return the maximum value */ public int getMaximumValue() { return getWrappedField().getMaximumValue() + 1; } /** * Get the maximum value for the field, which is one more than the wrapped * field's maximum value. * * @return the maximum value */ public int getMaximumValue(long instant) { return getWrappedField().getMaximumValue(instant) + 1; } /** * Get the maximum value for the field, which is one more than the wrapped * field's maximum value. * * @return the maximum value */ public int getMaximumValue(ReadablePartial instant) { return getWrappedField().getMaximumValue(instant) + 1; } /** * Get the maximum value for the field, which is one more than the wrapped * field's maximum value. * * @return the maximum value */ public int getMaximumValue(ReadablePartial instant, int[] values) { return getWrappedField().getMaximumValue(instant, values) + 1; } public long roundFloor(long instant) { return getWrappedField().roundFloor(instant); } public long roundCeiling(long instant) { return getWrappedField().roundCeiling(instant); } public long roundHalfFloor(long instant) { return getWrappedField().roundHalfFloor(instant); } public long roundHalfCeiling(long instant) { return getWrappedField().roundHalfCeiling(instant); } public long roundHalfEven(long instant) { return getWrappedField().roundHalfEven(instant); } public long remainder(long instant) { return getWrappedField().remainder(instant); } } joda-time-2.3/src/main/java/org/joda/time/field/DecoratedDateTimeField.java0000644000175000017500000000627012203435077026066 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * DecoratedDateTimeField extends {@link BaseDateTimeField}, * implementing only the minimum required set of methods. These implemented * methods delegate to a wrapped field. *

* This design allows new DateTimeField types to be defined that piggyback on * top of another, inheriting all the safe method implementations from * BaseDateTimeField. Should any method require pure delegation to the * wrapped field, simply override and use the provided getWrappedField method. *

* DecoratedDateTimeField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @since 1.0 * @see DelegatedDateTimeField */ public abstract class DecoratedDateTimeField extends BaseDateTimeField { /** Serialization version */ @SuppressWarnings("unused") private static final long serialVersionUID = 203115783733757597L; /** The DateTimeField being wrapped */ private final DateTimeField iField; /** * Constructor. * * @param field the field being decorated * @param type allow type to be overridden */ protected DecoratedDateTimeField(DateTimeField field, DateTimeFieldType type) { super(type); if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (!field.isSupported()) { throw new IllegalArgumentException("The field must be supported"); } iField = field; } /** * Gets the wrapped date time field. * * @return the wrapped DateTimeField */ public final DateTimeField getWrappedField() { return iField; } public boolean isLenient() { return iField.isLenient(); } public int get(long instant) { return iField.get(instant); } public long set(long instant, int value) { return iField.set(instant, value); } public DurationField getDurationField() { return iField.getDurationField(); } public DurationField getRangeDurationField() { return iField.getRangeDurationField(); } public int getMinimumValue() { return iField.getMinimumValue(); } public int getMaximumValue() { return iField.getMaximumValue(); } public long roundFloor(long instant) { return iField.roundFloor(instant); } } joda-time-2.3/src/main/java/org/joda/time/field/DividedDateTimeField.java0000644000175000017500000001674012203435106025540 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * Divides a DateTimeField such that the retrieved values are reduced by a * fixed divisor. The field's unit duration is scaled accordingly, but the * range duration is unchanged. *

* DividedDateTimeField is thread-safe and immutable. * * @see RemainderDateTimeField * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public class DividedDateTimeField extends DecoratedDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 8318475124230605365L; // Shared with RemainderDateTimeField. final int iDivisor; final DurationField iDurationField; private final int iMin; private final int iMax; /** * Constructor. * * @param field the field to wrap, like "year()". * @param type the field type this field will actually use * @param divisor divisor, such as 100 years in a century * @throws IllegalArgumentException if divisor is less than two */ public DividedDateTimeField(DateTimeField field, DateTimeFieldType type, int divisor) { super(field, type); if (divisor < 2) { throw new IllegalArgumentException("The divisor must be at least 2"); } DurationField unitField = field.getDurationField(); if (unitField == null) { iDurationField = null; } else { iDurationField = new ScaledDurationField( unitField, type.getDurationType(), divisor); } iDivisor = divisor; int i = field.getMinimumValue(); int min = (i >= 0) ? i / divisor : ((i + 1) / divisor - 1); int j = field.getMaximumValue(); int max = (j >= 0) ? j / divisor : ((j + 1) / divisor - 1); iMin = min; iMax = max; } /** * Construct a DividedDateTimeField that compliments the given * RemainderDateTimeField. * * @param remainderField complimentary remainder field, like "yearOfCentury()". * @param type the field type this field will actually use */ public DividedDateTimeField(RemainderDateTimeField remainderField, DateTimeFieldType type) { super(remainderField.getWrappedField(), type); int divisor = iDivisor = remainderField.iDivisor; iDurationField = remainderField.iRangeField; DateTimeField field = getWrappedField(); int i = field.getMinimumValue(); int min = (i >= 0) ? i / divisor : ((i + 1) / divisor - 1); int j = field.getMaximumValue(); int max = (j >= 0) ? j / divisor : ((j + 1) / divisor - 1); iMin = min; iMax = max; } /** * Get the amount of scaled units from the specified time instant. * * @param instant the time instant in millis to query. * @return the amount of scaled units extracted from the input. */ public int get(long instant) { int value = getWrappedField().get(instant); if (value >= 0) { return value / iDivisor; } else { return ((value + 1) / iDivisor) - 1; } } /** * Add the specified amount of scaled units to the specified time * instant. The amount added may be negative. * * @param instant the time instant in millis to update. * @param amount the amount of scaled units to add (can be negative). * @return the updated time instant. */ public long add(long instant, int amount) { return getWrappedField().add(instant, amount * iDivisor); } /** * Add the specified amount of scaled units to the specified time * instant. The amount added may be negative. * * @param instant the time instant in millis to update. * @param amount the amount of scaled units to add (can be negative). * @return the updated time instant. */ public long add(long instant, long amount) { return getWrappedField().add(instant, amount * iDivisor); } /** * Add to the scaled component of the specified time instant, * wrapping around within that component if necessary. * * @param instant the time instant in millis to update. * @param amount the amount of scaled units to add (can be negative). * @return the updated time instant. */ public long addWrapField(long instant, int amount) { return set(instant, FieldUtils.getWrappedValue(get(instant), amount, iMin, iMax)); } public int getDifference(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifference(minuendInstant, subtrahendInstant) / iDivisor; } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant) / iDivisor; } /** * Set the specified amount of scaled units to the specified time instant. * * @param instant the time instant in millis to update. * @param value value of scaled units to set. * @return the updated time instant. * @throws IllegalArgumentException if value is too large or too small. */ public long set(long instant, int value) { FieldUtils.verifyValueBounds(this, value, iMin, iMax); int remainder = getRemainder(getWrappedField().get(instant)); return getWrappedField().set(instant, value * iDivisor + remainder); } /** * Returns a scaled version of the wrapped field's unit duration field. */ public DurationField getDurationField() { return iDurationField; } /** * Get the minimum value for the field. * * @return the minimum value */ public int getMinimumValue() { return iMin; } /** * Get the maximum value for the field. * * @return the maximum value */ public int getMaximumValue() { return iMax; } public long roundFloor(long instant) { DateTimeField field = getWrappedField(); return field.roundFloor(field.set(instant, get(instant) * iDivisor)); } public long remainder(long instant) { return set(instant, get(getWrappedField().remainder(instant))); } /** * Returns the divisor applied, in the field's units. * * @return the divisor */ public int getDivisor() { return iDivisor; } private int getRemainder(int value) { if (value >= 0) { return value % iDivisor; } else { return (iDivisor - 1) + ((value + 1) % iDivisor); } } } joda-time-2.3/src/main/java/org/joda/time/field/DecoratedDurationField.java0000644000175000017500000000643711564251363026167 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; /** * DecoratedDurationField extends {@link BaseDurationField}, * implementing only the minimum required set of methods. These implemented * methods delegate to a wrapped field. *

* This design allows new DurationField types to be defined that piggyback on * top of another, inheriting all the safe method implementations from * BaseDurationField. Should any method require pure delegation to the * wrapped field, simply override and use the provided getWrappedField method. *

* DecoratedDurationField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @see DelegatedDurationField * @since 1.0 */ public class DecoratedDurationField extends BaseDurationField { private static final long serialVersionUID = 8019982251647420015L; /** The DurationField being wrapped */ private final DurationField iField; /** * Constructor. * * @param field the base field * @param type the type to actually use */ public DecoratedDurationField(DurationField field, DurationFieldType type) { super(type); if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (!field.isSupported()) { throw new IllegalArgumentException("The field must be supported"); } iField = field; } //----------------------------------------------------------------------- /** * Gets the wrapped duration field. * * @return the wrapped DurationField */ public final DurationField getWrappedField() { return iField; } public boolean isPrecise() { return iField.isPrecise(); } public long getValueAsLong(long duration, long instant) { return iField.getValueAsLong(duration, instant); } public long getMillis(int value, long instant) { return iField.getMillis(value, instant); } public long getMillis(long value, long instant) { return iField.getMillis(value, instant); } public long add(long instant, int value) { return iField.add(instant, value); } public long add(long instant, long value) { return iField.add(instant, value); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long getUnitMillis() { return iField.getUnitMillis(); } } joda-time-2.3/src/main/java/org/joda/time/field/AbstractPartialFieldProperty.java0000644000175000017500000002754611564251363027420 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadableInstant; import org.joda.time.ReadablePartial; /** * AbstractPartialFieldProperty is a base class for binding a * ReadablePartial to a DateTimeField. *

* It allows the date and time manipulation code to be field based yet * still easy to use. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public abstract class AbstractPartialFieldProperty { /** * Constructor. */ protected AbstractPartialFieldProperty() { super(); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public abstract DateTimeField getField(); /** * Gets the field type being used. * * @return the field type */ public DateTimeFieldType getFieldType() { return getField().getType(); } /** * Gets the name of the field. * * @return the field name */ public String getName() { return getField().getName(); } /** * Gets the partial instant being used. * * @return the partial instant */ protected abstract ReadablePartial getReadablePartial(); //----------------------------------------------------------------------- /** * Gets the value of this property from the instant. *

* For example, the following two lines of code are equivalent: *

     * partial.getDayOfMonth();
     * partial.dayOfMonth().get();
     * 
* * @return the current value */ public abstract int get(); /** * Gets the value of this property from the instant as a string. *

* This method returns the value converted to a String * using Integer.toString. This method does NOT return * textual descriptions such as 'Monday' or 'January'. * See {@link #getAsText()} and {@link #getAsShortText()} for those. * * @return the current value * @see DateTimeField#get * @since 1.1 */ public String getAsString() { return Integer.toString(get()); } /** * Gets the textual value of this property from the instant as a * string in the default locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Monday' in English. * * @return the current text value * @see DateTimeField#getAsText */ public String getAsText() { return getAsText(null); } /** * Gets the textual value of this property from the instant as a * string in the specified locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Monday' in English. * * @param locale locale to use for selecting a text symbol, null means default * @return the current text value * @see DateTimeField#getAsText */ public String getAsText(Locale locale) { return getField().getAsText(getReadablePartial(), get(), locale); } /** * Gets the short textual value of this property from the instant as a * string in the default locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Mon' in English. * * @return the current text value * @see DateTimeField#getAsShortText */ public String getAsShortText() { return getAsShortText(null); } /** * Gets the short textual value of this property from the instant as a * string in the specified locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Mon' in English. * * @param locale locale to use for selecting a text symbol, null means default * @return the current text value * @see DateTimeField#getAsShortText */ public String getAsShortText(Locale locale) { return getField().getAsShortText(getReadablePartial(), get(), locale); } //----------------------------------------------------------------------- /** * Returns the duration per unit value of this field. For example, if this * field represents "hour of day", then the duration is an hour. * * @return the duration of this field, or UnsupportedDurationField */ public DurationField getDurationField() { return getField().getDurationField(); } /** * Returns the range duration of this field. For example, if this field * represents "hour of day", then the range duration is a day. * * @return the range duration of this field, or null if field has no range */ public DurationField getRangeDurationField() { return getField().getRangeDurationField(); } //----------------------------------------------------------------------- /** * Gets the minimum value for the field ignoring the current time. * * @return the minimum value * @see DateTimeField#getMinimumValue */ public int getMinimumValueOverall() { return getField().getMinimumValue(); } /** * Gets the minimum value for this field given the current field values. * * @return the minimum value * @see DateTimeField#getMinimumValue */ public int getMinimumValue() { return getField().getMinimumValue(getReadablePartial()); } /** * Gets the maximum value for the field ignoring the current time. * * @return the maximum value * @see DateTimeField#getMaximumValue */ public int getMaximumValueOverall() { return getField().getMaximumValue(); } /** * Gets the maximum value for this field given the current field values. * * @return the maximum value * @see DateTimeField#getMaximumValue */ public int getMaximumValue() { return getField().getMaximumValue(getReadablePartial()); } //----------------------------------------------------------------------- /** * Gets the maximum text length for the field. * * @param locale optional locale to use for selecting a text symbol * @return the maximum length * @see DateTimeField#getMaximumTextLength */ public int getMaximumTextLength(Locale locale) { return getField().getMaximumTextLength(locale); } /** * Gets the maximum short text length for the field. * * @param locale optional locale to use for selecting a text symbol * @return the maximum length * @see DateTimeField#getMaximumShortTextLength */ public int getMaximumShortTextLength(Locale locale) { return getField().getMaximumShortTextLength(locale); } //----------------------------------------------------------------------- /** * Compare this field to the same field on another instant. *

* The comparison is based on the value of the same field type, irrespective * of any difference in chronology. Thus, if this property represents the * hourOfDay field, then the hourOfDay field of the other instant will be queried * whether in the same chronology or not. * * @param instant the instant to compare to * @return negative value if this is less, 0 if equal, or positive value if greater * @throws IllegalArgumentException if the instant is null or the instant * doesn't support the field of this property */ public int compareTo(ReadableInstant instant) { if (instant == null) { throw new IllegalArgumentException("The instant must not be null"); } int thisValue = get(); int otherValue = instant.get(getFieldType()); if (thisValue < otherValue) { return -1; } else if (thisValue > otherValue) { return 1; } else { return 0; } } /** * Compare this field to the same field on another partial instant. *

* The comparison is based on the value of the same field type, irrespective * of any difference in chronology. Thus, if this property represents the * hourOfDay field, then the hourOfDay field of the other partial will be queried * whether in the same chronology or not. * * @param partial the partial to compare to * @return negative value if this is less, 0 if equal, or positive value if greater * @throws IllegalArgumentException if the instant is null * @throws IllegalArgumentException if the field of this property cannot be queried * on the specified instant */ public int compareTo(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("The instant must not be null"); } int thisValue = get(); int otherValue = partial.get(getFieldType()); if (thisValue < otherValue) { return -1; } else if (thisValue > otherValue) { return 1; } else { return 0; } } //----------------------------------------------------------------------- /** * Compares this property to another. * * @param object the object to compare to * @return true if equal */ public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof AbstractPartialFieldProperty == false) { return false; } AbstractPartialFieldProperty other = (AbstractPartialFieldProperty) object; return get() == other.get() && getFieldType() == other.getFieldType() && FieldUtils.equals(getReadablePartial().getChronology(), other.getReadablePartial().getChronology()); } //----------------------------------------------------------------------- /** * Gets a suitable hashcode for the object. * * @return the hashcode * @since 1.3 */ public int hashCode() { int hash = 19; hash = 13 * hash + get(); hash = 13 * hash + getFieldType().hashCode(); hash = 13 * hash + getReadablePartial().getChronology().hashCode(); return hash; } //----------------------------------------------------------------------- /** * Output a debugging string. * * @return debugging string */ public String toString() { return "Property[" + getName() + "]"; } } joda-time-2.3/src/main/java/org/joda/time/field/BaseDurationField.java0000644000175000017500000001267511564251363025150 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.Serializable; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; /** * BaseDurationField provides the common behaviour for DurationField * implementations. *

* This class should generally not be used directly by API users. The * DurationField class should be used when different kinds of DurationField * objects are to be referenced. *

* BaseDurationField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @see DecoratedDurationField * @since 1.0 */ public abstract class BaseDurationField extends DurationField implements Serializable { /** Serialization lock. */ private static final long serialVersionUID = -2554245107589433218L; /** A desriptive name for the field. */ private final DurationFieldType iType; protected BaseDurationField(DurationFieldType type) { super(); if (type == null) { throw new IllegalArgumentException("The type must not be null"); } iType = type; } public final DurationFieldType getType() { return iType; } public final String getName() { return iType.getName(); } /** * @return true always */ public final boolean isSupported() { return true; } //------------------------------------------------------------------------ /** * Get the value of this field from the milliseconds, which is approximate * if this field is imprecise. * * @param duration the milliseconds to query, which may be negative * @return the value of the field, in the units of the field, which may be * negative */ public int getValue(long duration) { return FieldUtils.safeToInt(getValueAsLong(duration)); } /** * Get the value of this field from the milliseconds, which is approximate * if this field is imprecise. * * @param duration the milliseconds to query, which may be negative * @return the value of the field, in the units of the field, which may be * negative */ public long getValueAsLong(long duration) { return duration / getUnitMillis(); } /** * Get the value of this field from the milliseconds relative to an * instant. * *

If the milliseconds is positive, then the instant is treated as a * "start instant". If negative, the instant is treated as an "end * instant". * *

The default implementation returns * Utils.safeToInt(getAsLong(millisDuration, instant)). * * @param duration the milliseconds to query, which may be negative * @param instant the start instant to calculate relative to * @return the value of the field, in the units of the field, which may be * negative */ public int getValue(long duration, long instant) { return FieldUtils.safeToInt(getValueAsLong(duration, instant)); } /** * Get the millisecond duration of this field from its value, which is * approximate if this field is imprecise. * * @param value the value of the field, which may be negative * @return the milliseconds that the field represents, which may be * negative */ public long getMillis(int value) { return value * getUnitMillis(); // safe } /** * Get the millisecond duration of this field from its value, which is * approximate if this field is imprecise. * * @param value the value of the field, which may be negative * @return the milliseconds that the field represents, which may be * negative */ public long getMillis(long value) { return FieldUtils.safeMultiply(value, getUnitMillis()); } // Calculation API //------------------------------------------------------------------------ public int getDifference(long minuendInstant, long subtrahendInstant) { return FieldUtils.safeToInt(getDifferenceAsLong(minuendInstant, subtrahendInstant)); } //------------------------------------------------------------------------ public int compareTo(DurationField otherField) { long otherMillis = otherField.getUnitMillis(); long thisMillis = getUnitMillis(); // cannot do (thisMillis - otherMillis) as can overflow if (thisMillis == otherMillis) { return 0; } if (thisMillis < otherMillis) { return -1; } else { return 1; } } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return "DurationField[" + getName() + ']'; } } joda-time-2.3/src/main/java/org/joda/time/field/LenientDateTimeField.java0000644000175000017500000000524611564251363025577 0ustar ebourgebourg/* * Copyright 2001-2007 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.Chronology; import org.joda.time.DateTimeField; /** * Converts a strict DateTimeField into a lenient one. By being lenient, the * set method accepts out of bounds values, performing an addition instead. *

* LenientDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @see org.joda.time.chrono.LenientChronology * @see StrictDateTimeField * @since 1.0 */ public class LenientDateTimeField extends DelegatedDateTimeField { private static final long serialVersionUID = 8714085824173290599L; private final Chronology iBase; /** * Returns a lenient version of the given field. If it is already lenient, * then it is returned as-is. Otherwise, a new LenientDateTimeField is * returned. */ public static DateTimeField getInstance(DateTimeField field, Chronology base) { if (field == null) { return null; } if (field instanceof StrictDateTimeField) { field = ((StrictDateTimeField)field).getWrappedField(); } if (field.isLenient()) { return field; } return new LenientDateTimeField(field, base); } protected LenientDateTimeField(DateTimeField field, Chronology base) { super(field); iBase = base; } public final boolean isLenient() { return true; } /** * Set values which may be out of bounds by adding the difference between * the new value and the current value. */ public long set(long instant, int value) { // lenient needs to handle time zone chronologies // so we do the calculation using local milliseconds long localInstant = iBase.getZone().convertUTCToLocal(instant); long difference = FieldUtils.safeSubtract(value, get(instant)); localInstant = getType().getField(iBase.withUTC()).add(localInstant, difference); return iBase.getZone().convertLocalToUTC(localInstant, false, instant); } } joda-time-2.3/src/main/java/org/joda/time/field/MillisDurationField.java0000644000175000017500000001106511616003375025513 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.Serializable; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; /** * Duration field class representing a field with a fixed unit length of one * millisecond. *

* MillisDurationField is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public final class MillisDurationField extends DurationField implements Serializable { /** Serialization lock. */ private static final long serialVersionUID = 2656707858124633367L; /** Singleton instance. */ public static final DurationField INSTANCE = new MillisDurationField(); /** * Restricted constructor. */ private MillisDurationField() { super(); } //------------------------------------------------------------------------ public DurationFieldType getType() { return DurationFieldType.millis(); } public String getName() { return "millis"; } /** * Returns true as this field is supported. * * @return true always */ public boolean isSupported() { return true; } /** * Returns true as this field is precise. * * @return true always */ public final boolean isPrecise() { return true; } /** * Returns the amount of milliseconds per unit value of this field. * * @return one always */ public final long getUnitMillis() { return 1; } //------------------------------------------------------------------------ public int getValue(long duration) { return FieldUtils.safeToInt(duration); } public long getValueAsLong(long duration) { return duration; } public int getValue(long duration, long instant) { return FieldUtils.safeToInt(duration); } public long getValueAsLong(long duration, long instant) { return duration; } public long getMillis(int value) { return value; } public long getMillis(long value) { return value; } public long getMillis(int value, long instant) { return value; } public long getMillis(long value, long instant) { return value; } public long add(long instant, int value) { return FieldUtils.safeAdd(instant, value); } public long add(long instant, long value) { return FieldUtils.safeAdd(instant, value); } public int getDifference(long minuendInstant, long subtrahendInstant) { return FieldUtils.safeToInt(FieldUtils.safeSubtract(minuendInstant, subtrahendInstant)); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return FieldUtils.safeSubtract(minuendInstant, subtrahendInstant); } //------------------------------------------------------------------------ public int compareTo(DurationField otherField) { long otherMillis = otherField.getUnitMillis(); long thisMillis = getUnitMillis(); // cannot do (thisMillis - otherMillis) as can overflow if (thisMillis == otherMillis) { return 0; } if (thisMillis < otherMillis) { return -1; } else { return 1; } } public boolean equals(Object obj) { if (obj instanceof MillisDurationField) { return getUnitMillis() == ((MillisDurationField) obj).getUnitMillis(); } return false; } public int hashCode() { return (int) getUnitMillis(); } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return "DurationField[millis]"; } /** * Deserialize to the singleton. */ private Object readResolve() { return INSTANCE; } } joda-time-2.3/src/main/java/org/joda/time/field/AbstractReadableInstantFieldProperty.java0000644000175000017500000003726211564251363031060 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.io.Serializable; import java.util.Locale; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DurationField; import org.joda.time.Interval; import org.joda.time.ReadableInstant; import org.joda.time.ReadablePartial; /** * AbstractReadableInstantFieldProperty is a base class for binding a * ReadableInstant to a DateTimeField. *

* It allows the date and time manipulation code to be field based yet * still easy to use. *

* AbstractReadableInstantFieldProperty itself is thread-safe and immutable, * but the ReadableInstant being operated on may be mutable and not * thread-safe. * * @author Stephen Colebourne * @author Brian S O'Neill * @author Mike Schrag * @since 1.0 */ public abstract class AbstractReadableInstantFieldProperty implements Serializable { /** Serialization version. */ private static final long serialVersionUID = 1971226328211649661L; /** * Constructor. */ public AbstractReadableInstantFieldProperty() { super(); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public abstract DateTimeField getField(); /** * Gets the field type being used. * * @return the field type */ public DateTimeFieldType getFieldType() { return getField().getType(); } /** * Gets the name of the field. * * @return the field name */ public String getName() { return getField().getName(); } /** * Gets the milliseconds of the datetime that this property is linked to. * * @return the milliseconds */ protected abstract long getMillis(); /** * Gets the chronology of the datetime that this property is linked to. *

* This implementation throws UnsupportedOperationException, and must be * implemented by subclasses to enable the equals() and hashCode() methods. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { throw new UnsupportedOperationException( "The method getChronology() was added in v1.4 and needs " + "to be implemented by subclasses of AbstractReadableInstantFieldProperty"); } //----------------------------------------------------------------------- /** * Gets the value of this property from the instant. *

* For example, the following two lines of code are equivalent: *

     * datetime.getDayOfMonth();
     * datetime.dayOfMonth().get();
     * 
* * @return the current value * @see DateTimeField#get */ public int get() { return getField().get(getMillis()); } /** * Gets the value of this property from the instant as a string. *

* This method returns the value converted to a String * using Integer.toString. This method does NOT return * textual descriptions such as 'Monday' or 'January'. * See {@link #getAsText()} and {@link #getAsShortText()} for those. * * @return the current value * @see DateTimeField#get * @since 1.1 */ public String getAsString() { return Integer.toString(get()); } /** * Gets the textual value of this property from the instant as a * string in the default locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Monday' in English. * * @return the current text value * @see DateTimeField#getAsText */ public String getAsText() { return getAsText(null); } /** * Gets the textual value of this property from the instant as a * string in the specified locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Monday' in English. * * @param locale locale to use for selecting a text symbol, null means default * @return the current text value * @see DateTimeField#getAsText */ public String getAsText(Locale locale) { return getField().getAsText(getMillis(), locale); } /** * Gets the short textual value of this property from the instant as a * string in the default locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Mon' in English. * * @return the current text value * @see DateTimeField#getAsShortText */ public String getAsShortText() { return getAsShortText(null); } /** * Gets the short textual value of this property from the instant as a * string in the specified locale. *

* This method returns the value converted to a String * returning the appropriate textual description wherever possible. * Thus, a day of week of 1 would return 'Mon' in English. * * @param locale locale to use for selecting a text symbol, null means default * @return the current text value * @see DateTimeField#getAsShortText */ public String getAsShortText(Locale locale) { return getField().getAsShortText(getMillis(), locale); } //----------------------------------------------------------------------- /** * Returns the difference between this field property instant and the one * passed in, in the units of this field. The sign of the difference * matches that of compareTo. In other words, this field property's instant * is the minuend. * * @param instant the subtrahend, null means now * @return the difference in the units of this field * @see DateTimeField#getDifference */ public int getDifference(ReadableInstant instant) { if (instant == null) { return getField().getDifference(getMillis(), DateTimeUtils.currentTimeMillis()); } return getField().getDifference(getMillis(), instant.getMillis()); } /** * Returns the difference between this field property instant and the one * passed in, in the units of this field. The sign of the difference * matches that of compareTo. In other words, this field property's instant * is the minuend. * * @param instant the subtrahend, null means now * @return the difference in the units of this field * @see DateTimeField#getDifference */ public long getDifferenceAsLong(ReadableInstant instant) { if (instant == null) { return getField().getDifferenceAsLong(getMillis(), DateTimeUtils.currentTimeMillis()); } return getField().getDifferenceAsLong(getMillis(), instant.getMillis()); } //----------------------------------------------------------------------- /** * Returns the duration per unit value of this field. For example, if this * field represents "hour of day", then the duration is an hour. * * @return the duration of this field, or UnsupportedDurationField */ public DurationField getDurationField() { return getField().getDurationField(); } /** * Returns the range duration of this field. For example, if this field * represents "hour of day", then the range duration is a day. * * @return the range duration of this field, or null if field has no range */ public DurationField getRangeDurationField() { return getField().getRangeDurationField(); } /** * Gets whether this field is leap. * * @return true if a leap field * @see DateTimeField#isLeap */ public boolean isLeap() { return getField().isLeap(getMillis()); } /** * Gets the amount by which this field is leap. * * @return the amount by which the field is leap * @see DateTimeField#getLeapAmount */ public int getLeapAmount() { return getField().getLeapAmount(getMillis()); } /** * If this field were to leap, then it would be in units described by the * returned duration. If this field doesn't ever leap, null is returned. */ public DurationField getLeapDurationField() { return getField().getLeapDurationField(); } //----------------------------------------------------------------------- /** * Gets the minimum value for the field ignoring the current time. * * @return the minimum value * @see DateTimeField#getMinimumValue */ public int getMinimumValueOverall() { return getField().getMinimumValue(); } /** * Gets the minimum value for the field. * * @return the minimum value * @see DateTimeField#getMinimumValue */ public int getMinimumValue() { return getField().getMinimumValue(getMillis()); } /** * Gets the maximum value for the field ignoring the current time. * * @return the maximum value * @see DateTimeField#getMaximumValue */ public int getMaximumValueOverall() { return getField().getMaximumValue(); } /** * Gets the maximum value for the field. * * @return the maximum value * @see DateTimeField#getMaximumValue */ public int getMaximumValue() { return getField().getMaximumValue(getMillis()); } /** * Gets the maximum text length for the field. * * @param locale optional locale to use for selecting a text symbol * @return the maximum length * @see DateTimeField#getMaximumTextLength */ public int getMaximumTextLength(Locale locale) { return getField().getMaximumTextLength(locale); } /** * Gets the maximum short text length for the field. * * @param locale optional locale to use for selecting a text symbol * @return the maximum length * @see DateTimeField#getMaximumShortTextLength */ public int getMaximumShortTextLength(Locale locale) { return getField().getMaximumShortTextLength(locale); } /** * Returns the fractional duration milliseconds of this field. * * @see DateTimeField#remainder * @return remainder duration, in milliseconds */ public long remainder() { return getField().remainder(getMillis()); } /** * Returns the interval that represents the range of the minimum * and maximum values of this field. *

* For example, datetime.monthOfYear().toInterval() * will return an interval over the whole month. * * @return the interval of this field * @since 1.2 */ public Interval toInterval() { DateTimeField field = getField(); long start = field.roundFloor(getMillis()); long end = field.add(start, 1); Interval interval = new Interval(start, end); return interval; } //----------------------------------------------------------------------- /** * Compare this field to the same field on another instant. *

* The comparison is based on the value of the same field type, irrespective * of any difference in chronology. Thus, if this property represents the * hourOfDay field, then the hourOfDay field of the other instant will be queried * whether in the same chronology or not. * * @param instant the instant to compare to * @return negative value if this is less, 0 if equal, or positive value if greater * @throws IllegalArgumentException if the instant is null */ public int compareTo(ReadableInstant instant) { if (instant == null) { throw new IllegalArgumentException("The instant must not be null"); } int thisValue = get(); int otherValue = instant.get(getFieldType()); if (thisValue < otherValue) { return -1; } else if (thisValue > otherValue) { return 1; } else { return 0; } } //----------------------------------------------------------------------- /** * Compare this field to the same field on another partial instant. *

* The comparison is based on the value of the same field type, irrespective * of any difference in chronology. Thus, if this property represents the * hourOfDay field, then the hourOfDay field of the other partial will be queried * whether in the same chronology or not. * * @param partial the partial to compare to * @return negative value if this is less, 0 if equal, or positive value if greater * @throws IllegalArgumentException if the partial is null * @throws IllegalArgumentException if the partial doesn't support this field */ public int compareTo(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("The partial must not be null"); } int thisValue = get(); int otherValue = partial.get(getFieldType()); if (thisValue < otherValue) { return -1; } else if (thisValue > otherValue) { return 1; } else { return 0; } } //----------------------------------------------------------------------- /** * Compares this property to another. * * @param object the object to compare to * @return true if equal */ public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof AbstractReadableInstantFieldProperty == false) { return false; } AbstractReadableInstantFieldProperty other = (AbstractReadableInstantFieldProperty) object; return get() == other.get() && getFieldType().equals(other.getFieldType()) && FieldUtils.equals(getChronology(), other.getChronology()); } /** * Returns a hashcode compatible with the equals method. * * @return the hashcode */ public int hashCode() { return get() * 17 + getFieldType().hashCode() + getChronology().hashCode(); } //----------------------------------------------------------------------- /** * Output a debugging string. * * @return debugging string */ public String toString() { return "Property[" + getName() + "]"; } } joda-time-2.3/src/main/java/org/joda/time/field/PreciseDurationField.java0000644000175000017500000001115611564251363025661 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DurationFieldType; /** * Duration field class representing a field with a fixed unit length. *

* PreciseDurationField is thread-safe and immutable. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public class PreciseDurationField extends BaseDurationField { private static final long serialVersionUID = -8346152187724495365L; /** The size of the unit */ private final long iUnitMillis; /** * Constructor. * * @param type the field type * @param unitMillis the unit milliseconds */ public PreciseDurationField(DurationFieldType type, long unitMillis) { super(type); iUnitMillis = unitMillis; } //------------------------------------------------------------------------ /** * This field is precise. * * @return true always */ public final boolean isPrecise() { return true; } /** * Returns the amount of milliseconds per unit value of this field. * * @return the unit size of this field, in milliseconds */ public final long getUnitMillis() { return iUnitMillis; } //------------------------------------------------------------------------ /** * Get the value of this field from the milliseconds. * * @param duration the milliseconds to query, which may be negative * @param instant ignored * @return the value of the field, in the units of the field, which may be * negative */ public long getValueAsLong(long duration, long instant) { return duration / iUnitMillis; // safe } /** * Get the millisecond duration of this field from its value. * * @param value the value of the field, which may be negative * @param instant ignored * @return the milliseconds that the field represents, which may be * negative */ public long getMillis(int value, long instant) { return value * iUnitMillis; // safe } /** * Get the millisecond duration of this field from its value. * * @param value the value of the field, which may be negative * @param instant ignored * @return the milliseconds that the field represents, which may be * negative */ public long getMillis(long value, long instant) { return FieldUtils.safeMultiply(value, iUnitMillis); } public long add(long instant, int value) { long addition = value * iUnitMillis; // safe return FieldUtils.safeAdd(instant, addition); } public long add(long instant, long value) { long addition = FieldUtils.safeMultiply(value, iUnitMillis); return FieldUtils.safeAdd(instant, addition); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { long difference = FieldUtils.safeSubtract(minuendInstant, subtrahendInstant); return difference / iUnitMillis; } //----------------------------------------------------------------------- /** * Compares this duration field to another. * Two fields are equal if of the same type and duration. * * @param obj the object to compare to * @return if equal */ public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof PreciseDurationField) { PreciseDurationField other = (PreciseDurationField) obj; return (getType() == other.getType()) && (iUnitMillis == other.iUnitMillis); } return false; } /** * Gets a hash code for this instance. * * @return a suitable hashcode */ public int hashCode() { long millis = iUnitMillis; int hash = (int) (millis ^ (millis >>> 32)); hash += getType().hashCode(); return hash; } } joda-time-2.3/src/main/java/org/joda/time/field/BaseDateTimeField.java0000644000175000017500000012136411564251363025053 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.IllegalFieldValueException; import org.joda.time.ReadablePartial; /** * BaseDateTimeField provides the common behaviour for DateTimeField * implementations. *

* This class should generally not be used directly by API users. The * DateTimeField class should be used when different kinds of DateTimeField * objects are to be referenced. *

* BaseDateTimeField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @since 1.0 * @see DecoratedDateTimeField */ public abstract class BaseDateTimeField extends DateTimeField { /** The field type. */ private final DateTimeFieldType iType; /** * Constructor. */ protected BaseDateTimeField(DateTimeFieldType type) { super(); if (type == null) { throw new IllegalArgumentException("The type must not be null"); } iType = type; } public final DateTimeFieldType getType() { return iType; } public final String getName() { return iType.getName(); } /** * @return true always */ public final boolean isSupported() { return true; } // Main access API //------------------------------------------------------------------------ /** * Get the value of this field from the milliseconds. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the value of the field, in the units of the field */ public abstract int get(long instant); //----------------------------------------------------------------------- /** * Get the human-readable, text value of this field from the milliseconds. * If the specified locale is null, the default locale is used. *

* The default implementation returns getAsText(get(instant), locale). * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null means default * @return the text value of the field */ public String getAsText(long instant, Locale locale) { return getAsText(get(instant), locale); } /** * Get the human-readable, text value of this field from the milliseconds. *

* The default implementation calls {@link #getAsText(long, Locale)}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the text value of the field */ public final String getAsText(long instant) { return getAsText(instant, null); } /** * Get the human-readable, text value of this field from a partial instant. * If the specified locale is null, the default locale is used. *

* The default implementation returns getAsText(fieldValue, locale). * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsText(ReadablePartial partial, int fieldValue, Locale locale) { return getAsText(fieldValue, locale); } /** * Get the human-readable, text value of this field from a partial instant. * If the specified locale is null, the default locale is used. *

* The default implementation calls {@link ReadablePartial#get(DateTimeFieldType)} * and {@link #getAsText(ReadablePartial, int, Locale)}. * * @param partial the partial instant to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public final String getAsText(ReadablePartial partial, Locale locale) { return getAsText(partial, partial.get(getType()), locale); } /** * Get the human-readable, text value of this field from the field value. * If the specified locale is null, the default locale is used. *

* The default implementation returns Integer.toString(get(instant)). *

* Note: subclasses that override this method should also override * getMaximumTextLength. * * @param fieldValue the numeric value to convert to text * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsText(int fieldValue, Locale locale) { return Integer.toString(fieldValue); } //----------------------------------------------------------------------- /** * Get the human-readable, short text value of this field from the milliseconds. * If the specified locale is null, the default locale is used. *

* The default implementation returns getAsShortText(get(instant), locale). * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null means default * @return the text value of the field */ public String getAsShortText(long instant, Locale locale) { return getAsShortText(get(instant), locale); } /** * Get the human-readable, short text value of this field from the milliseconds. *

* The default implementation calls {@link #getAsShortText(long, Locale)}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the text value of the field */ public final String getAsShortText(long instant) { return getAsShortText(instant, null); } /** * Get the human-readable, short text value of this field from a partial instant. * If the specified locale is null, the default locale is used. *

* The default implementation returns getAsShortText(fieldValue, locale). * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale) { return getAsShortText(fieldValue, locale); } /** * Get the human-readable, short text value of this field from a partial instant. * If the specified locale is null, the default locale is used. *

* The default implementation calls {@link ReadablePartial#get(DateTimeFieldType)} * and {@link #getAsText(ReadablePartial, int, Locale)}. * * @param partial the partial instant to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public final String getAsShortText(ReadablePartial partial, Locale locale) { return getAsShortText(partial, partial.get(getType()), locale); } /** * Get the human-readable, short text value of this field from the field value. * If the specified locale is null, the default locale is used. *

* The default implementation returns getAsText(fieldValue, locale). *

* Note: subclasses that override this method should also override * getMaximumShortTextLength. * * @param fieldValue the numeric value to convert to text * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsShortText(int fieldValue, Locale locale) { return getAsText(fieldValue, locale); } //----------------------------------------------------------------------- /** * Adds a value (which may be negative) to the instant value, * overflowing into larger fields if necessary. *

* The value will be added to this field. If the value is too large to be * added solely to this field, larger fields will increase as required. * Smaller fields should be unaffected, except where the result would be * an invalid value for a smaller field. In this case the smaller field is * adjusted to be in range. *

* For example, in the ISO chronology:
* 2000-08-20 add six months is 2001-02-20
* 2000-08-20 add twenty months is 2002-04-20
* 2000-08-20 add minus nine months is 1999-11-20
* 2001-01-31 add one month is 2001-02-28
* 2001-01-31 add two months is 2001-03-31
* * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public long add(long instant, int value) { return getDurationField().add(instant, value); } /** * Adds a value (which may be negative) to the instant value, * overflowing into larger fields if necessary. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the long value to add, in the units of the field * @return the updated milliseconds * @throws IllegalArgumentException if value is too large * @see #add(long,int) */ public long add(long instant, long value) { return getDurationField().add(instant, value); } /** * Adds a value (which may be negative) to the partial instant, * throwing an exception if the maximum size of the instant is reached. *

* The value will be added to this field, overflowing into larger fields * if necessary. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* Partial instants only contain some fields. This may result in a maximum * possible value, such as TimeOfDay being limited to 23:59:59:999. If this * limit is breached by the add an exception is thrown. *

* For example, in the ISO chronology:
* 2000-08-20 add six months is 2000-02-20
* 2000-08-20 add twenty months is 2000-04-20
* 2000-08-20 add minus nine months is 2000-11-20
* 2001-01-31 add one month is 2001-02-28
* 2001-01-31 add two months is 2001-03-31
* * @param instant the partial instant * @param fieldIndex the index of this field in the partial * @param values the values of the partial instant which should be updated * @param valueToAdd the value to add, in the units of the field * @return the passed in values * @throws IllegalArgumentException if the value is invalid or the maximum instant is reached */ public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { if (valueToAdd == 0) { return values; } // there are more efficient algorithms than this (especially for time only fields) // trouble is when dealing with days and months, so we use this technique of // adding/removing one from the larger field at a time DateTimeField nextField = null; while (valueToAdd > 0) { int max = getMaximumValue(instant, values); long proposed = values[fieldIndex] + valueToAdd; if (proposed <= max) { values[fieldIndex] = (int) proposed; break; } if (nextField == null) { if (fieldIndex == 0) { throw new IllegalArgumentException("Maximum value exceeded for add"); } nextField = instant.getField(fieldIndex - 1); // test only works if this field is UTC (ie. local) if (getRangeDurationField().getType() != nextField.getDurationField().getType()) { throw new IllegalArgumentException("Fields invalid for add"); } } valueToAdd -= (max + 1) - values[fieldIndex]; // reduce the amount to add values = nextField.add(instant, fieldIndex - 1, values, 1); // add 1 to next bigger field values[fieldIndex] = getMinimumValue(instant, values); // reset this field to zero } while (valueToAdd < 0) { int min = getMinimumValue(instant, values); long proposed = values[fieldIndex] + valueToAdd; if (proposed >= min) { values[fieldIndex] = (int) proposed; break; } if (nextField == null) { if (fieldIndex == 0) { throw new IllegalArgumentException("Maximum value exceeded for add"); } nextField = instant.getField(fieldIndex - 1); if (getRangeDurationField().getType() != nextField.getDurationField().getType()) { throw new IllegalArgumentException("Fields invalid for add"); } } valueToAdd -= (min - 1) - values[fieldIndex]; // reduce the amount to add values = nextField.add(instant, fieldIndex - 1, values, -1); // subtract 1 from next bigger field values[fieldIndex] = getMaximumValue(instant, values); // reset this field to max value } return set(instant, fieldIndex, values, values[fieldIndex]); // adjusts smaller fields } /** * Adds a value (which may be negative) to the partial instant, * wrapping the whole partial if the maximum size of the partial is reached. *

* The value will be added to this field, overflowing into larger fields * if necessary. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* Partial instants only contain some fields. This may result in a maximum * possible value, such as TimeOfDay normally being limited to 23:59:59:999. * If ths limit is reached by the addition, this method will wrap back to * 00:00:00.000. In fact, you would generally only use this method for * classes that have a limitation such as this. *

* For example, in the ISO chronology:
* 10:20:30 add 20 minutes is 10:40:30
* 10:20:30 add 45 minutes is 11:05:30
* 10:20:30 add 16 hours is 02:20:30
* * @param instant the partial instant * @param fieldIndex the index of this field in the partial * @param values the values of the partial instant which should be updated * @param valueToAdd the value to add, in the units of the field * @return the passed in values * @throws IllegalArgumentException if the value is invalid or the maximum instant is reached */ public int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { if (valueToAdd == 0) { return values; } // there are more efficient algorithms than this (especially for time only fields) // trouble is when dealing with days and months, so we use this technique of // adding/removing one from the larger field at a time DateTimeField nextField = null; while (valueToAdd > 0) { int max = getMaximumValue(instant, values); long proposed = values[fieldIndex] + valueToAdd; if (proposed <= max) { values[fieldIndex] = (int) proposed; break; } if (nextField == null) { if (fieldIndex == 0) { valueToAdd -= (max + 1) - values[fieldIndex]; values[fieldIndex] = getMinimumValue(instant, values); continue; } nextField = instant.getField(fieldIndex - 1); // test only works if this field is UTC (ie. local) if (getRangeDurationField().getType() != nextField.getDurationField().getType()) { throw new IllegalArgumentException("Fields invalid for add"); } } valueToAdd -= (max + 1) - values[fieldIndex]; // reduce the amount to add values = nextField.addWrapPartial(instant, fieldIndex - 1, values, 1); // add 1 to next bigger field values[fieldIndex] = getMinimumValue(instant, values); // reset this field to zero } while (valueToAdd < 0) { int min = getMinimumValue(instant, values); long proposed = values[fieldIndex] + valueToAdd; if (proposed >= min) { values[fieldIndex] = (int) proposed; break; } if (nextField == null) { if (fieldIndex == 0) { valueToAdd -= (min - 1) - values[fieldIndex]; values[fieldIndex] = getMaximumValue(instant, values); continue; } nextField = instant.getField(fieldIndex - 1); if (getRangeDurationField().getType() != nextField.getDurationField().getType()) { throw new IllegalArgumentException("Fields invalid for add"); } } valueToAdd -= (min - 1) - values[fieldIndex]; // reduce the amount to add values = nextField.addWrapPartial(instant, fieldIndex - 1, values, -1); // subtract 1 from next bigger field values[fieldIndex] = getMaximumValue(instant, values); // reset this field to max value } return set(instant, fieldIndex, values, values[fieldIndex]); // adjusts smaller fields } /** * Adds a value (which may be negative) to the instant value, * wrapping within this field. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps. Larger fields are always * unaffected. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* For example, in the ISO chronology:
* 2000-08-20 addWrapField six months is 2000-02-20
* 2000-08-20 addWrapField twenty months is 2000-04-20
* 2000-08-20 addWrapField minus nine months is 2000-11-20
* 2001-01-31 addWrapField one month is 2001-02-28
* 2001-01-31 addWrapField two months is 2001-03-31
*

* The default implementation internally calls set. Subclasses are * encouraged to provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public long addWrapField(long instant, int value) { int current = get(instant); int wrapped = FieldUtils.getWrappedValue (current, value, getMinimumValue(instant), getMaximumValue(instant)); return set(instant, wrapped); } /** * Adds a value (which may be negative) to the partial instant, * wrapping within this field. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps. Larger fields are always * unaffected. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* For example, in the ISO chronology:
* 2000-08-20 addWrapField six months is 2000-02-20
* 2000-08-20 addWrapField twenty months is 2000-04-20
* 2000-08-20 addWrapField minus nine months is 2000-11-20
* 2001-01-31 addWrapField one month is 2001-02-28
* 2001-01-31 addWrapField two months is 2001-03-31
*

* The default implementation internally calls set. Subclasses are * encouraged to provide a more efficient implementation. * * @param instant the partial instant * @param fieldIndex the index of this field in the instant * @param values the values of the partial instant which should be updated * @param valueToAdd the value to add, in the units of the field * @return the passed in values * @throws IllegalArgumentException if the value is invalid */ public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { int current = values[fieldIndex]; int wrapped = FieldUtils.getWrappedValue (current, valueToAdd, getMinimumValue(instant), getMaximumValue(instant)); return set(instant, fieldIndex, values, wrapped); // adjusts smaller fields } //----------------------------------------------------------------------- /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *

     * long instant = ...
     * int v = ...
     * int age = getDifference(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public int getDifference(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifference(minuendInstant, subtrahendInstant); } /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *
     * long instant = ...
     * long v = ...
     * long age = getDifferenceAsLong(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } /** * Sets a value in the milliseconds supplied. *

* The value of this field will be set. * If the value is invalid, an exception if thrown. *

* If setting this field would make other fields invalid, then those fields * may be changed. For example if the current date is the 31st January, and * the month is set to February, the day would be invalid. Instead, the day * would be changed to the closest value - the 28th/29th February as appropriate. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param value the value to set, in the units of the field * @return the updated milliseconds * @throws IllegalArgumentException if the value is invalid */ public abstract long set(long instant, int value); /** * Sets a value using the specified partial instant. *

* The value of this field (specified by the index) will be set. * If the value is invalid, an exception if thrown. *

* If setting this field would make other fields invalid, then those fields * may be changed. For example if the current date is the 31st January, and * the month is set to February, the day would be invalid. Instead, the day * would be changed to the closest value - the 28th/29th February as appropriate. * * @param partial the partial instant * @param fieldIndex the index of this field in the instant * @param values the values to update * @param newValue the value to set, in the units of the field * @return the updated values * @throws IllegalArgumentException if the value is invalid */ public int[] set(ReadablePartial partial, int fieldIndex, int[] values, int newValue) { FieldUtils.verifyValueBounds(this, newValue, getMinimumValue(partial, values), getMaximumValue(partial, values)); values[fieldIndex] = newValue; // may need to adjust smaller fields for (int i = fieldIndex + 1; i < partial.size(); i++) { DateTimeField field = partial.getField(i); if (values[i] > field.getMaximumValue(partial, values)) { values[i] = field.getMaximumValue(partial, values); } if (values[i] < field.getMinimumValue(partial, values)) { values[i] = field.getMinimumValue(partial, values); } } return values; } /** * Sets a value in the milliseconds supplied from a human-readable, text value. * If the specified locale is null, the default locale is used. *

* This implementation uses convertText(String, Locale) and * {@link #set(long, int)}. *

* Note: subclasses that override this method should also override * getAsText. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param text the text value to set * @param locale the locale to use for selecting a text symbol, null for default * @return the updated milliseconds * @throws IllegalArgumentException if the text value is invalid */ public long set(long instant, String text, Locale locale) { int value = convertText(text, locale); return set(instant, value); } /** * Sets a value in the milliseconds supplied from a human-readable, text value. *

* This implementation uses {@link #set(long, String, Locale)}. *

* Note: subclasses that override this method should also override getAsText. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param text the text value to set * @return the updated milliseconds * @throws IllegalArgumentException if the text value is invalid */ public final long set(long instant, String text) { return set(instant, text, null); } /** * Sets a value in the milliseconds supplied from a human-readable, text value. * If the specified locale is null, the default locale is used. *

* This implementation uses convertText(String, Locale) and * {@link #set(ReadablePartial, int, int[], int)}. * * @param instant the partial instant * @param fieldIndex the index of this field in the instant * @param values the values of the partial instant which should be updated * @param text the text value to set * @param locale the locale to use for selecting a text symbol, null for default * @return the passed in values * @throws IllegalArgumentException if the text value is invalid */ public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale) { int value = convertText(text, locale); return set(instant, fieldIndex, values, value); } /** * Convert the specified text and locale into a value. * * @param text the text to convert * @param locale the locale to convert using * @return the value extracted from the text * @throws IllegalArgumentException if the text is invalid */ protected int convertText(String text, Locale locale) { try { return Integer.parseInt(text); } catch (NumberFormatException ex) { throw new IllegalFieldValueException(getType(), text); } } // Extra information API //------------------------------------------------------------------------ /** * Returns the duration per unit value of this field. For example, if this * field represents "hour of day", then the unit duration is an hour. * * @return the duration of this field, or UnsupportedDurationField if field * has no duration */ public abstract DurationField getDurationField(); /** * Returns the range duration of this field. For example, if this field * represents "hour of day", then the range duration is a day. * * @return the range duration of this field, or null if field has no range */ public abstract DurationField getRangeDurationField(); /** * Returns whether this field is 'leap' for the specified instant. *

* For example, a leap year would return true, a non leap year would return * false. *

* This implementation returns false. * * @return true if the field is 'leap' */ public boolean isLeap(long instant) { return false; } /** * Gets the amount by which this field is 'leap' for the specified instant. *

* For example, a leap year would return one, a non leap year would return * zero. *

* This implementation returns zero. */ public int getLeapAmount(long instant) { return 0; } /** * If this field were to leap, then it would be in units described by the * returned duration. If this field doesn't ever leap, null is returned. *

* This implementation returns null. */ public DurationField getLeapDurationField() { return null; } /** * Get the minimum allowable value for this field. * * @return the minimum valid value for this field, in the units of the * field */ public abstract int getMinimumValue(); /** * Get the minimum value for this field evaluated at the specified time. *

* This implementation returns the same as {@link #getMinimumValue()}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the minimum value for this field, in the units of the field */ public int getMinimumValue(long instant) { return getMinimumValue(); } /** * Get the minimum value for this field evaluated at the specified instant. *

* This implementation returns the same as {@link #getMinimumValue()}. * * @param instant the partial instant to query * @return the minimum value for this field, in the units of the field */ public int getMinimumValue(ReadablePartial instant) { return getMinimumValue(); } /** * Get the minimum value for this field using the partial instant and * the specified values. *

* This implementation returns the same as {@link #getMinimumValue(ReadablePartial)}. * * @param instant the partial instant to query * @param values the values to use * @return the minimum value for this field, in the units of the field */ public int getMinimumValue(ReadablePartial instant, int[] values) { return getMinimumValue(instant); } /** * Get the maximum allowable value for this field. * * @return the maximum valid value for this field, in the units of the * field */ public abstract int getMaximumValue(); /** * Get the maximum value for this field evaluated at the specified time. *

* This implementation returns the same as {@link #getMaximumValue()}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the maximum value for this field, in the units of the field */ public int getMaximumValue(long instant) { return getMaximumValue(); } /** * Get the maximum value for this field evaluated at the specified instant. *

* This implementation returns the same as {@link #getMaximumValue()}. * * @param instant the partial instant to query * @return the maximum value for this field, in the units of the field */ public int getMaximumValue(ReadablePartial instant) { return getMaximumValue(); } /** * Get the maximum value for this field using the partial instant and * the specified values. *

* This implementation returns the same as {@link #getMaximumValue(ReadablePartial)}. * * @param instant the partial instant to query * @param values the values to use * @return the maximum value for this field, in the units of the field */ public int getMaximumValue(ReadablePartial instant, int[] values) { return getMaximumValue(instant); } /** * Get the maximum text value for this field. The default implementation * returns the equivalent of Integer.toString(getMaximumValue()).length(). * * @param locale the locale to use for selecting a text symbol * @return the maximum text length */ public int getMaximumTextLength(Locale locale) { int max = getMaximumValue(); if (max >= 0) { if (max < 10) { return 1; } else if (max < 100) { return 2; } else if (max < 1000) { return 3; } } return Integer.toString(max).length(); } /** * Get the maximum short text value for this field. The default * implementation returns getMaximumTextLength(). * * @param locale the locale to use for selecting a text symbol * @return the maximum short text length */ public int getMaximumShortTextLength(Locale locale) { return getMaximumTextLength(locale); } // Calculation API //------------------------------------------------------------------------ /** * Round to the lowest whole unit of this field. After rounding, the value * of this field and all fields of a higher magnitude are retained. The * fractional millis that cannot be expressed in whole increments of this * field are set to minimum. *

* For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * lowest whole hour is 2002-11-02T23:00:00.000. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundFloor(long instant); /** * Round to the highest whole unit of this field. The value of this field * and all fields of a higher magnitude may be incremented in order to * achieve this result. The fractional millis that cannot be expressed in * whole increments of this field are set to minimum. *

* For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * highest whole hour is 2002-11-03T00:00:00.000. *

* The default implementation calls roundFloor, and if the instant is * modified as a result, adds one field unit. Subclasses are encouraged to * provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundCeiling(long instant) { long newInstant = roundFloor(instant); if (newInstant != instant) { instant = add(newInstant, 1); } return instant; } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor or is exactly halfway, this function * behaves like roundFloor. If the millisecond value is closer to the * ceiling, this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfFloor(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor <= diffToCeiling) { // Closer to the floor, or halfway - round floor return floor; } else { return ceiling; } } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling or is exactly halfway, * this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfCeiling(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffToCeiling <= diffFromFloor) { // Closer to the ceiling, or halfway - round ceiling return ceiling; } else { return floor; } } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling, this function behaves * like roundCeiling. *

* If the millisecond value is exactly halfway between the floor and * ceiling, the ceiling is chosen over the floor only if it makes this * field's value even. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfEven(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor < diffToCeiling) { // Closer to the floor - round floor return floor; } else if (diffToCeiling < diffFromFloor) { // Closer to the ceiling - round ceiling return ceiling; } else { // Round to the instant that makes this field even. If both values // make this field even (unlikely), favor the ceiling. if ((get(ceiling) & 1) == 0) { return ceiling; } return floor; } } /** * Returns the fractional duration milliseconds of this field. In other * words, calling remainder returns the duration that roundFloor would * subtract. *

* For example, on a datetime of 2002-11-02T23:34:56.789, the remainder by * hour is 34 minutes and 56.789 seconds. *

* The default implementation computes * instant - roundFloor(instant). Subclasses are encouraged to * provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to get the * remainder * @return remainder duration, in milliseconds */ public long remainder(long instant) { return instant - roundFloor(instant); } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return "DateTimeField[" + getName() + ']'; } } joda-time-2.3/src/main/java/org/joda/time/field/package.html0000644000175000017500000000205311564251363023227 0ustar ebourgebourg org.joda.time.field package

Implementation package providing abstract and standard field classes.

Provides DateTimeField and DurationField implementations and support. Applications will only use this package directly if they want to write their own DateTimeField implementation.

joda-time-2.3/src/main/java/org/joda/time/field/PreciseDateTimeField.java0000644000175000017500000001212112203435150025546 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * Precise datetime field, composed of two precise duration fields. *

* This DateTimeField is useful for defining DateTimeFields that are composed * of precise durations, like time of day fields. If either duration field is * imprecise, then an {@link ImpreciseDateTimeField} may be used instead. *

* PreciseDateTimeField is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 * @see ImpreciseDateTimeField */ public class PreciseDateTimeField extends PreciseDurationDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = -5586801265774496376L; /** The maximum range in the correct units */ private final int iRange; private final DurationField iRangeField; /** * Constructor. * * @param type the field type this field uses * @param unit precise unit duration, like "seconds()". * @param range precise range duration, preferably a multiple of the unit, * like "minutes()". * @throws IllegalArgumentException if either duration field is imprecise * @throws IllegalArgumentException if unit milliseconds is less than one * or effective value range is less than two. */ public PreciseDateTimeField(DateTimeFieldType type, DurationField unit, DurationField range) { super(type, unit); if (!range.isPrecise()) { throw new IllegalArgumentException("Range duration field must be precise"); } long rangeMillis = range.getUnitMillis(); iRange = (int)(rangeMillis / getUnitMillis()); if (iRange < 2) { throw new IllegalArgumentException("The effective range must be at least 2"); } iRangeField = range; } /** * Get the amount of fractional units from the specified time instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the amount of fractional units extracted from the input. */ public int get(long instant) { if (instant >= 0) { return (int) ((instant / getUnitMillis()) % iRange); } else { return iRange - 1 + (int) (((instant + 1) / getUnitMillis()) % iRange); } } /** * Add to the component of the specified time instant, wrapping around * within that component if necessary. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param amount the amount of units to add (can be negative). * @return the updated time instant. */ public long addWrapField(long instant, int amount) { int thisValue = get(instant); int wrappedValue = FieldUtils.getWrappedValue (thisValue, amount, getMinimumValue(), getMaximumValue()); // copy code from set() to avoid repeat call to get() return instant + (wrappedValue - thisValue) * getUnitMillis(); } /** * Set the specified amount of units to the specified time instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param value value of units to set. * @return the updated time instant. * @throws IllegalArgumentException if value is too large or too small. */ public long set(long instant, int value) { FieldUtils.verifyValueBounds(this, value, getMinimumValue(), getMaximumValue()); return instant + (value - get(instant)) * iUnitMillis; } /** * Returns the range duration of this field. For example, if this field * represents "minute of hour", then the range duration field is an hours. * * @return the range duration of this field, or null if field has no range */ public DurationField getRangeDurationField() { return iRangeField; } /** * Get the maximum value for the field. * * @return the maximum value */ public int getMaximumValue() { return iRange - 1; } /** * Returns the range of the field in the field's units. *

* For example, 60 for seconds per minute. The field is allowed values * from 0 to range - 1. * * @return unit range */ public int getRange() { return iRange; } } joda-time-2.3/src/main/java/org/joda/time/field/PreciseDurationDateTimeField.java0000644000175000017500000001232312203435142027261 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.field; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; /** * Precise datetime field, which has a precise unit duration field. *

* PreciseDurationDateTimeField is thread-safe and immutable, and its * subclasses must be as well. * * @author Brian S O'Neill * @since 1.0 */ public abstract class PreciseDurationDateTimeField extends BaseDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 5004523158306266035L; /** The fractional unit in millis */ final long iUnitMillis; private final DurationField iUnitField; /** * Constructor. * * @param type the field type * @param unit precise unit duration, like "days()". * @throws IllegalArgumentException if duration field is imprecise * @throws IllegalArgumentException if unit milliseconds is less than one */ public PreciseDurationDateTimeField(DateTimeFieldType type, DurationField unit) { super(type); if (!unit.isPrecise()) { throw new IllegalArgumentException("Unit duration field must be precise"); } iUnitMillis = unit.getUnitMillis(); if (iUnitMillis < 1) { throw new IllegalArgumentException("The unit milliseconds must be at least 1"); } iUnitField = unit; } /** * Returns false by default. */ public boolean isLenient() { return false; } /** * Set the specified amount of units to the specified time instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param value value of units to set. * @return the updated time instant. * @throws IllegalArgumentException if value is too large or too small. */ public long set(long instant, int value) { FieldUtils.verifyValueBounds(this, value, getMinimumValue(), getMaximumValueForSet(instant, value)); return instant + (value - get(instant)) * iUnitMillis; } /** * This method assumes that this field is properly rounded on * 1970-01-01T00:00:00. If the rounding alignment differs, override this * method as follows: *

     * return super.roundFloor(instant + ALIGNMENT_MILLIS) - ALIGNMENT_MILLIS;
     * 
*/ public long roundFloor(long instant) { if (instant >= 0) { return instant - instant % iUnitMillis; } else { instant += 1; return instant - instant % iUnitMillis - iUnitMillis; } } /** * This method assumes that this field is properly rounded on * 1970-01-01T00:00:00. If the rounding alignment differs, override this * method as follows: *
     * return super.roundCeiling(instant + ALIGNMENT_MILLIS) - ALIGNMENT_MILLIS;
     * 
*/ public long roundCeiling(long instant) { if (instant > 0) { instant -= 1; return instant - instant % iUnitMillis + iUnitMillis; } else { return instant - instant % iUnitMillis; } } /** * This method assumes that this field is properly rounded on * 1970-01-01T00:00:00. If the rounding alignment differs, override this * method as follows: *
     * return super.remainder(instant + ALIGNMENT_MILLIS);
     * 
*/ public long remainder(long instant) { if (instant >= 0) { return instant % iUnitMillis; } else { return (instant + 1) % iUnitMillis + iUnitMillis - 1; } } /** * Returns the duration per unit value of this field. For example, if this * field represents "minute of hour", then the duration field is minutes. * * @return the duration of this field, or UnsupportedDurationField if field * has no duration */ public DurationField getDurationField() { return iUnitField; } /** * Get the minimum value for the field. * * @return the minimum value */ public int getMinimumValue() { return 0; } public final long getUnitMillis() { return iUnitMillis; } /** * Called by the set method to get the maximum allowed value. By default, * returns getMaximumValue(instant). Override to provide a faster * implementation. */ protected int getMaximumValueForSet(long instant, int value) { return getMaximumValue(instant); } } joda-time-2.3/src/main/java/org/joda/time/DurationField.java0000644000175000017500000003020711564251363023261 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines the calculation engine for duration fields. * The interface defines a set of methods that manipulate a millisecond duration * with regards to a single field, such as months or seconds. *

* This design is extensible so, if you wish, you can extract a different field from * the millisecond duration. A number of standard implementations are provided to assist. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public abstract class DurationField implements Comparable { /** * Get the type of the field. * * @return field type */ public abstract DurationFieldType getType(); /** * Get the name of the field. *

* By convention, names are plural. * * @return field name */ public abstract String getName(); /** * Returns true if this field is supported. * * @return true if this field is supported */ public abstract boolean isSupported(); /** * Is this field precise. A precise field can calculate its value from * milliseconds without needing a reference date. Put another way, a * precise field's unit size is not variable. * * @return true if precise * @see #getUnitMillis() */ public abstract boolean isPrecise(); /** * Returns the amount of milliseconds per unit value of this field. For * example, if this field represents "seconds", then this returns the * milliseconds in one second. *

* For imprecise fields, the unit size is variable, and so this method * returns a suitable average value. * * @return the unit size of this field, in milliseconds * @see #isPrecise() */ public abstract long getUnitMillis(); //------------------------------------------------------------------------ /** * Get the value of this field from the milliseconds, which is approximate * if this field is imprecise. * * @param duration the milliseconds to query, which may be negative * @return the value of the field, in the units of the field, which may be * negative * @throws ArithmeticException if the value is too large for an int */ public abstract int getValue(long duration); /** * Get the value of this field from the milliseconds, which is approximate * if this field is imprecise. * * @param duration the milliseconds to query, which may be negative * @return the value of the field, in the units of the field, which may be * negative */ public abstract long getValueAsLong(long duration); /** * Get the value of this field from the milliseconds relative to an * instant. For precise fields this method produces the same result as for * the single argument get method. *

* If the millisecond duration is positive, then the instant is treated as a * "start instant". If negative, the instant is treated as an "end instant". * * @param duration the milliseconds to query, which may be negative * @param instant the start instant to calculate relative to * @return the value of the field, in the units of the field, which may be * negative * @throws ArithmeticException if the value is too large for an int */ public abstract int getValue(long duration, long instant); /** * Get the value of this field from the milliseconds relative to an * instant. For precise fields this method produces the same result as for * the single argument get method. *

* If the millisecond duration is positive, then the instant is treated as a * "start instant". If negative, the instant is treated as an "end instant". * * @param duration the milliseconds to query, which may be negative * @param instant the start instant to calculate relative to * @return the value of the field, in the units of the field, which may be * negative */ public abstract long getValueAsLong(long duration, long instant); //------------------------------------------------------------------------ /** * Get the millisecond duration of this field from its value, which is * approximate if this field is imprecise. * * @param value the value of the field, which may be negative * @return the milliseconds that the field represents, which may be * negative */ public abstract long getMillis(int value); /** * Get the millisecond duration of this field from its value, which is * approximate if this field is imprecise. * * @param value the value of the field, which may be negative * @return the milliseconds that the field represents, which may be * negative */ public abstract long getMillis(long value); /** * Get the millisecond duration of this field from its value relative to an * instant. For precise fields this method produces the same result as for * the single argument getMillis method. *

* If the value is positive, then the instant is treated as a "start * instant". If negative, the instant is treated as an "end instant". * * @param value the value of the field, which may be negative * @param instant the instant to calculate relative to * @return the millisecond duration that the field represents, which may be * negative */ public abstract long getMillis(int value, long instant); /** * Get the millisecond duration of this field from its value relative to an * instant. For precise fields this method produces the same result as for * the single argument getMillis method. *

* If the value is positive, then the instant is treated as a "start * instant". If negative, the instant is treated as an "end instant". * * @param value the value of the field, which may be negative * @param instant the instant to calculate relative to * @return the millisecond duration that the field represents, which may be * negative */ public abstract long getMillis(long value, long instant); /** * Adds a duration value (which may be negative) to the instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public abstract long add(long instant, int value); /** * Adds a duration value (which may be negative) to the instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public abstract long add(long instant, long value); /** * Subtracts a duration value (which may be negative) from the instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to subtract from * @param value the value to subtract, in the units of the field * @return the updated milliseconds * @since 1.1 */ public long subtract(long instant, int value) { if (value == Integer.MIN_VALUE) { return subtract(instant, (long) value); } return add(instant, -value); } /** * Subtracts a duration value (which may be negative) from the instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to subtract from * @param value the value to subtract, in the units of the field * @return the updated milliseconds * @since 1.1 */ public long subtract(long instant, long value) { if (value == Long.MIN_VALUE) { throw new ArithmeticException("Long.MIN_VALUE cannot be negated"); } return add(instant, -value); } /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *

     * long instant = ...
     * int v = ...
     * int age = getDifference(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public abstract int getDifference(long minuendInstant, long subtrahendInstant); /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *
     * long instant = ...
     * long v = ...
     * long age = getDifferenceAsLong(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public abstract long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); // Adding this definition would be backwards incompatible with earlier subclasses // This definition of compareTo was present in previous versions, and still applies // /** // * Compares this duration field with another duration field for ascending // * unit millisecond order. This ordering is inconsistent with equals, as it // * ignores name and precision. // * // * @param durationField a duration field to check against // * @return negative value if this is less, 0 if equal, or positive value if greater // * @throws NullPointerException if the object is null // * @throws ClassCastException if the object type is not supported // */ // public abstract int compareTo(DurationField durationField); /** * Returns a localized unit name of this field, using the given value as an * aid. For example, the unit name may differ if it is plural. * * @param value the duration value to use for selecting a unit name * @param locale the locale to use for selecting a name, null for default */ //String getUnitName(long value, Locale locale); /** * Returns a localized unit name of this field, using the given value as an * aid. For example, the unit name may differ if it is plural. * * @param value the duration value to use for selecting a unit name */ //String getUnitName(long value); /** * Get the maximum length string returned by getUnitName. * * @param locale the locale to use for selecting a unit name, null for * default * @return the maximum name length */ //int getMaximumUnitNameLength(Locale locale); //------------------------------------------------------------------------ /** * Get a suitable debug string. * * @return debug string */ public abstract String toString(); } joda-time-2.3/src/main/java/org/joda/time/Years.java0000644000175000017500000003233512075476522021623 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseSingleFieldPeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period representing a number of years. *

* Years is an immutable period that can only store years. * It does not store months, days or hours for example. As such it is a * type-safe way of representing a number of years in an application. *

* The number of years is set in the constructor, and may be queried using * getYears(). Basic mathematical operations are provided - * plus(), minus(), multipliedBy() and * dividedBy(). *

* Years is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.4 */ public final class Years extends BaseSingleFieldPeriod { /** Constant representing zero years. */ public static final Years ZERO = new Years(0); /** Constant representing one year. */ public static final Years ONE = new Years(1); /** Constant representing two years. */ public static final Years TWO = new Years(2); /** Constant representing three years. */ public static final Years THREE = new Years(3); /** Constant representing the maximum number of years that can be stored in this object. */ public static final Years MAX_VALUE = new Years(Integer.MAX_VALUE); /** Constant representing the minimum number of years that can be stored in this object. */ public static final Years MIN_VALUE = new Years(Integer.MIN_VALUE); /** The paser to use for this class. */ private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.years()); /** Serialization version. */ private static final long serialVersionUID = 87525275727380868L; //----------------------------------------------------------------------- /** * Obtains an instance of Years that may be cached. * Years is immutable, so instances can be cached and shared. * This factory method provides access to shared instances. * * @param years the number of years to obtain an instance for * @return the instance of Years */ public static Years years(int years) { switch (years) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Years(years); } } //----------------------------------------------------------------------- /** * Creates a Years representing the number of whole years * between the two specified datetimes. This method corectly handles * any daylight savings time changes that may occur during the interval. * * @param start the start instant, must not be null * @param end the end instant, must not be null * @return the period in years * @throws IllegalArgumentException if the instants are null or invalid */ public static Years yearsBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.years()); return Years.years(amount); } /** * Creates a Years representing the number of whole years * between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalDate objects. * * @param start the start partial date, must not be null * @param end the end partial date, must not be null * @return the period in years * @throws IllegalArgumentException if the partials are null or invalid */ public static Years yearsBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalDate && end instanceof LocalDate) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int years = chrono.years().getDifference( ((LocalDate) end).getLocalMillis(), ((LocalDate) start).getLocalMillis()); return Years.years(years); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Years.years(amount); } /** * Creates a Years representing the number of whole years * in the specified interval. This method corectly handles any daylight * savings time changes that may occur during the interval. * * @param interval the interval to extract years from, null returns zero * @return the period in years * @throws IllegalArgumentException if the partials are null or invalid */ public static Years yearsIn(ReadableInterval interval) { if (interval == null) { return Years.ZERO; } int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.years()); return Years.years(amount); } /** * Creates a new Years by parsing a string in the ISO8601 format 'PnY'. *

* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the * years component may be non-zero. If any other component is non-zero, an exception * will be thrown. * * @param periodStr the period string, null returns zero * @return the period in years * @throws IllegalArgumentException if the string format is invalid */ @FromString public static Years parseYears(String periodStr) { if (periodStr == null) { return Years.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Years.years(p.getYears()); } //----------------------------------------------------------------------- /** * Creates a new instance representing a number of years. * You should consider using the factory method {@link #years(int)} * instead of the constructor. * * @param years the number of years to represent */ private Years(int years) { super(years); } /** * Resolves singletons. * * @return the singleton instance */ private Object readResolve() { return Years.years(getValue()); } //----------------------------------------------------------------------- /** * Gets the duration field type, which is years. * * @return the period type */ public DurationFieldType getFieldType() { return DurationFieldType.years(); } /** * Gets the period type, which is years. * * @return the period type */ public PeriodType getPeriodType() { return PeriodType.years(); } //----------------------------------------------------------------------- /** * Gets the number of years that this period represents. * * @return the number of years in the period */ public int getYears() { return getValue(); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of years added. *

* This instance is immutable and unaffected by this method call. * * @param years the amount of years to add, may be negative * @return the new period plus the specified number of years * @throws ArithmeticException if the result overflows an int */ public Years plus(int years) { if (years == 0) { return this; } return Years.years(FieldUtils.safeAdd(getValue(), years)); } /** * Returns a new instance with the specified number of years added. *

* This instance is immutable and unaffected by this method call. * * @param years the amount of years to add, may be negative, null means zero * @return the new period plus the specified number of years * @throws ArithmeticException if the result overflows an int */ public Years plus(Years years) { if (years == null) { return this; } return plus(years.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of years taken away. *

* This instance is immutable and unaffected by this method call. * * @param years the amount of years to take away, may be negative * @return the new period minus the specified number of years * @throws ArithmeticException if the result overflows an int */ public Years minus(int years) { return plus(FieldUtils.safeNegate(years)); } /** * Returns a new instance with the specified number of years taken away. *

* This instance is immutable and unaffected by this method call. * * @param years the amount of years to take away, may be negative, null means zero * @return the new period minus the specified number of years * @throws ArithmeticException if the result overflows an int */ public Years minus(Years years) { if (years == null) { return this; } return minus(years.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the years multiplied by the specified scalar. *

* This instance is immutable and unaffected by this method call. * * @param scalar the amount to multiply by, may be negative * @return the new period multiplied by the specified scalar * @throws ArithmeticException if the result overflows an int */ public Years multipliedBy(int scalar) { return Years.years(FieldUtils.safeMultiply(getValue(), scalar)); } /** * Returns a new instance with the years divided by the specified divisor. * The calculation uses integer division, thus 3 divided by 2 is 1. *

* This instance is immutable and unaffected by this method call. * * @param divisor the amount to divide by, may be negative * @return the new period divided by the specified divisor * @throws ArithmeticException if the divisor is zero */ public Years dividedBy(int divisor) { if (divisor == 1) { return this; } return Years.years(getValue() / divisor); } //----------------------------------------------------------------------- /** * Returns a new instance with the years value negated. * * @return the new period with a negated value * @throws ArithmeticException if the result overflows an int */ public Years negated() { return Years.years(FieldUtils.safeNegate(getValue())); } //----------------------------------------------------------------------- /** * Is this years instance greater than the specified number of years. * * @param other the other period, null means zero * @return true if this years instance is greater than the specified one */ public boolean isGreaterThan(Years other) { if (other == null) { return getValue() > 0; } return getValue() > other.getValue(); } /** * Is this years instance less than the specified number of years. * * @param other the other period, null means zero * @return true if this years instance is less than the specified one */ public boolean isLessThan(Years other) { if (other == null) { return getValue() < 0; } return getValue() < other.getValue(); } //----------------------------------------------------------------------- /** * Gets this instance as a String in the ISO8601 duration format. *

* For example, "P4Y" represents 4 years. * * @return the value as an ISO8601 string */ @ToString public String toString() { return "P" + String.valueOf(getValue()) + "Y"; } } joda-time-2.3/src/main/java/org/joda/time/ReadWritableDateTime.java0000644000175000017500000002115411564251363024513 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines an instant in time that can be queried and modified using datetime fields. *

* The implementation of this interface will be mutable. * It may provide more advanced methods than those in the interface. *

* Methods in your application should be defined using ReadWritableDateTime * as a parameter if the method wants to manipulate and change a date in simple ways. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public interface ReadWritableDateTime extends ReadableDateTime, ReadWritableInstant { //----------------------------------------------------------------------- /** * Set the year to the specified value. * * @param year the year * @throws IllegalArgumentException if the value is invalid */ void setYear(int year); /** * Add a number of years to the date. * * @param years the years to add * @throws IllegalArgumentException if the value is invalid */ void addYears(int years); //----------------------------------------------------------------------- /** * Set the weekyear to the specified value. * * @param weekyear the weekyear * @throws IllegalArgumentException if the value is invalid */ void setWeekyear(int weekyear); /** * Add a number of weekyears to the date. * * @param weekyears the weekyears to add * @throws IllegalArgumentException if the value is invalid */ void addWeekyears(int weekyears); //----------------------------------------------------------------------- /** * Set the month of the year to the specified value. * * @param monthOfYear the month of the year * @throws IllegalArgumentException if the value is invalid */ void setMonthOfYear(int monthOfYear); /** * Add a number of months to the date. * * @param months the months to add * @throws IllegalArgumentException if the value is invalid */ void addMonths(int months); //----------------------------------------------------------------------- /** * Set the week of weekyear to the specified value. * * @param weekOfWeekyear the week of the weekyear * @throws IllegalArgumentException if the value is invalid */ void setWeekOfWeekyear(int weekOfWeekyear); /** * Add a number of weeks to the date. * * @param weeks the weeks to add * @throws IllegalArgumentException if the value is invalid */ void addWeeks(int weeks); //----------------------------------------------------------------------- /** * Set the day of year to the specified value. * * @param dayOfYear the day of the year * @throws IllegalArgumentException if the value is invalid */ void setDayOfYear(int dayOfYear); /** * Set the day of the month to the specified value. * * @param dayOfMonth the day of the month * @throws IllegalArgumentException if the value is invalid */ void setDayOfMonth(int dayOfMonth); /** * Set the day of week to the specified value. * * @param dayOfWeek the day of the week * @throws IllegalArgumentException if the value is invalid */ void setDayOfWeek(int dayOfWeek); /** * Add a number of days to the date. * * @param days the days to add * @throws IllegalArgumentException if the value is invalid */ void addDays(int days); //----------------------------------------------------------------------- /** * Set the hour of the day to the specified value. * * @param hourOfDay the hour of day * @throws IllegalArgumentException if the value is invalid */ void setHourOfDay(int hourOfDay); /** * Add a number of hours to the date. * * @param hours the hours to add * @throws IllegalArgumentException if the value is invalid */ void addHours(int hours); //----------------------------------------------------------------------- /** * Set the minute of the day to the specified value. * * @param minuteOfDay the minute of day * @throws IllegalArgumentException if the value is invalid */ void setMinuteOfDay(int minuteOfDay); /** * Set the minute of the hour to the specified value. * * @param minuteOfHour the minute of hour * @throws IllegalArgumentException if the value is invalid */ void setMinuteOfHour(int minuteOfHour); /** * Add a number of minutes to the date. * * @param minutes the minutes to add * @throws IllegalArgumentException if the value is invalid */ void addMinutes(int minutes); //----------------------------------------------------------------------- /** * Set the second of the day to the specified value. * * @param secondOfDay the second of day * @throws IllegalArgumentException if the value is invalid */ void setSecondOfDay(int secondOfDay); /** * Set the second of the minute to the specified value. * * @param secondOfMinute the second of minute * @throws IllegalArgumentException if the value is invalid */ void setSecondOfMinute(int secondOfMinute); /** * Add a number of seconds to the date. * * @param seconds the seconds to add * @throws IllegalArgumentException if the value is invalid */ void addSeconds(int seconds); //----------------------------------------------------------------------- /** * Set the millis of the day to the specified value. * * @param millisOfDay the millis of day * @throws IllegalArgumentException if the value is invalid */ void setMillisOfDay(int millisOfDay); /** * Set the millis of the second to the specified value. * * @param millisOfSecond the millis of second * @throws IllegalArgumentException if the value is invalid */ void setMillisOfSecond(int millisOfSecond); /** * Add a number of milliseconds to the date. The implementation of this * method differs from the {@link #add(long)} method in that a * DateTimeField performs the addition. * * @param millis the milliseconds to add * @throws IllegalArgumentException if the value is invalid */ void addMillis(int millis); /** * Set the date from fields. * The time part of this object will be unaffected. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @throws IllegalArgumentException if any value is invalid */ void setDate(int year, int monthOfYear, int dayOfMonth); /** * Set the time from fields. * The date part of this object will be unaffected. * * @param hour the hour * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @throws IllegalArgumentException if any value is invalid */ void setTime(int hour, int minuteOfHour, int secondOfMinute, int millisOfSecond); /** * Set the date and time from fields. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @throws IllegalArgumentException if any value is invalid */ void setDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond); } joda-time-2.3/src/main/java/org/joda/time/overview.html0000644000175000017500000000264511564251363022426 0ustar ebourgebourg org.joda.time package

Joda-Time is a library designed as a complete alternative to the JDK date and time classes. It includes date, duration, time period and interval classes and has a pluggable API for various calendar systems.

The library consists of quite a large number of classes, however most are internal to the implementation. All the key interfaces and classes are in the main package while the format package will be of interest for formatting.

Joda-Time is standalone and has no dependencies other than JDK 1.5. (The jar file may work on older JDK versions, but it is untested.) It is licensed under the Apache License Version 2.0.

joda-time-2.3/src/main/java/org/joda/time/Partial.java0000644000175000017500000011567211763631014022132 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.joda.time.base.AbstractPartial; import org.joda.time.field.AbstractPartialFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Partial is an immutable partial datetime supporting any set of datetime fields. *

* A Partial instance can be used to hold any combination of fields. * The instance does not contain a time zone, so any datetime is local. *

* A Partial can be matched against an instant using {@link #isMatch(ReadableInstant)}. * This method compares each field on this partial with those of the instant * and determines if the partial matches the instant. * Given this definition, an empty Partial instance represents any datetime * and always matches. *

* Calculations on Partial are performed using a {@link Chronology}. * This chronology is set to be in the UTC time zone for all calculations. *

* Each individual field can be queried in two ways: *

    *
  • get(DateTimeFieldType.monthOfYear()) *
  • property(DateTimeFieldType.monthOfYear()).get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value - monthOfYear().get() *
  • text value - monthOfYear().getAsText() *
  • short text value - monthOfYear().getAsShortText() *
  • maximum/minimum values - monthOfYear().getMaximumValue() *
  • add/subtract - monthOfYear().addToCopy() *
  • set - monthOfYear().setCopy() *
*

* Partial is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @since 1.1 */ public final class Partial extends AbstractPartial implements ReadablePartial, Serializable { /** Serialization version */ private static final long serialVersionUID = 12324121189002L; /** The chronology in use. */ private final Chronology iChronology; /** The set of field types. */ private final DateTimeFieldType[] iTypes; /** The values of each field in this partial. */ private final int[] iValues; /** The formatter to use, [0] may miss some fields, [1] doesn't miss any fields. */ private transient DateTimeFormatter[] iFormatter; // Constructors //----------------------------------------------------------------------- /** * Constructs a Partial with no fields or values, which can be considered * to represent any date. *

* This is most useful when constructing partials, for example: *

     * Partial p = new Partial()
     *     .with(DateTimeFieldType.dayOfWeek(), 5)
     *     .with(DateTimeFieldType.hourOfDay(), 12)
     *     .with(DateTimeFieldType.minuteOfHour(), 20);
     * 
* Note that, although this is a clean way to write code, it is fairly * inefficient internally. *

* The constructor uses the default ISO chronology. */ public Partial() { this((Chronology) null); } /** * Constructs a Partial with no fields or values, which can be considered * to represent any date. *

* This is most useful when constructing partials, for example: *

     * Partial p = new Partial(chrono)
     *     .with(DateTimeFieldType.dayOfWeek(), 5)
     *     .with(DateTimeFieldType.hourOfDay(), 12)
     *     .with(DateTimeFieldType.minuteOfHour(), 20);
     * 
* Note that, although this is a clean way to write code, it is fairly * inefficient internally. * * @param chrono the chronology, null means ISO */ public Partial(Chronology chrono) { super(); iChronology = DateTimeUtils.getChronology(chrono).withUTC(); iTypes = new DateTimeFieldType[0]; iValues = new int[0]; } /** * Constructs a Partial with the specified field and value. *

* The constructor uses the default ISO chronology. * * @param type the single type to create the partial from, not null * @param value the value to store * @throws IllegalArgumentException if the type or value is invalid */ public Partial(DateTimeFieldType type, int value) { this(type, value, null); } /** * Constructs a Partial with the specified field and value. *

* The constructor uses the specified chronology. * * @param type the single type to create the partial from, not null * @param value the value to store * @param chronology the chronology, null means ISO * @throws IllegalArgumentException if the type or value is invalid */ public Partial(DateTimeFieldType type, int value, Chronology chronology) { super(); chronology = DateTimeUtils.getChronology(chronology).withUTC(); iChronology = chronology; if (type == null) { throw new IllegalArgumentException("The field type must not be null"); } iTypes = new DateTimeFieldType[] {type}; iValues = new int[] {value}; chronology.validate(this, iValues); } /** * Constructs a Partial with the specified fields and values. * The fields must be specified in the order largest to smallest. *

* The constructor uses the specified chronology. * * @param types the types to create the partial from, not null * @param values the values to store, not null * @throws IllegalArgumentException if the types or values are invalid */ public Partial(DateTimeFieldType[] types, int[] values) { this(types, values, null); } /** * Constructs a Partial with the specified fields and values. * The fields must be specified in the order largest to smallest. *

* The constructor uses the specified chronology. * * @param types the types to create the partial from, not null * @param values the values to store, not null * @param chronology the chronology, null means ISO * @throws IllegalArgumentException if the types or values are invalid */ public Partial(DateTimeFieldType[] types, int[] values, Chronology chronology) { super(); chronology = DateTimeUtils.getChronology(chronology).withUTC(); iChronology = chronology; if (types == null) { throw new IllegalArgumentException("Types array must not be null"); } if (values == null) { throw new IllegalArgumentException("Values array must not be null"); } if (values.length != types.length) { throw new IllegalArgumentException("Values array must be the same length as the types array"); } if (types.length == 0) { iTypes = types; iValues = values; return; } for (int i = 0; i < types.length; i++) { if (types[i] == null) { throw new IllegalArgumentException("Types array must not contain null: index " + i); } } DurationField lastUnitField = null; for (int i = 0; i < types.length; i++) { DateTimeFieldType loopType = types[i]; DurationField loopUnitField = loopType.getDurationType().getField(iChronology); if (i > 0) { int compare = lastUnitField.compareTo(loopUnitField); if (compare < 0 || (compare != 0 && loopUnitField.isSupported() == false)) { throw new IllegalArgumentException("Types array must be in order largest-smallest: " + types[i - 1].getName() + " < " + loopType.getName()); } else if (compare == 0) { if (types[i - 1].getRangeDurationType() == null) { if (loopType.getRangeDurationType() == null) { throw new IllegalArgumentException("Types array must not contain duplicate: " + loopType.getName()); } } else { if (loopType.getRangeDurationType() == null) { throw new IllegalArgumentException("Types array must be in order largest-smallest: " + types[i - 1].getName() + " < " + loopType.getName()); } DurationField lastRangeField = types[i - 1].getRangeDurationType().getField(iChronology); DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); if (lastRangeField.compareTo(loopRangeField) < 0) { throw new IllegalArgumentException("Types array must be in order largest-smallest: " + types[i - 1].getName() + " < " + loopType.getName()); } if (lastRangeField.compareTo(loopRangeField) == 0) { throw new IllegalArgumentException("Types array must not contain duplicate: " + loopType.getName()); } } } } lastUnitField = loopUnitField; } iTypes = (DateTimeFieldType[]) types.clone(); chronology.validate(this, values); iValues = (int[]) values.clone(); } /** * Constructs a Partial by copying all the fields and types from * another partial. *

* This is most useful when copying from a YearMonthDay or TimeOfDay. */ public Partial(ReadablePartial partial) { super(); if (partial == null) { throw new IllegalArgumentException("The partial must not be null"); } iChronology = DateTimeUtils.getChronology(partial.getChronology()).withUTC(); iTypes = new DateTimeFieldType[partial.size()]; iValues = new int[partial.size()]; for (int i = 0; i < partial.size(); i++) { iTypes[i] = partial.getFieldType(i); iValues[i] = partial.getValue(i); } } /** * Constructs a Partial with the specified values. * This constructor assigns and performs no validation. * * @param partial the partial to copy * @param values the values to store * @throws IllegalArgumentException if the types or values are invalid */ Partial(Partial partial, int[] values) { super(); iChronology = partial.iChronology; iTypes = partial.iTypes; iValues = values; } /** * Constructs a Partial with the specified chronology, fields and values. * This constructor assigns and performs no validation. * * @param chronology the chronology * @param types the types to create the partial from * @param values the values to store * @throws IllegalArgumentException if the types or values are invalid */ Partial(Chronology chronology, DateTimeFieldType[] types, int[] values) { super(); iChronology = chronology; iTypes = types; iValues = values; } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial. * * @return the field count */ public int size() { return iTypes.length; } /** * Gets the chronology of the partial which is never null. *

* The {@link Chronology} is the calculation engine behind the partial and * provides conversion and validation of the fields in a particular calendar system. * * @return the chronology, never null */ public Chronology getChronology() { return iChronology; } /** * Gets the field for a specific index in the chronology specified. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field * @throws IndexOutOfBoundsException if the index is invalid */ protected DateTimeField getField(int index, Chronology chrono) { return iTypes[index].getField(chrono); } /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public DateTimeFieldType getFieldType(int index) { return iTypes[index]; } /** * Gets an array of the field type of each of the fields that * this partial supports. *

* The fields are returned largest to smallest. * * @return the array of field types (cloned), largest to smallest */ public DateTimeFieldType[] getFieldTypes() { return (DateTimeFieldType[]) iTypes.clone(); } //----------------------------------------------------------------------- /** * Gets the value of the field at the specifed index. * * @param index the index * @return the value * @throws IndexOutOfBoundsException if the index is invalid */ public int getValue(int index) { return iValues[index]; } /** * Gets an array of the value of each of the fields that * this partial supports. *

* The fields are returned largest to smallest. * Each value corresponds to the same array index as getFieldTypes() * * @return the current values of each field (cloned), largest to smallest */ public int[] getValues() { return (int[]) iValues.clone(); } //----------------------------------------------------------------------- /** * Creates a new Partial instance with the specified chronology. * This instance is immutable and unaffected by this method call. *

* This method retains the values of the fields, thus the result will * typically refer to a different instant. *

* The time zone of the specified chronology is ignored, as Partial * operates without a time zone. * * @param newChronology the new chronology, null means ISO * @return a copy of this datetime with a different chronology * @throws IllegalArgumentException if the values are invalid for the new chronology */ public Partial withChronologyRetainFields(Chronology newChronology) { newChronology = DateTimeUtils.getChronology(newChronology); newChronology = newChronology.withUTC(); if (newChronology == getChronology()) { return this; } else { Partial newPartial = new Partial(newChronology, iTypes, iValues); newChronology.validate(newPartial, iValues); return newPartial; } } //----------------------------------------------------------------------- /** * Gets a copy of this date with the specified field set to a new value. *

* If this partial did not previously support the field, the new one will. * Contrast this behaviour with {@link #withField(DateTimeFieldType, int)}. *

* For example, if the field type is dayOfMonth then the day * would be changed/added in the returned instance. * * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this instance with the field set * @throws IllegalArgumentException if the value is null or invalid */ public Partial with(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("The field type must not be null"); } int index = indexOf(fieldType); if (index == -1) { DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1]; int[] newValues = new int[newTypes.length]; // find correct insertion point to keep largest-smallest order int i = 0; DurationField unitField = fieldType.getDurationType().getField(iChronology); if (unitField.isSupported()) { for (; i < iTypes.length; i++) { DateTimeFieldType loopType = iTypes[i]; DurationField loopUnitField = loopType.getDurationType().getField(iChronology); if (loopUnitField.isSupported()) { int compare = unitField.compareTo(loopUnitField); if (compare > 0) { break; } else if (compare == 0) { DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology); DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); if (rangeField.compareTo(loopRangeField) > 0) { break; } } } } } System.arraycopy(iTypes, 0, newTypes, 0, i); System.arraycopy(iValues, 0, newValues, 0, i); newTypes[i] = fieldType; newValues[i] = value; System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1); System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1); Partial newPartial = new Partial(iChronology, newTypes, newValues); iChronology.validate(newPartial, newValues); return newPartial; } if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new Partial(this, newValues); } /** * Gets a copy of this date with the specified field removed. *

* If this partial did not previously support the field, no error occurs. * * @param fieldType the field type to remove, may be null * @return a copy of this instance with the field removed */ public Partial without(DateTimeFieldType fieldType) { int index = indexOf(fieldType); if (index != -1) { DateTimeFieldType[] newTypes = new DateTimeFieldType[size() - 1]; int[] newValues = new int[size() - 1]; System.arraycopy(iTypes, 0, newTypes, 0, index); System.arraycopy(iTypes, index + 1, newTypes, index, newTypes.length - index); System.arraycopy(iValues, 0, newValues, 0, index); System.arraycopy(iValues, index + 1, newValues, index, newValues.length - index); Partial newPartial = new Partial(iChronology, newTypes, newValues); iChronology.validate(newPartial, newValues); return newPartial; } return this; } //----------------------------------------------------------------------- /** * Gets a copy of this Partial with the specified field set to a new value. *

* If this partial does not support the field, an exception is thrown. * Contrast this behaviour with {@link #with(DateTimeFieldType, int)}. *

* For example, if the field type is dayOfMonth then the day * would be changed in the returned instance if supported. * * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this instance with the field set * @throws IllegalArgumentException if the value is null or invalid */ public Partial withField(DateTimeFieldType fieldType, int value) { int index = indexOfSupported(fieldType); if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new Partial(this, newValues); } /** * Gets a copy of this Partial with the value of the specified field increased. * If this partial does not support the field, an exception is thrown. *

* If the addition is zero, then this is returned. * The addition will overflow into larger fields (eg. minute to hour). * However, it will not wrap around if the top maximum is reached. * * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this instance with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new datetime exceeds the capacity */ public Partial withFieldAdded(DurationFieldType fieldType, int amount) { int index = indexOfSupported(fieldType); if (amount == 0) { return this; } int[] newValues = getValues(); newValues = getField(index).add(this, index, newValues, amount); return new Partial(this, newValues); } /** * Gets a copy of this Partial with the value of the specified field increased. * If this partial does not support the field, an exception is thrown. *

* If the addition is zero, then this is returned. * The addition will overflow into larger fields (eg. minute to hour). * If the maximum is reached, the addition will wra. * * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this instance with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new datetime exceeds the capacity */ public Partial withFieldAddWrapped(DurationFieldType fieldType, int amount) { int index = indexOfSupported(fieldType); if (amount == 0) { return this; } int[] newValues = getValues(); newValues = getField(index).addWrapPartial(this, index, newValues, amount); return new Partial(this, newValues); } /** * Gets a copy of this Partial with the specified period added. *

* If the addition is zero, then this is returned. * Fields in the period that aren't present in the partial are ignored. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using the method * {@link #withFieldAdded(DurationFieldType, int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this instance with the period added * @throws ArithmeticException if the new datetime exceeds the capacity */ public Partial withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } int[] newValues = getValues(); for (int i = 0; i < period.size(); i++) { DurationFieldType fieldType = period.getFieldType(i); int index = indexOf(fieldType); if (index >= 0) { newValues = getField(index).add(this, index, newValues, FieldUtils.safeMultiply(period.getValue(i), scalar)); } } return new Partial(this, newValues); } /** * Gets a copy of this instance with the specified period added. *

* If the amount is zero or null, then this is returned. * * @param period the duration to add to this one, null means zero * @return a copy of this instance with the period added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public Partial plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } /** * Gets a copy of this instance with the specified period take away. *

* If the amount is zero or null, then this is returned. * * @param period the period to reduce this instant by * @return a copy of this instance with the period taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public Partial minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains * many useful methods for getting and manipulating the partial. *

* See also {@link ReadablePartial#get(DateTimeFieldType)}. * * @param type the field type to get the property for, not null * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType type) { return new Property(this, indexOfSupported(type)); } //----------------------------------------------------------------------- /** * Does this partial match the specified instant. *

* A match occurs when all the fields of this partial are the same as the * corresponding fields on the specified instant. * * @param instant an instant to check against, null means now in default zone * @return true if this partial matches the specified instant */ public boolean isMatch(ReadableInstant instant) { long millis = DateTimeUtils.getInstantMillis(instant); Chronology chrono = DateTimeUtils.getInstantChronology(instant); for (int i = 0; i < iTypes.length; i++) { int value = iTypes[i].getField(chrono).get(millis); if (value != iValues[i]) { return false; } } return true; } /** * Does this partial match the specified partial. *

* A match occurs when all the fields of this partial are the same as the * corresponding fields on the specified partial. * * @param partial a partial to check against, must not be null * @return true if this partial matches the specified partial * @throws IllegalArgumentException if the partial is null * @throws IllegalArgumentException if the fields of the two partials do not match * @since 1.5 */ public boolean isMatch(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("The partial must not be null"); } for (int i = 0; i < iTypes.length; i++) { int value = partial.get(iTypes[i]); if (value != iValues[i]) { return false; } } return true; } //----------------------------------------------------------------------- /** * Gets a formatter suitable for the fields in this partial. *

* If there is no appropriate ISO format, null is returned. * This method may return a formatter that does not display all the * fields of the partial. This might occur when you have overlapping * fields, such as dayOfWeek and dayOfMonth. * * @return a formatter suitable for the fields in this partial, null * if none is suitable */ public DateTimeFormatter getFormatter() { DateTimeFormatter[] f = iFormatter; if (f == null) { if (size() == 0) { return null; } f = new DateTimeFormatter[2]; try { List list = new ArrayList(Arrays.asList(iTypes)); f[0] = ISODateTimeFormat.forFields(list, true, false); if (list.size() == 0) { f[1] = f[0]; } } catch (IllegalArgumentException ex) { // ignore } iFormatter = f; } return f[0]; } //----------------------------------------------------------------------- /** * Output the date in an appropriate ISO8601 format. *

* This method will output the partial in one of two ways. * If {@link #getFormatter()} *

* If there is no appropriate ISO format a dump of the fields is output * via {@link #toStringList()}. * * @return ISO8601 formatted string */ public String toString() { DateTimeFormatter[] f = iFormatter; if (f == null) { getFormatter(); f = iFormatter; if (f == null) { return toStringList(); } } DateTimeFormatter f1 = f[1]; if (f1 == null) { return toStringList(); } return f1.print(this); } /** * Gets a string version of the partial that lists all the fields. *

* This method exists to provide a better debugging toString than * the standard toString. This method lists all the fields and their * values in a style similar to the collections framework. * * @return a toString format that lists all the fields */ public String toStringList() { int size = size(); StringBuilder buf = new StringBuilder(20 * size); buf.append('['); for (int i = 0; i < size; i++) { if (i > 0) { buf.append(',').append(' '); } buf.append(iTypes[i].getName()); buf.append('='); buf.append(iValues[i]); } buf.append(']'); return buf.toString(); } /** * Output the date using the specified format pattern. * Unsupported fields will appear as special unicode characters. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the date using the specified format pattern. * Unsupported fields will appear as special unicode characters. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } //----------------------------------------------------------------------- /** * The property class for Partial. *

* This class binds a Partial to a DateTimeField. * * @author Stephen Colebourne * @since 1.1 */ public static class Property extends AbstractPartialFieldProperty implements Serializable { /** Serialization version */ private static final long serialVersionUID = 53278362873888L; /** The partial */ private final Partial iPartial; /** The field index */ private final int iFieldIndex; /** * Constructs a property. * * @param partial the partial instance * @param fieldIndex the index in the partial */ Property(Partial partial, int fieldIndex) { super(); iPartial = partial; iFieldIndex = fieldIndex; } /** * Gets the field that this property uses. * * @return the field */ public DateTimeField getField() { return iPartial.getField(iFieldIndex); } /** * Gets the partial that this property belongs to. * * @return the partial */ protected ReadablePartial getReadablePartial() { return iPartial; } /** * Gets the partial that this property belongs to. * * @return the partial */ public Partial getPartial() { return iPartial; } /** * Gets the value of this field. * * @return the field value */ public int get() { return iPartial.getValue(iFieldIndex); } //----------------------------------------------------------------------- /** * Adds to the value of this field in a copy of this Partial. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it will affect larger fields. * Smaller fields are unaffected. *

* If the result would be too large, beyond the maximum year, then an * IllegalArgumentException is thrown. *

* The Partial attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the Partial with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public Partial addToCopy(int valueToAdd) { int[] newValues = iPartial.getValues(); newValues = getField().add(iPartial, iFieldIndex, newValues, valueToAdd); return new Partial(iPartial, newValues); } /** * Adds to the value of this field in a copy of this Partial wrapping * within this field if the maximum value is reached. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps within this field. * Other fields are unaffected. *

* For example, * 2004-12-20 addWrapField one month returns 2004-01-20. *

* The Partial attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the Partial with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public Partial addWrapFieldToCopy(int valueToAdd) { int[] newValues = iPartial.getValues(); newValues = getField().addWrapField(iPartial, iFieldIndex, newValues, valueToAdd); return new Partial(iPartial, newValues); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the Partial. *

* The Partial attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param value the value to set the field in the copy to * @return a copy of the Partial with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public Partial setCopy(int value) { int[] newValues = iPartial.getValues(); newValues = getField().set(iPartial, iFieldIndex, newValues, value); return new Partial(iPartial, newValues); } /** * Sets this field in a copy of the Partial to a parsed text value. *

* The Partial attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the Partial with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public Partial setCopy(String text, Locale locale) { int[] newValues = iPartial.getValues(); newValues = getField().set(iPartial, iFieldIndex, newValues, text, locale); return new Partial(iPartial, newValues); } /** * Sets this field in a copy of the Partial to a parsed text value. *

* The Partial attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @return a copy of the Partial with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public Partial setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new Partial with this field set to the maximum value * for this field. *

* The Partial attached to this property is unchanged by this call. * * @return a copy of the Partial with this field set to its maximum * @since 1.2 */ public Partial withMaximumValue() { return setCopy(getMaximumValue()); } /** * Returns a new Partial with this field set to the minimum value * for this field. *

* The Partial attached to this property is unchanged by this call. * * @return a copy of the Partial with this field set to its minimum * @since 1.2 */ public Partial withMinimumValue() { return setCopy(getMinimumValue()); } } } joda-time-2.3/src/main/java/org/joda/time/ReadWritableInstant.java0000644000175000017500000001344111564251363024437 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines an instant in the datetime continuum that can be queried and modified. * This interface expresses the datetime as milliseconds from 1970-01-01T00:00:00Z. *

* The implementation of this interface will be mutable. * It may provide more advanced methods than those in the interface. * * @author Stephen Colebourne * @since 1.0 */ public interface ReadWritableInstant extends ReadableInstant { /** * Sets the value as the number of milliseconds since * the epoch, 1970-01-01T00:00:00Z. * * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the * instant to * @throws IllegalArgumentException if the value is invalid */ void setMillis(long instant); /** * Sets the millisecond instant of this instant from another. *

* This method does not change the chronology of this instant, just the * millisecond instant. * * @param instant the instant to use, null means now */ void setMillis(ReadableInstant instant); /** * Sets the chronology of the datetime, which has no effect if not applicable. * * @param chronology the chronology to use, null means ISOChronology in default zone * @throws IllegalArgumentException if the value is invalid */ void setChronology(Chronology chronology); /** * Sets the time zone of the datetime, changing the chronology and field values. *

* Changing the zone using this method retains the millisecond instant. * The millisecond instant is adjusted in the new zone to compensate. * * chronology. Setting the time zone does not affect the millisecond value * of this instant. *

* If the chronology already has this time zone, no change occurs. * * @param zone the time zone to use, null means default zone * @see #setZoneRetainFields */ void setZone(DateTimeZone zone); /** * Sets the time zone of the datetime, changing the chronology and millisecond. *

* Changing the zone using this method retains the field values. * The millisecond instant is adjusted in the new zone to compensate. *

* If the chronology already has this time zone, no change occurs. * * @param zone the time zone to use, null means default zone * @see #setZone */ void setZoneRetainFields(DateTimeZone zone); //----------------------------------------------------------------------- /** * Adds a millisecond duration to this instant. *

* This will typically change the value of ost fields. * * @param duration the millis to add * @throws IllegalArgumentException if the value is invalid */ void add(long duration); /** * Adds a duration to this instant. *

* This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ void add(ReadableDuration duration); /** * Adds a duration to this instant specifying how many times to add. *

* This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ void add(ReadableDuration duration, int scalar); /** * Adds a period to this instant. *

* This will typically change the value of most fields. * * @param period the period to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ void add(ReadablePeriod period); /** * Adds a period to this instant specifying how many times to add. *

* This will typically change the value of most fields. * * @param period the period to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ void add(ReadablePeriod period, int scalar); //----------------------------------------------------------------------- /** * Sets the value of one of the fields of the instant, such as hourOfDay. * * @param type a field type, usually obtained from DateTimeFieldType, null ignored * @param value the value to set the field to * @throws IllegalArgumentException if the value is invalid */ void set(DateTimeFieldType type, int value); /** * Adds to the instant specifying the duration and multiple to add. * * @param type a field type, usually obtained from DateTimeFieldType, null ignored * @param amount the amount to add of this duration * @throws ArithmeticException if the result exceeds the capacity of the instant */ void add(DurationFieldType type, int amount); } joda-time-2.3/src/main/java/org/joda/time/JodaTimePermission.java0000644000175000017500000000426611564251363024303 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.security.BasicPermission; /** * JodaTimePermission is used for securing global method calls in the Joda-Time * library. Since this class extends BasicPermission, asterisks may be used to * denote wildcard permissions. The following permissions are supported: * *

 * DateTimeZone
 *   .setDefault                 Allows a default DateTimeZone to be set
 *   .setProvider                Allows the DateTimeZone instance provider to be set
 *   .setNameProvider            Allows the DateTimeZone name provider to be set
 *
 * ConverterManager
 *   .alterInstantConverters     Allows an instant converter to be added or removed
 *   .alterPartialConverters     Allows a partial converter to be added or removed
 *   .alterDurationConverters    Allows a duration converter to be added or removed
 *   .alterPeriodConverters      Allows a period converter to be added or removed
 *   .alterIntervalConverters    Allows an interval converter to be added or removed
 *
 * CurrentTime.setProvider       Allows the current time provider to be set
 * 
*

* JodaTimePermission is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public class JodaTimePermission extends BasicPermission { /** Serialization version */ private static final long serialVersionUID = 1408944367355875472L; /** * Constructs a new permission object. * * @param name the permission name */ public JodaTimePermission(String name) { super(name); } } joda-time-2.3/src/main/java/org/joda/time/DateTimeUtils.java0000644000175000017500000005344212162055431023244 0ustar ebourgebourg/* * Copyright 2001-2012 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.lang.reflect.Method; import java.text.DateFormatSymbols; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import org.joda.time.chrono.ISOChronology; /** * DateTimeUtils provide public utility methods for the date-time library. *

* DateTimeUtils is thread-safe although shared static variables are used. * * @author Stephen Colebourne * @since 1.0 */ public class DateTimeUtils { /** The singleton instance of the system millisecond provider. */ private static final SystemMillisProvider SYSTEM_MILLIS_PROVIDER = new SystemMillisProvider(); /** The millisecond provider currently in use. */ private static volatile MillisProvider cMillisProvider = SYSTEM_MILLIS_PROVIDER; /** The millisecond provider currently in use. */ private static volatile Map cZoneNames; static { // names from RFC-822 / JDK // this is all very US-centric and dubious, but perhaps it will help some Map map = new LinkedHashMap(); map.put("UT", DateTimeZone.UTC); map.put("UTC", DateTimeZone.UTC); map.put("GMT", DateTimeZone.UTC); put(map, "EST", "America/New_York"); put(map, "EDT", "America/New_York"); put(map, "CST", "America/Chicago"); put(map, "CDT", "America/Chicago"); put(map, "MST", "America/Denver"); put(map, "MDT", "America/Denver"); put(map, "PST", "America/Los_Angeles"); put(map, "PDT", "America/Los_Angeles"); cZoneNames = Collections.unmodifiableMap(map); } private static void put(Map map, String name, String id) { try { map.put(name, DateTimeZone.forID(id)); } catch (RuntimeException ex) { // ignore } } /** * Restrictive constructor */ protected DateTimeUtils() { super(); } //----------------------------------------------------------------------- /** * Gets the current time in milliseconds. *

* By default this returns System.currentTimeMillis(). * This may be changed using other methods in this class. * * @return the current time in milliseconds from 1970-01-01T00:00:00Z */ public static final long currentTimeMillis() { return cMillisProvider.getMillis(); } /** * Resets the current time to return the system time. *

* This method changes the behaviour of {@link #currentTimeMillis()}. * Whenever the current time is queried, {@link System#currentTimeMillis()} is used. * * @throws SecurityException if the application does not have sufficient security rights */ public static final void setCurrentMillisSystem() throws SecurityException { checkPermission(); cMillisProvider = SYSTEM_MILLIS_PROVIDER; } /** * Sets the current time to return a fixed millisecond time. *

* This method changes the behaviour of {@link #currentTimeMillis()}. * Whenever the current time is queried, the same millisecond time will be returned. * * @param fixedMillis the fixed millisecond time to use * @throws SecurityException if the application does not have sufficient security rights */ public static final void setCurrentMillisFixed(long fixedMillis) throws SecurityException { checkPermission(); cMillisProvider = new FixedMillisProvider(fixedMillis); } /** * Sets the current time to return the system time plus an offset. *

* This method changes the behaviour of {@link #currentTimeMillis()}. * Whenever the current time is queried, {@link System#currentTimeMillis()} is used * and then offset by adding the millisecond value specified here. * * @param offsetMillis the fixed millisecond time to use * @throws SecurityException if the application does not have sufficient security rights */ public static final void setCurrentMillisOffset(long offsetMillis) throws SecurityException { checkPermission(); if (offsetMillis == 0) { cMillisProvider = SYSTEM_MILLIS_PROVIDER; } else { cMillisProvider = new OffsetMillisProvider(offsetMillis); } } /** * Sets the provider of the current time to class specified. *

* This method changes the behaviour of {@link #currentTimeMillis()}. * Whenever the current time is queried, the specified class will be called. * * @param millisProvider the provider of the current time to use, not null * @throws SecurityException if the application does not have sufficient security rights * @since 2.0 */ public static final void setCurrentMillisProvider(MillisProvider millisProvider) throws SecurityException { if (millisProvider == null) { throw new IllegalArgumentException("The MillisProvider must not be null"); } checkPermission(); cMillisProvider = millisProvider; } /** * Checks whether the provider may be changed using permission 'CurrentTime.setProvider'. * * @throws SecurityException if the provider may not be changed */ private static void checkPermission() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("CurrentTime.setProvider")); } } //----------------------------------------------------------------------- /** * Gets the millisecond instant from the specified instant object handling null. *

* If the instant object is null, the {@link #currentTimeMillis()} * will be returned. Otherwise, the millis from the object are returned. * * @param instant the instant to examine, null means now * @return the time in milliseconds from 1970-01-01T00:00:00Z */ public static final long getInstantMillis(ReadableInstant instant) { if (instant == null) { return DateTimeUtils.currentTimeMillis(); } return instant.getMillis(); } //----------------------------------------------------------------------- /** * Gets the chronology from the specified instant object handling null. *

* If the instant object is null, or the instant's chronology is * null, {@link ISOChronology#getInstance()} will be returned. * Otherwise, the chronology from the object is returned. * * @param instant the instant to examine, null means ISO in the default zone * @return the chronology, never null */ public static final Chronology getInstantChronology(ReadableInstant instant) { if (instant == null) { return ISOChronology.getInstance(); } Chronology chrono = instant.getChronology(); if (chrono == null) { return ISOChronology.getInstance(); } return chrono; } //----------------------------------------------------------------------- /** * Gets the chronology from the specified instant based interval handling null. *

* The chronology is obtained from the start if that is not null, or from the * end if the start is null. The result is additionally checked, and if still * null then {@link ISOChronology#getInstance()} will be returned. * * @param start the instant to examine and use as the primary source of the chronology * @param end the instant to examine and use as the secondary source of the chronology * @return the chronology, never null */ public static final Chronology getIntervalChronology(ReadableInstant start, ReadableInstant end) { Chronology chrono = null; if (start != null) { chrono = start.getChronology(); } else if (end != null) { chrono = end.getChronology(); } if (chrono == null) { chrono = ISOChronology.getInstance(); } return chrono; } //----------------------------------------------------------------------- /** * Gets the chronology from the specified interval object handling null. *

* If the interval object is null, or the interval's chronology is * null, {@link ISOChronology#getInstance()} will be returned. * Otherwise, the chronology from the object is returned. * * @param interval the interval to examine, null means ISO in the default zone * @return the chronology, never null */ public static final Chronology getIntervalChronology(ReadableInterval interval) { if (interval == null) { return ISOChronology.getInstance(); } Chronology chrono = interval.getChronology(); if (chrono == null) { return ISOChronology.getInstance(); } return chrono; } //----------------------------------------------------------------------- /** * Gets the interval handling null. *

* If the interval is null, an interval representing now * to now in the {@link ISOChronology#getInstance() ISOChronology} * will be returned. Otherwise, the interval specified is returned. * * @param interval the interval to use, null means now to now * @return the interval, never null * @since 1.1 */ public static final ReadableInterval getReadableInterval(ReadableInterval interval) { if (interval == null) { long now = DateTimeUtils.currentTimeMillis(); interval = new Interval(now, now); } return interval; } //----------------------------------------------------------------------- /** * Gets the chronology handling null. *

* If the chronology is null, {@link ISOChronology#getInstance()} * will be returned. Otherwise, the chronology is returned. * * @param chrono the chronology to use, null means ISO in the default zone * @return the chronology, never null */ public static final Chronology getChronology(Chronology chrono) { if (chrono == null) { return ISOChronology.getInstance(); } return chrono; } //----------------------------------------------------------------------- /** * Gets the zone handling null. *

* If the zone is null, {@link DateTimeZone#getDefault()} * will be returned. Otherwise, the zone specified is returned. * * @param zone the time zone to use, null means the default zone * @return the time zone, never null */ public static final DateTimeZone getZone(DateTimeZone zone) { if (zone == null) { return DateTimeZone.getDefault(); } return zone; } //----------------------------------------------------------------------- /** * Gets the period type handling null. *

* If the zone is null, {@link PeriodType#standard()} * will be returned. Otherwise, the type specified is returned. * * @param type the time zone to use, null means the standard type * @return the type to use, never null */ public static final PeriodType getPeriodType(PeriodType type) { if (type == null) { return PeriodType.standard(); } return type; } //----------------------------------------------------------------------- /** * Gets the millisecond duration from the specified duration object handling null. *

* If the duration object is null, zero will be returned. * Otherwise, the millis from the object are returned. * * @param duration the duration to examine, null means zero * @return the duration in milliseconds */ public static final long getDurationMillis(ReadableDuration duration) { if (duration == null) { return 0L; } return duration.getMillis(); } //----------------------------------------------------------------------- /** * Checks whether the partial is contiguous. *

* A partial is contiguous if one field starts where another ends. *

* For example LocalDate is contiguous because DayOfMonth has * the same range (Month) as the unit of the next field (MonthOfYear), and * MonthOfYear has the same range (Year) as the unit of the next field (Year). *

* Similarly, LocalTime is contiguous, as it consists of * MillisOfSecond, SecondOfMinute, MinuteOfHour and HourOfDay (note how * the names of each field 'join up'). *

* However, a Year/HourOfDay partial is not contiguous because the range * field Day is not equal to the next field Year. * Similarly, a DayOfWeek/DayOfMonth partial is not contiguous because * the range Month is not equal to the next field Day. * * @param partial the partial to check * @return true if the partial is contiguous * @throws IllegalArgumentException if the partial is null * @since 1.1 */ public static final boolean isContiguous(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("Partial must not be null"); } DurationFieldType lastType = null; for (int i = 0; i < partial.size(); i++) { DateTimeField loopField = partial.getField(i); if (i > 0) { if (loopField.getRangeDurationField().getType() != lastType) { return false; } } lastType = loopField.getDurationField().getType(); } return true; } //----------------------------------------------------------------------- /** * Gets the {@link DateFormatSymbols} based on the given locale. *

* If JDK 6 or newer is being used, DateFormatSymbols.getInstance(locale) will * be used in order to allow the use of locales defined as extensions. * Otherwise, new DateFormatSymbols(locale) will be used. * See JDK 6 {@link DateFormatSymbols} for further information. * * @param locale the {@link Locale} used to get the correct {@link DateFormatSymbols} * @return the symbols * @since 2.0 */ public static final DateFormatSymbols getDateFormatSymbols(Locale locale) { try { Method method = DateFormatSymbols.class.getMethod("getInstance", new Class[] {Locale.class}); return (DateFormatSymbols) method.invoke(null, new Object[] {locale}); } catch (Exception ex) { return new DateFormatSymbols(locale); } } //----------------------------------------------------------------------- /** * Gets the default map of time zone names. *

* This can be changed by {@link #setDefaultTimeZoneNames}. *

* The default set of short time zone names is as follows: *

    *
  • UT - UTC *
  • UTC - UTC *
  • GMT - UTC *
  • EST - America/New_York *
  • EDT - America/New_York *
  • CST - America/Chicago *
  • CDT - America/Chicago *
  • MST - America/Denver *
  • MDT - America/Denver *
  • PST - America/Los_Angeles *
  • PDT - America/Los_Angeles *
* * @return the unmodifiable map of abbreviations to zones, not null * @since 2.2 */ public static final Map getDefaultTimeZoneNames() { return cZoneNames; } /** * Sets the default map of time zone names. *

* The map is copied before storage. * * @param names the map of abbreviations to zones, not null * @since 2.2 */ public static final void setDefaultTimeZoneNames(Map names) { cZoneNames = Collections.unmodifiableMap(new HashMap(names)); } //------------------------------------------------------------------------- /** * Calculates the astronomical Julian Day for an instant. *

* The Julian day is a well-known * system of time measurement for scientific use by the astronomy community. * It expresses the interval of time in days and fractions of a day since * January 1, 4713 BC (Julian) Greenwich noon. *

* Each day starts at midday (not midnight) and time is expressed as a fraction. * Thus the fraction 0.25 is 18:00. equal to one quarter of the day from midday to midday. *

* Note that this method has nothing to do with the day-of-year. * * @param epochMillis the epoch millis from 1970-01-01Z * @return the astronomical Julian Day represented by the specified instant * @since 2.2 */ public static final double toJulianDay(long epochMillis) { // useful links // http://en.wikipedia.org/wiki/Julian_day#cite_note-13 - Wikipedia // http://aa.usno.navy.mil/data/docs/JulianDate.php" - USNO // http://users.zoominternet.net/~matto/Java/Julian%20Date%20Converter.htm - Julian Date Converter by Matt Oltersdorf // http://ssd.jpl.nasa.gov/tc.cgi#top - CalTech double epochDay = epochMillis / 86400000d; return epochDay + 2440587.5d; } /** * Calculates the astronomical Julian Day Number for an instant. *

* The {@link #toJulianDay(long)} method calculates the astronomical Julian Day * with a fraction based on days starting at midday. * This method calculates the variant where days start at midnight. * JDN 0 is used for the date equivalent to Monday January 1, 4713 BC (Julian). * Thus these days start 12 hours before those of the fractional Julian Day. *

* Note that this method has nothing to do with the day-of-year. * * @param epochMillis the epoch millis from 1970-01-01Z * @return the astronomical Julian Day represented by the specified instant * @since 2.2 */ public static final long toJulianDayNumber(long epochMillis) { return (long) Math.floor(toJulianDay(epochMillis) + 0.5d); } /** * Creates a date-time from a Julian Day. *

* Returns the {@code DateTime} object equal to the specified Julian Day. * * @param julianDay the Julian Day * @return the epoch millis from 1970-01-01Z * @since 2.2 */ public static final long fromJulianDay(double julianDay) { double epochDay = julianDay - 2440587.5d; return (long) (epochDay * 86400000d); } //----------------------------------------------------------------------- /** * A millisecond provider, allowing control of the system clock. * * @author Stephen Colebourne * @since 2.0 (previously private) */ public static interface MillisProvider { /** * Gets the current time. *

* Implementations of this method must be thread-safe. * * @return the current time in milliseconds */ long getMillis(); } /** * System millis provider. */ static class SystemMillisProvider implements MillisProvider { /** * Gets the current time. * @return the current time in millis */ public long getMillis() { return System.currentTimeMillis(); } } /** * Fixed millisecond provider. */ static class FixedMillisProvider implements MillisProvider { /** The fixed millis value. */ private final long iMillis; /** * Constructor. * @param offsetMillis the millis offset */ FixedMillisProvider(long fixedMillis) { iMillis = fixedMillis; } /** * Gets the current time. * @return the current time in millis */ public long getMillis() { return iMillis; } } /** * Offset from system millis provider. */ static class OffsetMillisProvider implements MillisProvider { /** The millis offset. */ private final long iMillis; /** * Constructor. * @param offsetMillis the millis offset */ OffsetMillisProvider(long offsetMillis) { iMillis = offsetMillis; } /** * Gets the current time. * @return the current time in millis */ public long getMillis() { return System.currentTimeMillis() + iMillis; } } } joda-time-2.3/src/main/java/org/joda/time/format/0000755000175000017500000000000012205344143021143 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/format/messages.properties0000644000175000017500000000121211564251363025074 0ustar ebourgebourgPeriodFormat.space=\ PeriodFormat.comma=, PeriodFormat.commandand=,and PeriodFormat.commaspaceand=, and PeriodFormat.commaspace=, PeriodFormat.spaceandspace=\ and PeriodFormat.year=\ year PeriodFormat.years=\ years PeriodFormat.month=\ month PeriodFormat.months=\ months PeriodFormat.week=\ week PeriodFormat.weeks=\ weeks PeriodFormat.day=\ day PeriodFormat.days=\ days PeriodFormat.hour=\ hour PeriodFormat.hours=\ hours PeriodFormat.minute=\ minute PeriodFormat.minutes=\ minutes PeriodFormat.second=\ second PeriodFormat.seconds=\ seconds PeriodFormat.millisecond=\ millisecond PeriodFormat.milliseconds=\ milliseconds joda-time-2.3/src/main/java/org/joda/time/format/PeriodPrinter.java0000644000175000017500000000533611564251363024613 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.IOException; import java.io.Writer; import java.util.Locale; import org.joda.time.ReadablePeriod; /** * Internal interface for printing textual representations of time periods. *

* Application users will rarely use this class directly. Instead, you * will use one of the factory classes to create a {@link PeriodFormatter}. *

* The factory classes are:
* - {@link PeriodFormatterBuilder}
* - {@link PeriodFormat}
* - {@link ISOPeriodFormat}
* * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 * @see PeriodFormatter * @see PeriodFormatterBuilder * @see PeriodFormat */ public interface PeriodPrinter { /** * Returns the exact number of characters produced for the given period. * * @param period the period to use * @param locale the locale to use * @return the estimated length */ int calculatePrintedLength(ReadablePeriod period, Locale locale); /** * Returns the amount of fields from the given period that this printer * will print. * * @param period the period to use * @param stopAt stop counting at this value, enter a number ≥ 256 to count all * @param locale the locale to use * @return amount of fields printed */ int countFieldsToPrint(ReadablePeriod period, int stopAt, Locale locale); //----------------------------------------------------------------------- /** * Prints a ReadablePeriod to a StringBuffer. * * @param buf the formatted period is appended to this buffer * @param period the period to format * @param locale the locale to use */ void printTo(StringBuffer buf, ReadablePeriod period, Locale locale); /** * Prints a ReadablePeriod to a Writer. * * @param out the formatted period is written out * @param period the period to format * @param locale the locale to use */ void printTo(Writer out, ReadablePeriod period, Locale locale) throws IOException; } joda-time-2.3/src/main/java/org/joda/time/format/DateTimeFormatterBuilder.java0000644000175000017500000032651312203434112026701 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.MutableDateTime; import org.joda.time.ReadablePartial; import org.joda.time.MutableDateTime.Property; import org.joda.time.field.MillisDurationField; import org.joda.time.field.PreciseDateTimeField; /** * Factory that creates complex instances of DateTimeFormatter via method calls. *

* Datetime formatting is performed by the {@link DateTimeFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link DateTimeFormat} and {@link ISODateTimeFormat}. *

* DateTimeFormatterBuilder is used for constructing formatters which are then * used to print or parse. The formatters are built by appending specific fields * or other formatters to an instance of this builder. *

* For example, a formatter that prints month and year, like "January 1970", * can be constructed as follows: *

*

 * DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
 *     .appendMonthOfYearText()
 *     .appendLiteral(' ')
 *     .appendYear(4, 4)
 *     .toFormatter();
 * 
*

* DateTimeFormatterBuilder itself is mutable and not thread-safe, but the * formatters that it builds are thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @author Fredrik Borgh * @since 1.0 * @see DateTimeFormat * @see ISODateTimeFormat */ public class DateTimeFormatterBuilder { /** Array of printers and parsers (alternating). */ private ArrayList iElementPairs; /** Cache of the last returned formatter. */ private Object iFormatter; //----------------------------------------------------------------------- /** * Creates a DateTimeFormatterBuilder. */ public DateTimeFormatterBuilder() { super(); iElementPairs = new ArrayList(); } //----------------------------------------------------------------------- /** * Constructs a DateTimeFormatter using all the appended elements. *

* This is the main method used by applications at the end of the build * process to create a usable formatter. *

* Subsequent changes to this builder do not affect the returned formatter. *

* The returned formatter may not support both printing and parsing. * The methods {@link DateTimeFormatter#isPrinter()} and * {@link DateTimeFormatter#isParser()} will help you determine the state * of the formatter. * * @throws UnsupportedOperationException if neither printing nor parsing is supported */ public DateTimeFormatter toFormatter() { Object f = getFormatter(); DateTimePrinter printer = null; if (isPrinter(f)) { printer = (DateTimePrinter) f; } DateTimeParser parser = null; if (isParser(f)) { parser = (DateTimeParser) f; } if (printer != null || parser != null) { return new DateTimeFormatter(printer, parser); } throw new UnsupportedOperationException("Both printing and parsing not supported"); } /** * Internal method to create a DateTimePrinter instance using all the * appended elements. *

* Most applications will not use this method. * If you want a printer in an application, call {@link #toFormatter()} * and just use the printing API. *

* Subsequent changes to this builder do not affect the returned printer. * * @throws UnsupportedOperationException if printing is not supported */ public DateTimePrinter toPrinter() { Object f = getFormatter(); if (isPrinter(f)) { return (DateTimePrinter) f; } throw new UnsupportedOperationException("Printing is not supported"); } /** * Internal method to create a DateTimeParser instance using all the * appended elements. *

* Most applications will not use this method. * If you want a parser in an application, call {@link #toFormatter()} * and just use the parsing API. *

* Subsequent changes to this builder do not affect the returned parser. * * @throws UnsupportedOperationException if parsing is not supported */ public DateTimeParser toParser() { Object f = getFormatter(); if (isParser(f)) { return (DateTimeParser) f; } throw new UnsupportedOperationException("Parsing is not supported"); } //----------------------------------------------------------------------- /** * Returns true if toFormatter can be called without throwing an * UnsupportedOperationException. * * @return true if a formatter can be built */ public boolean canBuildFormatter() { return isFormatter(getFormatter()); } /** * Returns true if toPrinter can be called without throwing an * UnsupportedOperationException. * * @return true if a printer can be built */ public boolean canBuildPrinter() { return isPrinter(getFormatter()); } /** * Returns true if toParser can be called without throwing an * UnsupportedOperationException. * * @return true if a parser can be built */ public boolean canBuildParser() { return isParser(getFormatter()); } //----------------------------------------------------------------------- /** * Clears out all the appended elements, allowing this builder to be * reused. */ public void clear() { iFormatter = null; iElementPairs.clear(); } //----------------------------------------------------------------------- /** * Appends another formatter. *

* This extracts the underlying printer and parser and appends them * The printer and parser interfaces are the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param formatter the formatter to add * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if formatter is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimeFormatter formatter) { if (formatter == null) { throw new IllegalArgumentException("No formatter supplied"); } return append0(formatter.getPrinter(), formatter.getParser()); } /** * Appends just a printer. With no matching parser, a parser cannot be * built from this DateTimeFormatterBuilder. *

* The printer interface is part of the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param printer the printer to add, not null * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if printer is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimePrinter printer) { checkPrinter(printer); return append0(printer, null); } /** * Appends just a parser. With no matching printer, a printer cannot be * built from this builder. *

* The parser interface is part of the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param parser the parser to add, not null * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if parser is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimeParser parser) { checkParser(parser); return append0(null, parser); } /** * Appends a printer/parser pair. *

* The printer and parser interfaces are the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param printer the printer to add, not null * @param parser the parser to add, not null * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if printer or parser is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser parser) { checkPrinter(printer); checkParser(parser); return append0(printer, parser); } /** * Appends a printer and a set of matching parsers. When parsing, the first * parser in the list is selected for parsing. If it fails, the next is * chosen, and so on. If none of these parsers succeeds, then the failed * position of the parser that made the greatest progress is returned. *

* Only the printer is optional. In addition, it is illegal for any but the * last of the parser array elements to be null. If the last element is * null, this represents the empty parser. The presence of an empty parser * indicates that the entire array of parse formats is optional. *

* The printer and parser interfaces are the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param printer the printer to add * @param parsers the parsers to add * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if any printer or parser is of an invalid type * @throws IllegalArgumentException if any parser element but the last is null */ public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser[] parsers) { if (printer != null) { checkPrinter(printer); } if (parsers == null) { throw new IllegalArgumentException("No parsers supplied"); } int length = parsers.length; if (length == 1) { if (parsers[0] == null) { throw new IllegalArgumentException("No parser supplied"); } return append0(printer, parsers[0]); } DateTimeParser[] copyOfParsers = new DateTimeParser[length]; int i; for (i = 0; i < length - 1; i++) { if ((copyOfParsers[i] = parsers[i]) == null) { throw new IllegalArgumentException("Incomplete parser array"); } } copyOfParsers[i] = parsers[i]; return append0(printer, new MatchingParser(copyOfParsers)); } /** * Appends just a parser element which is optional. With no matching * printer, a printer cannot be built from this DateTimeFormatterBuilder. *

* The parser interface is part of the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if parser is null or of an invalid type */ public DateTimeFormatterBuilder appendOptional(DateTimeParser parser) { checkParser(parser); DateTimeParser[] parsers = new DateTimeParser[] {parser, null}; return append0(null, new MatchingParser(parsers)); } //----------------------------------------------------------------------- /** * Checks if the parser is non null and a provider. * * @param parser the parser to check */ private void checkParser(DateTimeParser parser) { if (parser == null) { throw new IllegalArgumentException("No parser supplied"); } } /** * Checks if the printer is non null and a provider. * * @param printer the printer to check */ private void checkPrinter(DateTimePrinter printer) { if (printer == null) { throw new IllegalArgumentException("No printer supplied"); } } private DateTimeFormatterBuilder append0(Object element) { iFormatter = null; // Add the element as both a printer and parser. iElementPairs.add(element); iElementPairs.add(element); return this; } private DateTimeFormatterBuilder append0( DateTimePrinter printer, DateTimeParser parser) { iFormatter = null; iElementPairs.add(printer); iElementPairs.add(parser); return this; } //----------------------------------------------------------------------- /** * Instructs the printer to emit a specific character, and the parser to * expect it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendLiteral(char c) { return append0(new CharacterLiteral(c)); } /** * Instructs the printer to emit specific text, and the parser to expect * it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if text is null */ public DateTimeFormatterBuilder appendLiteral(String text) { if (text == null) { throw new IllegalArgumentException("Literal must not be null"); } switch (text.length()) { case 0: return this; case 1: return append0(new CharacterLiteral(text.charAt(0))); default: return append0(new StringLiteral(text)); } } /** * Instructs the printer to emit a field value as a decimal number, and the * parser to expect an unsigned decimal number. * * @param fieldType type of field to append * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to parse, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendDecimal( DateTimeFieldType fieldType, int minDigits, int maxDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (maxDigits < minDigits) { maxDigits = minDigits; } if (minDigits < 0 || maxDigits <= 0) { throw new IllegalArgumentException(); } if (minDigits <= 1) { return append0(new UnpaddedNumber(fieldType, maxDigits, false)); } else { return append0(new PaddedNumber(fieldType, maxDigits, false, minDigits)); } } /** * Instructs the printer to emit a field value as a fixed-width decimal * number (smaller numbers will be left-padded with zeros), and the parser * to expect an unsigned decimal number with the same fixed width. * * @param fieldType type of field to append * @param numDigits the exact number of digits to parse or print, except if * printed value requires more digits * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null or if numDigits <= 0 * @since 1.5 */ public DateTimeFormatterBuilder appendFixedDecimal( DateTimeFieldType fieldType, int numDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (numDigits <= 0) { throw new IllegalArgumentException("Illegal number of digits: " + numDigits); } return append0(new FixedNumber(fieldType, numDigits, false)); } /** * Instructs the printer to emit a field value as a decimal number, and the * parser to expect a signed decimal number. * * @param fieldType type of field to append * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to parse, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendSignedDecimal( DateTimeFieldType fieldType, int minDigits, int maxDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (maxDigits < minDigits) { maxDigits = minDigits; } if (minDigits < 0 || maxDigits <= 0) { throw new IllegalArgumentException(); } if (minDigits <= 1) { return append0(new UnpaddedNumber(fieldType, maxDigits, true)); } else { return append0(new PaddedNumber(fieldType, maxDigits, true, minDigits)); } } /** * Instructs the printer to emit a field value as a fixed-width decimal * number (smaller numbers will be left-padded with zeros), and the parser * to expect an signed decimal number with the same fixed width. * * @param fieldType type of field to append * @param numDigits the exact number of digits to parse or print, except if * printed value requires more digits * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null or if numDigits <= 0 * @since 1.5 */ public DateTimeFormatterBuilder appendFixedSignedDecimal( DateTimeFieldType fieldType, int numDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (numDigits <= 0) { throw new IllegalArgumentException("Illegal number of digits: " + numDigits); } return append0(new FixedNumber(fieldType, numDigits, true)); } /** * Instructs the printer to emit a field value as text, and the * parser to expect text. * * @param fieldType type of field to append * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendText(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } return append0(new TextField(fieldType, false)); } /** * Instructs the printer to emit a field value as short text, and the * parser to expect text. * * @param fieldType type of field to append * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendShortText(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } return append0(new TextField(fieldType, true)); } /** * Instructs the printer to emit a remainder of time as a decimal fraction, * without decimal point. For example, if the field is specified as * minuteOfHour and the time is 12:30:45, the value printed is 75. A * decimal point is implied, so the fraction is 0.75, or three-quarters of * a minute. * * @param fieldType type of field to append * @param minDigits minimum number of digits to print. * @param maxDigits maximum number of digits to print or parse. * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendFraction( DateTimeFieldType fieldType, int minDigits, int maxDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (maxDigits < minDigits) { maxDigits = minDigits; } if (minDigits < 0 || maxDigits <= 0) { throw new IllegalArgumentException(); } return append0(new Fraction(fieldType, minDigits, maxDigits)); } /** * Appends the print/parse of a fractional second. *

* This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 230 milliseconds. * Contrast this behaviour to {@link #appendMillisOfSecond}. * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfSecond(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.secondOfDay(), minDigits, maxDigits); } /** * Appends the print/parse of a fractional minute. *

* This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 0.23 minutes (converted to milliseconds). * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfMinute(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.minuteOfDay(), minDigits, maxDigits); } /** * Appends the print/parse of a fractional hour. *

* This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 0.23 hours (converted to milliseconds). * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfHour(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.hourOfDay(), minDigits, maxDigits); } /** * Appends the print/parse of a fractional day. *

* This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 0.23 days (converted to milliseconds). * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfDay(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.dayOfYear(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric millisOfSecond field. *

* This method will append a field that prints a three digit value. * During parsing the value that is parsed is assumed to be three digits. * If less than three digits are present then they will be counted as the * smallest parts of the millisecond. This is probably not what you want * if you are using the field as a fraction. Instead, a fractional * millisecond should be produced using {@link #appendFractionOfSecond}. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMillisOfSecond(int minDigits) { return appendDecimal(DateTimeFieldType.millisOfSecond(), minDigits, 3); } /** * Instructs the printer to emit a numeric millisOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMillisOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.millisOfDay(), minDigits, 8); } /** * Instructs the printer to emit a numeric secondOfMinute field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendSecondOfMinute(int minDigits) { return appendDecimal(DateTimeFieldType.secondOfMinute(), minDigits, 2); } /** * Instructs the printer to emit a numeric secondOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendSecondOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.secondOfDay(), minDigits, 5); } /** * Instructs the printer to emit a numeric minuteOfHour field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMinuteOfHour(int minDigits) { return appendDecimal(DateTimeFieldType.minuteOfHour(), minDigits, 2); } /** * Instructs the printer to emit a numeric minuteOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMinuteOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.minuteOfDay(), minDigits, 4); } /** * Instructs the printer to emit a numeric hourOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendHourOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.hourOfDay(), minDigits, 2); } /** * Instructs the printer to emit a numeric clockhourOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendClockhourOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.clockhourOfDay(), minDigits, 2); } /** * Instructs the printer to emit a numeric hourOfHalfday field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendHourOfHalfday(int minDigits) { return appendDecimal(DateTimeFieldType.hourOfHalfday(), minDigits, 2); } /** * Instructs the printer to emit a numeric clockhourOfHalfday field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendClockhourOfHalfday(int minDigits) { return appendDecimal(DateTimeFieldType.clockhourOfHalfday(), minDigits, 2); } /** * Instructs the printer to emit a numeric dayOfWeek field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfWeek(int minDigits) { return appendDecimal(DateTimeFieldType.dayOfWeek(), minDigits, 1); } /** * Instructs the printer to emit a numeric dayOfMonth field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfMonth(int minDigits) { return appendDecimal(DateTimeFieldType.dayOfMonth(), minDigits, 2); } /** * Instructs the printer to emit a numeric dayOfYear field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfYear(int minDigits) { return appendDecimal(DateTimeFieldType.dayOfYear(), minDigits, 3); } /** * Instructs the printer to emit a numeric weekOfWeekyear field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendWeekOfWeekyear(int minDigits) { return appendDecimal(DateTimeFieldType.weekOfWeekyear(), minDigits, 2); } /** * Instructs the printer to emit a numeric weekyear field. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to parse, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendWeekyear(int minDigits, int maxDigits) { return appendSignedDecimal(DateTimeFieldType.weekyear(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric monthOfYear field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMonthOfYear(int minDigits) { return appendDecimal(DateTimeFieldType.monthOfYear(), minDigits, 2); } /** * Instructs the printer to emit a numeric year field. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to parse, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendYear(int minDigits, int maxDigits) { return appendSignedDecimal(DateTimeFieldType.year(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric year field which always prints * and parses two digits. A pivot year is used during parsing to determine * the range of supported years as (pivot - 50) .. (pivot + 49). * *

     * pivot   supported range   00 is   20 is   40 is   60 is   80 is
     * ---------------------------------------------------------------
     * 1950      1900..1999      1900    1920    1940    1960    1980
     * 1975      1925..2024      2000    2020    1940    1960    1980
     * 2000      1950..2049      2000    2020    2040    1960    1980
     * 2025      1975..2074      2000    2020    2040    2060    1980
     * 2050      2000..2099      2000    2020    2040    2060    2080
     * 
* * @param pivot pivot year to use when parsing * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTwoDigitYear(int pivot) { return appendTwoDigitYear(pivot, false); } /** * Instructs the printer to emit a numeric year field which always prints * two digits. A pivot year is used during parsing to determine the range * of supported years as (pivot - 50) .. (pivot + 49). If * parse is instructed to be lenient and the digit count is not two, it is * treated as an absolute year. With lenient parsing, specifying a positive * or negative sign before the year also makes it absolute. * * @param pivot pivot year to use when parsing * @param lenientParse when true, if digit count is not two, it is treated * as an absolute year * @return this DateTimeFormatterBuilder, for chaining * @since 1.1 */ public DateTimeFormatterBuilder appendTwoDigitYear(int pivot, boolean lenientParse) { return append0(new TwoDigitYear(DateTimeFieldType.year(), pivot, lenientParse)); } /** * Instructs the printer to emit a numeric weekyear field which always prints * and parses two digits. A pivot year is used during parsing to determine * the range of supported years as (pivot - 50) .. (pivot + 49). * *
     * pivot   supported range   00 is   20 is   40 is   60 is   80 is
     * ---------------------------------------------------------------
     * 1950      1900..1999      1900    1920    1940    1960    1980
     * 1975      1925..2024      2000    2020    1940    1960    1980
     * 2000      1950..2049      2000    2020    2040    1960    1980
     * 2025      1975..2074      2000    2020    2040    2060    1980
     * 2050      2000..2099      2000    2020    2040    2060    2080
     * 
* * @param pivot pivot weekyear to use when parsing * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTwoDigitWeekyear(int pivot) { return appendTwoDigitWeekyear(pivot, false); } /** * Instructs the printer to emit a numeric weekyear field which always prints * two digits. A pivot year is used during parsing to determine the range * of supported years as (pivot - 50) .. (pivot + 49). If * parse is instructed to be lenient and the digit count is not two, it is * treated as an absolute weekyear. With lenient parsing, specifying a positive * or negative sign before the weekyear also makes it absolute. * * @param pivot pivot weekyear to use when parsing * @param lenientParse when true, if digit count is not two, it is treated * as an absolute weekyear * @return this DateTimeFormatterBuilder, for chaining * @since 1.1 */ public DateTimeFormatterBuilder appendTwoDigitWeekyear(int pivot, boolean lenientParse) { return append0(new TwoDigitYear(DateTimeFieldType.weekyear(), pivot, lenientParse)); } /** * Instructs the printer to emit a numeric yearOfEra field. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to parse, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendYearOfEra(int minDigits, int maxDigits) { return appendDecimal(DateTimeFieldType.yearOfEra(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric year of century field. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to parse, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendYearOfCentury(int minDigits, int maxDigits) { return appendDecimal(DateTimeFieldType.yearOfCentury(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric century of era field. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to parse, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendCenturyOfEra(int minDigits, int maxDigits) { return appendSignedDecimal(DateTimeFieldType.centuryOfEra(), minDigits, maxDigits); } /** * Instructs the printer to emit a locale-specific AM/PM text, and the * parser to expect it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendHalfdayOfDayText() { return appendText(DateTimeFieldType.halfdayOfDay()); } /** * Instructs the printer to emit a locale-specific dayOfWeek text. The * parser will accept a long or short dayOfWeek text, case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfWeekText() { return appendText(DateTimeFieldType.dayOfWeek()); } /** * Instructs the printer to emit a short locale-specific dayOfWeek * text. The parser will accept a long or short dayOfWeek text, * case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfWeekShortText() { return appendShortText(DateTimeFieldType.dayOfWeek()); } /** * Instructs the printer to emit a short locale-specific monthOfYear * text. The parser will accept a long or short monthOfYear text, * case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMonthOfYearText() { return appendText(DateTimeFieldType.monthOfYear()); } /** * Instructs the printer to emit a locale-specific monthOfYear text. The * parser will accept a long or short monthOfYear text, case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMonthOfYearShortText() { return appendShortText(DateTimeFieldType.monthOfYear()); } /** * Instructs the printer to emit a locale-specific era text (BC/AD), and * the parser to expect it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendEraText() { return appendText(DateTimeFieldType.era()); } /** * Instructs the printer to emit a locale-specific time zone name. * Using this method prevents parsing, because time zone names are not unique. * See {@link #appendTimeZoneName(Map)}. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneName() { return append0(new TimeZoneName(TimeZoneName.LONG_NAME, null), null); } /** * Instructs the printer to emit a locale-specific time zone name, providing a lookup for parsing. * Time zone names are not unique, thus the API forces you to supply the lookup. * The names are searched in the order of the map, thus it is strongly recommended * to use a {@code LinkedHashMap} or similar. * * @param parseLookup the table of names, not null * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneName(Map parseLookup) { TimeZoneName pp = new TimeZoneName(TimeZoneName.LONG_NAME, parseLookup); return append0(pp, pp); } /** * Instructs the printer to emit a short locale-specific time zone name. * Using this method prevents parsing, because time zone names are not unique. * See {@link #appendTimeZoneShortName(Map)}. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneShortName() { return append0(new TimeZoneName(TimeZoneName.SHORT_NAME, null), null); } /** * Instructs the printer to emit a short locale-specific time zone * name, providing a lookup for parsing. * Time zone names are not unique, thus the API forces you to supply the lookup. * The names are searched in the order of the map, thus it is strongly recommended * to use a {@code LinkedHashMap} or similar. * * @param parseLookup the table of names, null to use the {@link DateTimeUtils#getDefaultTimeZoneNames() default names} * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneShortName(Map parseLookup) { TimeZoneName pp = new TimeZoneName(TimeZoneName.SHORT_NAME, parseLookup); return append0(pp, pp); } /** * Instructs the printer to emit the identifier of the time zone. * From version 2.0, this field can be parsed. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneId() { return append0(TimeZoneId.INSTANCE, TimeZoneId.INSTANCE); } /** * Instructs the printer to emit text and numbers to display time zone * offset from UTC. A parser will use the parsed time zone offset to adjust * the datetime. *

* If zero offset text is supplied, then it will be printed when the zone is zero. * During parsing, either the zero offset text, or the offset will be parsed. * * @param zeroOffsetText the text to use if time zone offset is zero. If * null, offset is always shown. * @param showSeparators if true, prints ':' separator before minute and * second field and prints '.' separator before fraction field. * @param minFields minimum number of fields to print, stopping when no * more precision is required. 1=hours, 2=minutes, 3=seconds, 4=fraction * @param maxFields maximum number of fields to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneOffset( String zeroOffsetText, boolean showSeparators, int minFields, int maxFields) { return append0(new TimeZoneOffset (zeroOffsetText, zeroOffsetText, showSeparators, minFields, maxFields)); } /** * Instructs the printer to emit text and numbers to display time zone * offset from UTC. A parser will use the parsed time zone offset to adjust * the datetime. *

* If zero offset print text is supplied, then it will be printed when the zone is zero. * If zero offset parse text is supplied, then either it or the offset will be parsed. * * @param zeroOffsetPrintText the text to print if time zone offset is zero. If * null, offset is always shown. * @param zeroOffsetParseText the text to optionally parse to indicate that the time * zone offset is zero. If null, then always use the offset. * @param showSeparators if true, prints ':' separator before minute and * second field and prints '.' separator before fraction field. * @param minFields minimum number of fields to print, stopping when no * more precision is required. 1=hours, 2=minutes, 3=seconds, 4=fraction * @param maxFields maximum number of fields to print * @return this DateTimeFormatterBuilder, for chaining * @since 2.0 */ public DateTimeFormatterBuilder appendTimeZoneOffset( String zeroOffsetPrintText, String zeroOffsetParseText, boolean showSeparators, int minFields, int maxFields) { return append0(new TimeZoneOffset (zeroOffsetPrintText, zeroOffsetParseText, showSeparators, minFields, maxFields)); } //----------------------------------------------------------------------- /** * Calls upon {@link DateTimeFormat} to parse the pattern and append the * results into this builder. * * @param pattern pattern specification * @throws IllegalArgumentException if the pattern is invalid * @see DateTimeFormat */ public DateTimeFormatterBuilder appendPattern(String pattern) { DateTimeFormat.appendPatternTo(this, pattern); return this; } //----------------------------------------------------------------------- private Object getFormatter() { Object f = iFormatter; if (f == null) { if (iElementPairs.size() == 2) { Object printer = iElementPairs.get(0); Object parser = iElementPairs.get(1); if (printer != null) { if (printer == parser || parser == null) { f = printer; } } else { f = parser; } } if (f == null) { f = new Composite(iElementPairs); } iFormatter = f; } return f; } private boolean isPrinter(Object f) { if (f instanceof DateTimePrinter) { if (f instanceof Composite) { return ((Composite)f).isPrinter(); } return true; } return false; } private boolean isParser(Object f) { if (f instanceof DateTimeParser) { if (f instanceof Composite) { return ((Composite)f).isParser(); } return true; } return false; } private boolean isFormatter(Object f) { return (isPrinter(f) || isParser(f)); } static void appendUnknownString(StringBuffer buf, int len) { for (int i = len; --i >= 0;) { buf.append('\ufffd'); } } static void printUnknownString(Writer out, int len) throws IOException { for (int i = len; --i >= 0;) { out.write('\ufffd'); } } //----------------------------------------------------------------------- static class CharacterLiteral implements DateTimePrinter, DateTimeParser { private final char iValue; CharacterLiteral(char value) { super(); iValue = value; } public int estimatePrintedLength() { return 1; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(iValue); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(iValue); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { buf.append(iValue); } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { out.write(iValue); } public int estimateParsedLength() { return 1; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { if (position >= text.length()) { return ~position; } char a = text.charAt(position); char b = iValue; if (a != b) { a = Character.toUpperCase(a); b = Character.toUpperCase(b); if (a != b) { a = Character.toLowerCase(a); b = Character.toLowerCase(b); if (a != b) { return ~position; } } } return position + 1; } } //----------------------------------------------------------------------- static class StringLiteral implements DateTimePrinter, DateTimeParser { private final String iValue; StringLiteral(String value) { super(); iValue = value; } public int estimatePrintedLength() { return iValue.length(); } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(iValue); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(iValue); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { buf.append(iValue); } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { out.write(iValue); } public int estimateParsedLength() { return iValue.length(); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { if (text.regionMatches(true, position, iValue, 0, iValue.length())) { return position + iValue.length(); } return ~position; } } //----------------------------------------------------------------------- static abstract class NumberFormatter implements DateTimePrinter, DateTimeParser { protected final DateTimeFieldType iFieldType; protected final int iMaxParsedDigits; protected final boolean iSigned; NumberFormatter(DateTimeFieldType fieldType, int maxParsedDigits, boolean signed) { super(); iFieldType = fieldType; iMaxParsedDigits = maxParsedDigits; iSigned = signed; } public int estimateParsedLength() { return iMaxParsedDigits; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int limit = Math.min(iMaxParsedDigits, text.length() - position); boolean negative = false; int length = 0; while (length < limit) { char c = text.charAt(position + length); if (length == 0 && (c == '-' || c == '+') && iSigned) { negative = c == '-'; // Next character must be a digit. if (length + 1 >= limit || (c = text.charAt(position + length + 1)) < '0' || c > '9') { break; } if (negative) { length++; } else { // Skip the '+' for parseInt to succeed. position++; } // Expand the limit to disregard the sign character. limit = Math.min(limit + 1, text.length() - position); continue; } if (c < '0' || c > '9') { break; } length++; } if (length == 0) { return ~position; } int value; if (length >= 9) { // Since value may exceed integer limits, use stock parser // which checks for this. value = Integer.parseInt(text.substring(position, position += length)); } else { int i = position; if (negative) { i++; } try { value = text.charAt(i++) - '0'; } catch (StringIndexOutOfBoundsException e) { return ~position; } position += length; while (i < position) { value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0'; } if (negative) { value = -value; } } bucket.saveField(iFieldType, value); return position; } } //----------------------------------------------------------------------- static class UnpaddedNumber extends NumberFormatter { protected UnpaddedNumber(DateTimeFieldType fieldType, int maxParsedDigits, boolean signed) { super(fieldType, maxParsedDigits, signed); } public int estimatePrintedLength() { return iMaxParsedDigits; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.appendUnpaddedInteger(buf, field.get(instant)); } catch (RuntimeException e) { buf.append('\ufffd'); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.writeUnpaddedInteger(out, field.get(instant)); } catch (RuntimeException e) { out.write('\ufffd'); } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { if (partial.isSupported(iFieldType)) { try { FormatUtils.appendUnpaddedInteger(buf, partial.get(iFieldType)); } catch (RuntimeException e) { buf.append('\ufffd'); } } else { buf.append('\ufffd'); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { if (partial.isSupported(iFieldType)) { try { FormatUtils.writeUnpaddedInteger(out, partial.get(iFieldType)); } catch (RuntimeException e) { out.write('\ufffd'); } } else { out.write('\ufffd'); } } } //----------------------------------------------------------------------- static class PaddedNumber extends NumberFormatter { protected final int iMinPrintedDigits; protected PaddedNumber(DateTimeFieldType fieldType, int maxParsedDigits, boolean signed, int minPrintedDigits) { super(fieldType, maxParsedDigits, signed); iMinPrintedDigits = minPrintedDigits; } public int estimatePrintedLength() { return iMaxParsedDigits; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.appendPaddedInteger(buf, field.get(instant), iMinPrintedDigits); } catch (RuntimeException e) { appendUnknownString(buf, iMinPrintedDigits); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.writePaddedInteger(out, field.get(instant), iMinPrintedDigits); } catch (RuntimeException e) { printUnknownString(out, iMinPrintedDigits); } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { if (partial.isSupported(iFieldType)) { try { FormatUtils.appendPaddedInteger(buf, partial.get(iFieldType), iMinPrintedDigits); } catch (RuntimeException e) { appendUnknownString(buf, iMinPrintedDigits); } } else { appendUnknownString(buf, iMinPrintedDigits); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { if (partial.isSupported(iFieldType)) { try { FormatUtils.writePaddedInteger(out, partial.get(iFieldType), iMinPrintedDigits); } catch (RuntimeException e) { printUnknownString(out, iMinPrintedDigits); } } else { printUnknownString(out, iMinPrintedDigits); } } } //----------------------------------------------------------------------- static class FixedNumber extends PaddedNumber { protected FixedNumber(DateTimeFieldType fieldType, int numDigits, boolean signed) { super(fieldType, numDigits, signed, numDigits); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int newPos = super.parseInto(bucket, text, position); if (newPos < 0) { return newPos; } int expectedPos = position + iMaxParsedDigits; if (newPos != expectedPos) { if (iSigned) { char c = text.charAt(position); if (c == '-' || c == '+') { expectedPos++; } } if (newPos > expectedPos) { // The failure is at the position of the first extra digit. return ~(expectedPos + 1); } else if (newPos < expectedPos) { // The failure is at the position where the next digit should be. return ~newPos; } } return newPos; } } //----------------------------------------------------------------------- static class TwoDigitYear implements DateTimePrinter, DateTimeParser { /** The field to print/parse. */ private final DateTimeFieldType iType; /** The pivot year. */ private final int iPivot; private final boolean iLenientParse; TwoDigitYear(DateTimeFieldType type, int pivot, boolean lenientParse) { super(); iType = type; iPivot = pivot; iLenientParse = lenientParse; } public int estimateParsedLength() { return iLenientParse ? 4 : 2; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int limit = text.length() - position; if (!iLenientParse) { limit = Math.min(2, limit); if (limit < 2) { return ~position; } } else { boolean hasSignChar = false; boolean negative = false; int length = 0; while (length < limit) { char c = text.charAt(position + length); if (length == 0 && (c == '-' || c == '+')) { hasSignChar = true; negative = c == '-'; if (negative) { length++; } else { // Skip the '+' for parseInt to succeed. position++; limit--; } continue; } if (c < '0' || c > '9') { break; } length++; } if (length == 0) { return ~position; } if (hasSignChar || length != 2) { int value; if (length >= 9) { // Since value may exceed integer limits, use stock // parser which checks for this. value = Integer.parseInt(text.substring(position, position += length)); } else { int i = position; if (negative) { i++; } try { value = text.charAt(i++) - '0'; } catch (StringIndexOutOfBoundsException e) { return ~position; } position += length; while (i < position) { value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0'; } if (negative) { value = -value; } } bucket.saveField(iType, value); return position; } } int year; char c = text.charAt(position); if (c < '0' || c > '9') { return ~position; } year = c - '0'; c = text.charAt(position + 1); if (c < '0' || c > '9') { return ~position; } year = ((year << 3) + (year << 1)) + c - '0'; int pivot = iPivot; // If the bucket pivot year is non-null, use that when parsing if (bucket.getPivotYear() != null) { pivot = bucket.getPivotYear().intValue(); } int low = pivot - 50; int t; if (low >= 0) { t = low % 100; } else { t = 99 + ((low + 1) % 100); } year += low + ((year < t) ? 100 : 0) - t; bucket.saveField(iType, year); return position + 2; } public int estimatePrintedLength() { return 2; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { int year = getTwoDigitYear(instant, chrono); if (year < 0) { buf.append('\ufffd'); buf.append('\ufffd'); } else { FormatUtils.appendPaddedInteger(buf, year, 2); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { int year = getTwoDigitYear(instant, chrono); if (year < 0) { out.write('\ufffd'); out.write('\ufffd'); } else { FormatUtils.writePaddedInteger(out, year, 2); } } private int getTwoDigitYear(long instant, Chronology chrono) { try { int year = iType.getField(chrono).get(instant); if (year < 0) { year = -year; } return year % 100; } catch (RuntimeException e) { return -1; } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { int year = getTwoDigitYear(partial); if (year < 0) { buf.append('\ufffd'); buf.append('\ufffd'); } else { FormatUtils.appendPaddedInteger(buf, year, 2); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { int year = getTwoDigitYear(partial); if (year < 0) { out.write('\ufffd'); out.write('\ufffd'); } else { FormatUtils.writePaddedInteger(out, year, 2); } } private int getTwoDigitYear(ReadablePartial partial) { if (partial.isSupported(iType)) { try { int year = partial.get(iType); if (year < 0) { year = -year; } return year % 100; } catch (RuntimeException e) {} } return -1; } } //----------------------------------------------------------------------- static class TextField implements DateTimePrinter, DateTimeParser { private static Map> cParseCache = new HashMap>(); private final DateTimeFieldType iFieldType; private final boolean iShort; TextField(DateTimeFieldType fieldType, boolean isShort) { super(); iFieldType = fieldType; iShort = isShort; } public int estimatePrintedLength() { return iShort ? 6 : 20; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { buf.append(print(instant, chrono, locale)); } catch (RuntimeException e) { buf.append('\ufffd'); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { try { out.write(print(instant, chrono, locale)); } catch (RuntimeException e) { out.write('\ufffd'); } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { try { buf.append(print(partial, locale)); } catch (RuntimeException e) { buf.append('\ufffd'); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { try { out.write(print(partial, locale)); } catch (RuntimeException e) { out.write('\ufffd'); } } private String print(long instant, Chronology chrono, Locale locale) { DateTimeField field = iFieldType.getField(chrono); if (iShort) { return field.getAsShortText(instant, locale); } else { return field.getAsText(instant, locale); } } private String print(ReadablePartial partial, Locale locale) { if (partial.isSupported(iFieldType)) { DateTimeField field = iFieldType.getField(partial.getChronology()); if (iShort) { return field.getAsShortText(partial, locale); } else { return field.getAsText(partial, locale); } } else { return "\ufffd"; } } public int estimateParsedLength() { return estimatePrintedLength(); } @SuppressWarnings("unchecked") public int parseInto(DateTimeParserBucket bucket, String text, int position) { Locale locale = bucket.getLocale(); // handle languages which might have non ASCII A-Z or punctuation // bug 1788282 Set validValues = null; int maxLength = 0; synchronized (cParseCache) { Map innerMap = cParseCache.get(locale); if (innerMap == null) { innerMap = new HashMap(); cParseCache.put(locale, innerMap); } Object[] array = innerMap.get(iFieldType); if (array == null) { validValues = new HashSet(32); MutableDateTime dt = new MutableDateTime(0L, DateTimeZone.UTC); Property property = dt.property(iFieldType); int min = property.getMinimumValueOverall(); int max = property.getMaximumValueOverall(); if (max - min > 32) { // protect against invalid fields return ~position; } maxLength = property.getMaximumTextLength(locale); for (int i = min; i <= max; i++) { property.set(i); validValues.add(property.getAsShortText(locale)); validValues.add(property.getAsShortText(locale).toLowerCase(locale)); validValues.add(property.getAsShortText(locale).toUpperCase(locale)); validValues.add(property.getAsText(locale)); validValues.add(property.getAsText(locale).toLowerCase(locale)); validValues.add(property.getAsText(locale).toUpperCase(locale)); } if ("en".equals(locale.getLanguage()) && iFieldType == DateTimeFieldType.era()) { // hack to support for parsing "BCE" and "CE" if the language is English validValues.add("BCE"); validValues.add("bce"); validValues.add("CE"); validValues.add("ce"); maxLength = 3; } array = new Object[] {validValues, Integer.valueOf(maxLength)}; innerMap.put(iFieldType, array); } else { validValues = (Set) array[0]; maxLength = ((Integer) array[1]).intValue(); } } // match the longest string first using our knowledge of the max length int limit = Math.min(text.length(), position + maxLength); for (int i = limit; i > position; i--) { String match = text.substring(position, i); if (validValues.contains(match)) { bucket.saveField(iFieldType, match, locale); return i; } } return ~position; } } //----------------------------------------------------------------------- static class Fraction implements DateTimePrinter, DateTimeParser { private final DateTimeFieldType iFieldType; protected int iMinDigits; protected int iMaxDigits; protected Fraction(DateTimeFieldType fieldType, int minDigits, int maxDigits) { super(); iFieldType = fieldType; // Limit the precision requirements. if (maxDigits > 18) { maxDigits = 18; } iMinDigits = minDigits; iMaxDigits = maxDigits; } public int estimatePrintedLength() { return iMaxDigits; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { printTo(buf, null, instant, chrono); } catch (IOException e) { // Not gonna happen. } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { printTo(null, out, instant, chrono); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // removed check whether field is supported, as input field is typically // secondOfDay which is unsupported by TimeOfDay long millis = partial.getChronology().set(partial, 0L); try { printTo(buf, null, millis, partial.getChronology()); } catch (IOException e) { // Not gonna happen. } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // removed check whether field is supported, as input field is typically // secondOfDay which is unsupported by TimeOfDay long millis = partial.getChronology().set(partial, 0L); printTo(null, out, millis, partial.getChronology()); } protected void printTo(StringBuffer buf, Writer out, long instant, Chronology chrono) throws IOException { DateTimeField field = iFieldType.getField(chrono); int minDigits = iMinDigits; long fraction; try { fraction = field.remainder(instant); } catch (RuntimeException e) { if (buf != null) { appendUnknownString(buf, minDigits); } else { printUnknownString(out, minDigits); } return; } if (fraction == 0) { if (buf != null) { while (--minDigits >= 0) { buf.append('0'); } } else { while (--minDigits >= 0) { out.write('0'); } } return; } String str; long[] fractionData = getFractionData(fraction, field); long scaled = fractionData[0]; int maxDigits = (int) fractionData[1]; if ((scaled & 0x7fffffff) == scaled) { str = Integer.toString((int) scaled); } else { str = Long.toString(scaled); } int length = str.length(); int digits = maxDigits; while (length < digits) { if (buf != null) { buf.append('0'); } else { out.write('0'); } minDigits--; digits--; } if (minDigits < digits) { // Chop off as many trailing zero digits as necessary. while (minDigits < digits) { if (length <= 1 || str.charAt(length - 1) != '0') { break; } digits--; length--; } if (length < str.length()) { if (buf != null) { for (int i=0; i '9') { break; } length++; long nn = n / 10; value += (c - '0') * nn; n = nn; } value /= 10; if (length == 0) { return ~position; } if (value > Integer.MAX_VALUE) { return ~position; } DateTimeField parseField = new PreciseDateTimeField( DateTimeFieldType.millisOfSecond(), MillisDurationField.INSTANCE, field.getDurationField()); bucket.saveField(parseField, (int) value); return position + length; } } //----------------------------------------------------------------------- static class TimeZoneOffset implements DateTimePrinter, DateTimeParser { private final String iZeroOffsetPrintText; private final String iZeroOffsetParseText; private final boolean iShowSeparators; private final int iMinFields; private final int iMaxFields; TimeZoneOffset(String zeroOffsetPrintText, String zeroOffsetParseText, boolean showSeparators, int minFields, int maxFields) { super(); iZeroOffsetPrintText = zeroOffsetPrintText; iZeroOffsetParseText = zeroOffsetParseText; iShowSeparators = showSeparators; if (minFields <= 0 || maxFields < minFields) { throw new IllegalArgumentException(); } if (minFields > 4) { minFields = 4; maxFields = 4; } iMinFields = minFields; iMaxFields = maxFields; } public int estimatePrintedLength() { int est = 1 + iMinFields << 1; if (iShowSeparators) { est += iMinFields - 1; } if (iZeroOffsetPrintText != null && iZeroOffsetPrintText.length() > est) { est = iZeroOffsetPrintText.length(); } return est; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { if (displayZone == null) { return; // no zone } if (displayOffset == 0 && iZeroOffsetPrintText != null) { buf.append(iZeroOffsetPrintText); return; } if (displayOffset >= 0) { buf.append('+'); } else { buf.append('-'); displayOffset = -displayOffset; } int hours = displayOffset / DateTimeConstants.MILLIS_PER_HOUR; FormatUtils.appendPaddedInteger(buf, hours, 2); if (iMaxFields == 1) { return; } displayOffset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR; if (displayOffset == 0 && iMinFields <= 1) { return; } int minutes = displayOffset / DateTimeConstants.MILLIS_PER_MINUTE; if (iShowSeparators) { buf.append(':'); } FormatUtils.appendPaddedInteger(buf, minutes, 2); if (iMaxFields == 2) { return; } displayOffset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; if (displayOffset == 0 && iMinFields <= 2) { return; } int seconds = displayOffset / DateTimeConstants.MILLIS_PER_SECOND; if (iShowSeparators) { buf.append(':'); } FormatUtils.appendPaddedInteger(buf, seconds, 2); if (iMaxFields == 3) { return; } displayOffset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; if (displayOffset == 0 && iMinFields <= 3) { return; } if (iShowSeparators) { buf.append('.'); } FormatUtils.appendPaddedInteger(buf, displayOffset, 3); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { if (displayZone == null) { return; // no zone } if (displayOffset == 0 && iZeroOffsetPrintText != null) { out.write(iZeroOffsetPrintText); return; } if (displayOffset >= 0) { out.write('+'); } else { out.write('-'); displayOffset = -displayOffset; } int hours = displayOffset / DateTimeConstants.MILLIS_PER_HOUR; FormatUtils.writePaddedInteger(out, hours, 2); if (iMaxFields == 1) { return; } displayOffset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR; if (displayOffset == 0 && iMinFields == 1) { return; } int minutes = displayOffset / DateTimeConstants.MILLIS_PER_MINUTE; if (iShowSeparators) { out.write(':'); } FormatUtils.writePaddedInteger(out, minutes, 2); if (iMaxFields == 2) { return; } displayOffset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; if (displayOffset == 0 && iMinFields == 2) { return; } int seconds = displayOffset / DateTimeConstants.MILLIS_PER_SECOND; if (iShowSeparators) { out.write(':'); } FormatUtils.writePaddedInteger(out, seconds, 2); if (iMaxFields == 3) { return; } displayOffset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; if (displayOffset == 0 && iMinFields == 3) { return; } if (iShowSeparators) { out.write('.'); } FormatUtils.writePaddedInteger(out, displayOffset, 3); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // no zone info } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // no zone info } public int estimateParsedLength() { return estimatePrintedLength(); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int limit = text.length() - position; zeroOffset: if (iZeroOffsetParseText != null) { if (iZeroOffsetParseText.length() == 0) { // Peek ahead, looking for sign character. if (limit > 0) { char c = text.charAt(position); if (c == '-' || c == '+') { break zeroOffset; } } bucket.setOffset(Integer.valueOf(0)); return position; } if (text.regionMatches(true, position, iZeroOffsetParseText, 0, iZeroOffsetParseText.length())) { bucket.setOffset(Integer.valueOf(0)); return position + iZeroOffsetParseText.length(); } } // Format to expect is sign character followed by at least one digit. if (limit <= 1) { return ~position; } boolean negative; char c = text.charAt(position); if (c == '-') { negative = true; } else if (c == '+') { negative = false; } else { return ~position; } limit--; position++; // Format following sign is one of: // // hh // hhmm // hhmmss // hhmmssSSS // hh:mm // hh:mm:ss // hh:mm:ss.SSS // First parse hours. if (digitCount(text, position, 2) < 2) { // Need two digits for hour. return ~position; } int offset; int hours = FormatUtils.parseTwoDigits(text, position); if (hours > 23) { return ~position; } offset = hours * DateTimeConstants.MILLIS_PER_HOUR; limit -= 2; position += 2; parse: { // Need to decide now if separators are expected or parsing // stops at hour field. if (limit <= 0) { break parse; } boolean expectSeparators; c = text.charAt(position); if (c == ':') { expectSeparators = true; limit--; position++; } else if (c >= '0' && c <= '9') { expectSeparators = false; } else { break parse; } // Proceed to parse minutes. int count = digitCount(text, position, 2); if (count == 0 && !expectSeparators) { break parse; } else if (count < 2) { // Need two digits for minute. return ~position; } int minutes = FormatUtils.parseTwoDigits(text, position); if (minutes > 59) { return ~position; } offset += minutes * DateTimeConstants.MILLIS_PER_MINUTE; limit -= 2; position += 2; // Proceed to parse seconds. if (limit <= 0) { break parse; } if (expectSeparators) { if (text.charAt(position) != ':') { break parse; } limit--; position++; } count = digitCount(text, position, 2); if (count == 0 && !expectSeparators) { break parse; } else if (count < 2) { // Need two digits for second. return ~position; } int seconds = FormatUtils.parseTwoDigits(text, position); if (seconds > 59) { return ~position; } offset += seconds * DateTimeConstants.MILLIS_PER_SECOND; limit -= 2; position += 2; // Proceed to parse fraction of second. if (limit <= 0) { break parse; } if (expectSeparators) { if (text.charAt(position) != '.' && text.charAt(position) != ',') { break parse; } limit--; position++; } count = digitCount(text, position, 3); if (count == 0 && !expectSeparators) { break parse; } else if (count < 1) { // Need at least one digit for fraction of second. return ~position; } offset += (text.charAt(position++) - '0') * 100; if (count > 1) { offset += (text.charAt(position++) - '0') * 10; if (count > 2) { offset += text.charAt(position++) - '0'; } } } bucket.setOffset(Integer.valueOf(negative ? -offset : offset)); return position; } /** * Returns actual amount of digits to parse, but no more than original * 'amount' parameter. */ private int digitCount(String text, int position, int amount) { int limit = Math.min(text.length() - position, amount); amount = 0; for (; limit > 0; limit--) { char c = text.charAt(position + amount); if (c < '0' || c > '9') { break; } amount++; } return amount; } } //----------------------------------------------------------------------- static class TimeZoneName implements DateTimePrinter, DateTimeParser { static final int LONG_NAME = 0; static final int SHORT_NAME = 1; private final Map iParseLookup; private final int iType; TimeZoneName(int type, Map parseLookup) { super(); iType = type; iParseLookup = parseLookup; } public int estimatePrintedLength() { return (iType == SHORT_NAME ? 4 : 20); } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(print(instant - displayOffset, displayZone, locale)); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(print(instant - displayOffset, displayZone, locale)); } private String print(long instant, DateTimeZone displayZone, Locale locale) { if (displayZone == null) { return ""; // no zone } switch (iType) { case LONG_NAME: return displayZone.getName(instant, locale); case SHORT_NAME: return displayZone.getShortName(instant, locale); } return ""; } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // no zone info } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // no zone info } public int estimateParsedLength() { return (iType == SHORT_NAME ? 4 : 20); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { Map parseLookup = iParseLookup; parseLookup = (parseLookup != null ? parseLookup : DateTimeUtils.getDefaultTimeZoneNames()); String str = text.substring(position); String matched = null; for (String name : parseLookup.keySet()) { if (str.startsWith(name)) { if (matched == null || name.length() > matched.length()) { matched = name; } } } if (matched != null) { bucket.setZone(parseLookup.get(matched)); return position + matched.length(); } return ~position; } } //----------------------------------------------------------------------- static enum TimeZoneId implements DateTimePrinter, DateTimeParser { INSTANCE; static final Set ALL_IDS = DateTimeZone.getAvailableIDs(); static final int MAX_LENGTH; static { int max = 0; for (String id : ALL_IDS) { max = Math.max(max, id.length()); } MAX_LENGTH = max; } public int estimatePrintedLength() { return MAX_LENGTH; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(displayZone != null ? displayZone.getID() : ""); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(displayZone != null ? displayZone.getID() : ""); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // no zone info } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // no zone info } public int estimateParsedLength() { return MAX_LENGTH; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { String str = text.substring(position); String best = null; for (String id : ALL_IDS) { if (str.startsWith(id)) { if (best == null || id.length() > best.length()) { best = id; } } } if (best != null) { bucket.setZone(DateTimeZone.forID(best)); return position + best.length(); } return ~position; } } //----------------------------------------------------------------------- static class Composite implements DateTimePrinter, DateTimeParser { private final DateTimePrinter[] iPrinters; private final DateTimeParser[] iParsers; private final int iPrintedLengthEstimate; private final int iParsedLengthEstimate; Composite(List elementPairs) { super(); List printerList = new ArrayList(); List parserList = new ArrayList(); decompose(elementPairs, printerList, parserList); if (printerList.contains(null) || printerList.isEmpty()) { iPrinters = null; iPrintedLengthEstimate = 0; } else { int size = printerList.size(); iPrinters = new DateTimePrinter[size]; int printEst = 0; for (int i=0; i= 0; i++) { position = elements[i].parseInto(bucket, text, position); } return position; } boolean isPrinter() { return iPrinters != null; } boolean isParser() { return iParsers != null; } /** * Processes the element pairs, putting results into the given printer * and parser lists. */ private void decompose(List elementPairs, List printerList, List parserList) { int size = elementPairs.size(); for (int i=0; i list, Object[] array) { if (array != null) { for (int i=0; i=0 ;) { DateTimeParser parser = parsers[i]; if (parser != null) { int len = parser.estimateParsedLength(); if (len > est) { est = len; } } } iParsedLengthEstimate = est; } public int estimateParsedLength() { return iParsedLengthEstimate; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { DateTimeParser[] parsers = iParsers; int length = parsers.length; final Object originalState = bucket.saveState(); boolean isOptional = false; int bestValidPos = position; Object bestValidState = null; int bestInvalidPos = position; for (int i=0; i= position) { if (parsePos > bestValidPos) { if (parsePos >= text.length() || (i + 1) >= length || parsers[i + 1] == null) { // Completely parsed text or no more parsers to // check. Skip the rest. return parsePos; } bestValidPos = parsePos; bestValidState = bucket.saveState(); } } else { if (parsePos < 0) { parsePos = ~parsePos; if (parsePos > bestInvalidPos) { bestInvalidPos = parsePos; } } } bucket.restoreState(originalState); } if (bestValidPos > position || (bestValidPos == position && isOptional)) { // Restore the state to the best valid parse. if (bestValidState != null) { bucket.restoreState(bestValidState); } return bestValidPos; } return ~bestInvalidPos; } } } joda-time-2.3/src/main/java/org/joda/time/format/DateTimeFormat.java0000644000175000017500000010146412200502764024661 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.IOException; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.ReadablePartial; /** * Factory that creates instances of DateTimeFormatter from patterns and styles. *

* Datetime formatting is performed by the {@link DateTimeFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link ISODateTimeFormat} and {@link DateTimeFormatterBuilder}. *

* This class provides two types of factory: *

    *
  • {@link #forPattern(String) Pattern} provides a DateTimeFormatter based on * a pattern string that is mostly compatible with the JDK date patterns. *
  • {@link #forStyle(String) Style} provides a DateTimeFormatter based on a * two character style, representing short, medium, long and full. *
*

* For example, to use a patterm: *

 * DateTime dt = new DateTime();
 * DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM, yyyy");
 * String str = fmt.print(dt);
 * 
* * The pattern syntax is mostly compatible with java.text.SimpleDateFormat - * time zone names cannot be parsed and a few more symbols are supported. * All ASCII letters are reserved as pattern letters, which are defined as follows: *
*
 * Symbol  Meaning                      Presentation  Examples
 * ------  -------                      ------------  -------
 * G       era                          text          AD
 * C       century of era (>=0)         number        20
 * Y       year of era (>=0)            year          1996
 *
 * x       weekyear                     year          1996
 * w       week of weekyear             number        27
 * e       day of week                  number        2
 * E       day of week                  text          Tuesday; Tue
 *
 * y       year                         year          1996
 * D       day of year                  number        189
 * M       month of year                month         July; Jul; 07
 * d       day of month                 number        10
 *
 * a       halfday of day               text          PM
 * K       hour of halfday (0~11)       number        0
 * h       clockhour of halfday (1~12)  number        12
 *
 * H       hour of day (0~23)           number        0
 * k       clockhour of day (1~24)      number        24
 * m       minute of hour               number        30
 * s       second of minute             number        55
 * S       fraction of second           number        978
 *
 * z       time zone                    text          Pacific Standard Time; PST
 * Z       time zone offset/id          zone          -0800; -08:00; America/Los_Angeles
 *
 * '       escape for text              delimiter
 * ''      single quote                 literal       '
 * 
*
* The count of pattern letters determine the format. *

* Text: If the number of pattern letters is 4 or more, * the full form is used; otherwise a short or abbreviated form is used if * available. *

* Number: The minimum number of digits. Shorter numbers * are zero-padded to this amount. *

* Year: Numeric presentation for year and weekyear fields * are handled specially. For example, if the count of 'y' is 2, the year * will be displayed as the zero-based year of the century, which is two * digits. *

* Month: 3 or over, use text, otherwise use number. *

* Zone: 'Z' outputs offset without a colon, 'ZZ' outputs * the offset with a colon, 'ZZZ' or more outputs the zone id. *

* Zone names: Time zone names ('z') cannot be parsed. *

* Any characters in the pattern that are not in the ranges of ['a'..'z'] * and ['A'..'Z'] will be treated as quoted text. For instance, characters * like ':', '.', ' ', '#' and '?' will appear in the resulting time text * even they are not embraced within single quotes. *

* DateTimeFormat is thread-safe and immutable, and the formatters it returns * are as well. * * @author Brian S O'Neill * @author Maxim Zhao * @since 1.0 * @see ISODateTimeFormat * @see DateTimeFormatterBuilder */ public class DateTimeFormat { /** Style constant for FULL. */ static final int FULL = 0; // DateFormat.FULL /** Style constant for LONG. */ static final int LONG = 1; // DateFormat.LONG /** Style constant for MEDIUM. */ static final int MEDIUM = 2; // DateFormat.MEDIUM /** Style constant for SHORT. */ static final int SHORT = 3; // DateFormat.SHORT /** Style constant for NONE. */ static final int NONE = 4; /** Type constant for DATE only. */ static final int DATE = 0; /** Type constant for TIME only. */ static final int TIME = 1; /** Type constant for DATETIME. */ static final int DATETIME = 2; /** Maximum size of the pattern cache. */ private static final int PATTERN_CACHE_SIZE = 500; /** Maps patterns to formatters via LRU, patterns don't vary by locale. */ private static final Map PATTERN_CACHE = new LinkedHashMap(7) { private static final long serialVersionUID = 23L; @Override protected boolean removeEldestEntry(final Map.Entry eldest) { return size() > PATTERN_CACHE_SIZE; }; }; /** Maps patterns to formatters, patterns don't vary by locale. */ private static final DateTimeFormatter[] STYLE_CACHE = new DateTimeFormatter[25]; //----------------------------------------------------------------------- /** * Factory to create a formatter from a pattern string. * The pattern string is described above in the class level javadoc. * It is very similar to SimpleDateFormat patterns. *

* The format may contain locale specific output, and this will change as * you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * For example: *

     * DateTimeFormat.forPattern(pattern).withLocale(Locale.FRANCE).print(dt);
     * 
* * @param pattern pattern specification * @return the formatter * @throws IllegalArgumentException if the pattern is invalid */ public static DateTimeFormatter forPattern(String pattern) { return createFormatterForPattern(pattern); } /** * Factory to create a format from a two character style pattern. *

* The first character is the date style, and the second character is the * time style. Specify a character of 'S' for short style, 'M' for medium, * 'L' for long, and 'F' for full. * A date or time may be ommitted by specifying a style character '-'. *

* The returned formatter will dynamically adjust to the locale that * the print/parse takes place in. Thus you just call * {@link DateTimeFormatter#withLocale(Locale)} and the Short/Medium/Long/Full * style for that locale will be output. For example: *

     * DateTimeFormat.forStyle(style).withLocale(Locale.FRANCE).print(dt);
     * 
* * @param style two characters from the set {"S", "M", "L", "F", "-"} * @return the formatter * @throws IllegalArgumentException if the style is invalid */ public static DateTimeFormatter forStyle(String style) { return createFormatterForStyle(style); } /** * Returns the pattern used by a particular style and locale. *

* The first character is the date style, and the second character is the * time style. Specify a character of 'S' for short style, 'M' for medium, * 'L' for long, and 'F' for full. * A date or time may be ommitted by specifying a style character '-'. * * @param style two characters from the set {"S", "M", "L", "F", "-"} * @param locale locale to use, null means default * @return the formatter * @throws IllegalArgumentException if the style is invalid * @since 1.3 */ public static String patternForStyle(String style, Locale locale) { DateTimeFormatter formatter = createFormatterForStyle(style); if (locale == null) { locale = Locale.getDefault(); } // Not pretty, but it works. return ((StyleFormatter) formatter.getPrinter()).getPattern(locale); } //----------------------------------------------------------------------- /** * Creates a format that outputs a short date format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter shortDate() { return createFormatterForStyleIndex(SHORT, NONE); } /** * Creates a format that outputs a short time format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter shortTime() { return createFormatterForStyleIndex(NONE, SHORT); } /** * Creates a format that outputs a short datetime format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter shortDateTime() { return createFormatterForStyleIndex(SHORT, SHORT); } //----------------------------------------------------------------------- /** * Creates a format that outputs a medium date format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter mediumDate() { return createFormatterForStyleIndex(MEDIUM, NONE); } /** * Creates a format that outputs a medium time format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter mediumTime() { return createFormatterForStyleIndex(NONE, MEDIUM); } /** * Creates a format that outputs a medium datetime format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter mediumDateTime() { return createFormatterForStyleIndex(MEDIUM, MEDIUM); } //----------------------------------------------------------------------- /** * Creates a format that outputs a long date format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter longDate() { return createFormatterForStyleIndex(LONG, NONE); } /** * Creates a format that outputs a long time format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter longTime() { return createFormatterForStyleIndex(NONE, LONG); } /** * Creates a format that outputs a long datetime format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter longDateTime() { return createFormatterForStyleIndex(LONG, LONG); } //----------------------------------------------------------------------- /** * Creates a format that outputs a full date format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter fullDate() { return createFormatterForStyleIndex(FULL, NONE); } /** * Creates a format that outputs a full time format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter fullTime() { return createFormatterForStyleIndex(NONE, FULL); } /** * Creates a format that outputs a full datetime format. *

* The format will change as you change the locale of the formatter. * Call {@link DateTimeFormatter#withLocale(Locale)} to switch the locale. * * @return the formatter */ public static DateTimeFormatter fullDateTime() { return createFormatterForStyleIndex(FULL, FULL); } //----------------------------------------------------------------------- /** * Parses the given pattern and appends the rules to the given * DateTimeFormatterBuilder. * * @param pattern pattern specification * @throws IllegalArgumentException if the pattern is invalid */ static void appendPatternTo(DateTimeFormatterBuilder builder, String pattern) { parsePatternTo(builder, pattern); } //----------------------------------------------------------------------- /** * Constructor. * * @since 1.1 (previously private) */ protected DateTimeFormat() { super(); } //----------------------------------------------------------------------- /** * Parses the given pattern and appends the rules to the given * DateTimeFormatterBuilder. * * @param pattern pattern specification * @throws IllegalArgumentException if the pattern is invalid * @see #forPattern */ private static void parsePatternTo(DateTimeFormatterBuilder builder, String pattern) { int length = pattern.length(); int[] indexRef = new int[1]; for (int i=0; i= 3) { if (tokenLen >= 4) { builder.appendMonthOfYearText(); } else { builder.appendMonthOfYearShortText(); } } else { builder.appendMonthOfYear(tokenLen); } break; case 'd': // day of month (number) builder.appendDayOfMonth(tokenLen); break; case 'a': // am/pm marker (text) builder.appendHalfdayOfDayText(); break; case 'h': // clockhour of halfday (number, 1..12) builder.appendClockhourOfHalfday(tokenLen); break; case 'H': // hour of day (number, 0..23) builder.appendHourOfDay(tokenLen); break; case 'k': // clockhour of day (1..24) builder.appendClockhourOfDay(tokenLen); break; case 'K': // hour of halfday (0..11) builder.appendHourOfHalfday(tokenLen); break; case 'm': // minute of hour (number) builder.appendMinuteOfHour(tokenLen); break; case 's': // second of minute (number) builder.appendSecondOfMinute(tokenLen); break; case 'S': // fraction of second (number) builder.appendFractionOfSecond(tokenLen, tokenLen); break; case 'e': // day of week (number) builder.appendDayOfWeek(tokenLen); break; case 'E': // dayOfWeek (text) if (tokenLen >= 4) { builder.appendDayOfWeekText(); } else { builder.appendDayOfWeekShortText(); } break; case 'D': // day of year (number) builder.appendDayOfYear(tokenLen); break; case 'w': // week of weekyear (number) builder.appendWeekOfWeekyear(tokenLen); break; case 'z': // time zone (text) if (tokenLen >= 4) { builder.appendTimeZoneName(); } else { builder.appendTimeZoneShortName(null); } break; case 'Z': // time zone offset if (tokenLen == 1) { builder.appendTimeZoneOffset(null, "Z", false, 2, 2); } else if (tokenLen == 2) { builder.appendTimeZoneOffset(null, "Z", true, 2, 2); } else { builder.appendTimeZoneId(); } break; case '\'': // literal text String sub = token.substring(1); if (sub.length() == 1) { builder.appendLiteral(sub.charAt(0)); } else { // Create copy of sub since otherwise the temporary quoted // string would still be referenced internally. builder.appendLiteral(new String(sub)); } break; default: throw new IllegalArgumentException ("Illegal pattern component: " + token); } } } /** * Parses an individual token. * * @param pattern the pattern string * @param indexRef a single element array, where the input is the start * location and the output is the location after parsing the token * @return the parsed token */ private static String parseToken(String pattern, int[] indexRef) { StringBuilder buf = new StringBuilder(); int i = indexRef[0]; int length = pattern.length(); char c = pattern.charAt(i); if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { // Scan a run of the same character, which indicates a time // pattern. buf.append(c); while (i + 1 < length) { char peek = pattern.charAt(i + 1); if (peek == c) { buf.append(c); i++; } else { break; } } } else { // This will identify token as text. buf.append('\''); boolean inLiteral = false; for (; i < length; i++) { c = pattern.charAt(i); if (c == '\'') { if (i + 1 < length && pattern.charAt(i + 1) == '\'') { // '' is treated as escaped ' i++; buf.append(c); } else { inLiteral = !inLiteral; } } else if (!inLiteral && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { i--; break; } else { buf.append(c); } } } indexRef[0] = i; return buf.toString(); } /** * Returns true if token should be parsed as a numeric field. * * @param token the token to parse * @return true if numeric field */ private static boolean isNumericToken(String token) { int tokenLen = token.length(); if (tokenLen > 0) { char c = token.charAt(0); switch (c) { case 'c': // century (number) case 'C': // century of era (number) case 'x': // weekyear (number) case 'y': // year (number) case 'Y': // year of era (number) case 'd': // day of month (number) case 'h': // hour of day (number, 1..12) case 'H': // hour of day (number, 0..23) case 'm': // minute of hour (number) case 's': // second of minute (number) case 'S': // fraction of second (number) case 'e': // day of week (number) case 'D': // day of year (number) case 'F': // day of week in month (number) case 'w': // week of year (number) case 'W': // week of month (number) case 'k': // hour of day (1..24) case 'K': // hour of day (0..11) return true; case 'M': // month of year (text and number) if (tokenLen <= 2) { return true; } } } return false; } //----------------------------------------------------------------------- /** * Select a format from a custom pattern. * * @param pattern pattern specification * @throws IllegalArgumentException if the pattern is invalid * @see #appendPatternTo */ private static DateTimeFormatter createFormatterForPattern(String pattern) { if (pattern == null || pattern.length() == 0) { throw new IllegalArgumentException("Invalid pattern specification"); } DateTimeFormatter formatter = null; synchronized (PATTERN_CACHE) { formatter = PATTERN_CACHE.get(pattern); if (formatter == null) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); parsePatternTo(builder, pattern); formatter = builder.toFormatter(); PATTERN_CACHE.put(pattern, formatter); } } return formatter; } /** * Select a format from a two character style pattern. The first character * is the date style, and the second character is the time style. Specify a * character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' * for full. A date or time may be ommitted by specifying a style character '-'. * * @param style two characters from the set {"S", "M", "L", "F", "-"} * @throws IllegalArgumentException if the style is invalid */ private static DateTimeFormatter createFormatterForStyle(String style) { if (style == null || style.length() != 2) { throw new IllegalArgumentException("Invalid style specification: " + style); } int dateStyle = selectStyle(style.charAt(0)); int timeStyle = selectStyle(style.charAt(1)); if (dateStyle == NONE && timeStyle == NONE) { throw new IllegalArgumentException("Style '--' is invalid"); } return createFormatterForStyleIndex(dateStyle, timeStyle); } /** * Gets the formatter for the specified style. * * @param dateStyle the date style * @param timeStyle the time style * @return the formatter */ private static DateTimeFormatter createFormatterForStyleIndex(int dateStyle, int timeStyle) { int index = ((dateStyle << 2) + dateStyle) + timeStyle; // Should never happen but do a double check... if (index >= STYLE_CACHE.length) { return createDateTimeFormatter(dateStyle, timeStyle); } DateTimeFormatter f = null; synchronized (STYLE_CACHE) { f = STYLE_CACHE[index]; if (f == null) { f = createDateTimeFormatter(dateStyle, timeStyle); STYLE_CACHE[index] = f; } } return f; } /** * Creates a formatter for the specified style. * @param dateStyle the date style * @param timeStyle the time style * @return the formatter */ private static DateTimeFormatter createDateTimeFormatter(int dateStyle, int timeStyle){ int type = DATETIME; if (dateStyle == NONE) { type = TIME; } else if (timeStyle == NONE) { type = DATE; } StyleFormatter llf = new StyleFormatter(dateStyle, timeStyle, type); return new DateTimeFormatter(llf, llf); } /** * Gets the JDK style code from the Joda code. * * @param ch the Joda style code * @return the JDK style code */ private static int selectStyle(char ch) { switch (ch) { case 'S': return SHORT; case 'M': return MEDIUM; case 'L': return LONG; case 'F': return FULL; case '-': return NONE; default: throw new IllegalArgumentException("Invalid style character: " + ch); } } //----------------------------------------------------------------------- static class StyleFormatter implements DateTimePrinter, DateTimeParser { private static final Map cCache = new HashMap(); // manual sync private final int iDateStyle; private final int iTimeStyle; private final int iType; StyleFormatter(int dateStyle, int timeStyle, int type) { super(); iDateStyle = dateStyle; iTimeStyle = timeStyle; iType = type; } public int estimatePrintedLength() { return 40; // guess } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { DateTimePrinter p = getFormatter(locale).getPrinter(); p.printTo(buf, instant, chrono, displayOffset, displayZone, locale); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { DateTimePrinter p = getFormatter(locale).getPrinter(); p.printTo(out, instant, chrono, displayOffset, displayZone, locale); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { DateTimePrinter p = getFormatter(locale).getPrinter(); p.printTo(buf, partial, locale); } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { DateTimePrinter p = getFormatter(locale).getPrinter(); p.printTo(out, partial, locale); } public int estimateParsedLength() { return 40; // guess } public int parseInto(DateTimeParserBucket bucket, String text, int position) { DateTimeParser p = getFormatter(bucket.getLocale()).getParser(); return p.parseInto(bucket, text, position); } private DateTimeFormatter getFormatter(Locale locale) { locale = (locale == null ? Locale.getDefault() : locale); String key = Integer.toString(iType + (iDateStyle << 4) + (iTimeStyle << 8)) + locale.toString(); DateTimeFormatter f = null; synchronized (cCache) { f = cCache.get(key); if (f == null) { String pattern = getPattern(locale); f = DateTimeFormat.forPattern(pattern); cCache.put(key, f); } } return f; } String getPattern(Locale locale) { DateFormat f = null; switch (iType) { case DATE: f = DateFormat.getDateInstance(iDateStyle, locale); break; case TIME: f = DateFormat.getTimeInstance(iTimeStyle, locale); break; case DATETIME: f = DateFormat.getDateTimeInstance(iDateStyle, iTimeStyle, locale); break; } if (f instanceof SimpleDateFormat == false) { throw new IllegalArgumentException("No datetime pattern for locale: " + locale); } return ((SimpleDateFormat) f).toPattern(); } } } joda-time-2.3/src/main/java/org/joda/time/format/PeriodFormat.java0000644000175000017500000001305012071610721024377 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Factory that creates instances of PeriodFormatter. *

* Period formatting is performed by the {@link PeriodFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link ISOPeriodFormat} and {@link PeriodFormatterBuilder}. *

* PeriodFormat is thread-safe and immutable, and the formatters it returns * are as well. * * @author Brian S O'Neill * @since 1.0 * @see ISOPeriodFormat * @see PeriodFormatterBuilder */ public class PeriodFormat { /** * The resource bundle name. */ private static final String BUNDLE_NAME = "org.joda.time.format.messages"; /** * The created formatters. */ private static final ConcurrentMap FORMATTERS = new ConcurrentHashMap(); /** * Constructor. * * @since 1.1 (previously private) */ protected PeriodFormat() { super(); } //----------------------------------------------------------------------- /** * Gets the default formatter that outputs words in English. *

* This calls {@link #wordBased(Locale)} using a locale of {@code ENGLISH}. * * @return the formatter, not null */ public static PeriodFormatter getDefault() { return wordBased(Locale.ENGLISH); } /** * Returns a word based formatter for the JDK default locale. *

* This calls {@link #wordBased(Locale)} using the {@link Locale#getDefault() default locale}. * * @return the formatter, not null * @since 2.0 */ public static PeriodFormatter wordBased() { return wordBased(Locale.getDefault()); } /** * Returns a word based formatter for the specified locale. *

* The words are configured in a resource bundle text file - * {@code org.joda.time.format.messages}. * This can be added to via the normal classpath resource bundle mechanisms. *

* Available languages are English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. * * @return the formatter, not null * @since 2.0 */ public static PeriodFormatter wordBased(Locale locale) { PeriodFormatter pf = FORMATTERS.get(locale); if (pf == null) { ResourceBundle b = ResourceBundle.getBundle(BUNDLE_NAME, locale); String[] variants = { b.getString("PeriodFormat.space"), b.getString("PeriodFormat.comma"), b.getString("PeriodFormat.commandand"), b.getString("PeriodFormat.commaspaceand")}; pf = new PeriodFormatterBuilder() .appendYears() .appendSuffix(b.getString("PeriodFormat.year"), b.getString("PeriodFormat.years")) .appendSeparator(b.getString("PeriodFormat.commaspace"), b.getString("PeriodFormat.spaceandspace"), variants) .appendMonths() .appendSuffix(b.getString("PeriodFormat.month"), b.getString("PeriodFormat.months")) .appendSeparator(b.getString("PeriodFormat.commaspace"), b.getString("PeriodFormat.spaceandspace"), variants) .appendWeeks() .appendSuffix(b.getString("PeriodFormat.week"), b.getString("PeriodFormat.weeks")) .appendSeparator(b.getString("PeriodFormat.commaspace"), b.getString("PeriodFormat.spaceandspace"), variants) .appendDays() .appendSuffix(b.getString("PeriodFormat.day"), b.getString("PeriodFormat.days")) .appendSeparator(b.getString("PeriodFormat.commaspace"), b.getString("PeriodFormat.spaceandspace"), variants) .appendHours() .appendSuffix(b.getString("PeriodFormat.hour"), b.getString("PeriodFormat.hours")) .appendSeparator(b.getString("PeriodFormat.commaspace"), b.getString("PeriodFormat.spaceandspace"), variants) .appendMinutes() .appendSuffix(b.getString("PeriodFormat.minute"), b.getString("PeriodFormat.minutes")) .appendSeparator(b.getString("PeriodFormat.commaspace"), b.getString("PeriodFormat.spaceandspace"), variants) .appendSeconds() .appendSuffix(b.getString("PeriodFormat.second"), b.getString("PeriodFormat.seconds")) .appendSeparator(b.getString("PeriodFormat.commaspace"), b.getString("PeriodFormat.spaceandspace"), variants) .appendMillis() .appendSuffix(b.getString("PeriodFormat.millisecond"), b.getString("PeriodFormat.milliseconds")) .toFormatter(); FORMATTERS.putIfAbsent(locale, pf); } return pf; } } joda-time-2.3/src/main/java/org/joda/time/format/PeriodParser.java0000644000175000017500000000447311564251363024425 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Locale; import org.joda.time.ReadWritablePeriod; /** * Internal interface for parsing textual representations of time periods. *

* Application users will rarely use this class directly. Instead, you * will use one of the factory classes to create a {@link PeriodFormatter}. *

* The factory classes are:
* - {@link PeriodFormatterBuilder}
* - {@link PeriodFormat}
* - {@link ISOPeriodFormat}
* * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 * @see PeriodFormatter * @see PeriodFormatterBuilder * @see PeriodFormat */ public interface PeriodParser { /** * Parses a period from the given text, at the given position, saving the * result into the fields of the given ReadWritablePeriod. If the parse * succeeds, the return value is the new text position. Note that the parse * may succeed without fully reading the text. *

* If it fails, the return value is negative, but the period may still be * modified. To determine the position where the parse failed, apply the * one's complement operator (~) on the return value. * * @param period a period that will be modified * @param periodStr text to parse * @param position position to start parsing from * @param locale the locale to use for parsing * @return new position, if negative, parse failed. Apply complement * operator (~) to get position of failure * @throws IllegalArgumentException if any field is out of range */ int parseInto(ReadWritablePeriod period, String periodStr, int position, Locale locale); } joda-time-2.3/src/main/java/org/joda/time/format/messages_es.properties0000644000175000017500000000120512030573642025561 0ustar ebourgebourgPeriodFormat.space=\ PeriodFormat.comma=, PeriodFormat.commandand=,y PeriodFormat.commaspaceand=, y PeriodFormat.commaspace=, PeriodFormat.spaceandspace=\ y PeriodFormat.year=\ año PeriodFormat.years=\ años PeriodFormat.month=\ mes PeriodFormat.months=\ meses PeriodFormat.week=\ semana PeriodFormat.weeks=\ semanas PeriodFormat.day=\ día PeriodFormat.days=\ días PeriodFormat.hour=\ hora PeriodFormat.hours=\ horas PeriodFormat.minute=\ minuto PeriodFormat.minutes=\ minutos PeriodFormat.second=\ segundo PeriodFormat.seconds=\ segundos PeriodFormat.millisecond=\ milisegundo PeriodFormat.milliseconds=\ milisegundos joda-time-2.3/src/main/java/org/joda/time/format/messages_da.properties0000644000175000017500000000115512031053066025534 0ustar ebourgebourgPeriodFormat.space=\ PeriodFormat.comma=, PeriodFormat.commandand=,og PeriodFormat.commaspaceand=, og PeriodFormat.commaspace=,\ PeriodFormat.spaceandspace=\ og\ PeriodFormat.year=\ år PeriodFormat.years=\ år PeriodFormat.month=\ måned PeriodFormat.months=\ måneder PeriodFormat.week=\ uge PeriodFormat.weeks=\ uger PeriodFormat.day=\ dag PeriodFormat.days=\ dage PeriodFormat.hour=\ time PeriodFormat.hours=\ timer PeriodFormat.minute=\ minut PeriodFormat.minutes=\ minutter PeriodFormat.second=\ sekund PeriodFormat.seconds=\ sekunder PeriodFormat.millisecond=\ millisekund PeriodFormat.milliseconds=\ millisekunder joda-time-2.3/src/main/java/org/joda/time/format/messages_en.properties0000644000175000017500000000000011712473256025552 0ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/format/PeriodFormatterBuilder.java0000644000175000017500000021266312071610306026433 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.TreeSet; import org.joda.time.DateTimeConstants; import org.joda.time.DurationFieldType; import org.joda.time.PeriodType; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadablePeriod; /** * Factory that creates complex instances of PeriodFormatter via method calls. *

* Period formatting is performed by the {@link PeriodFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link PeriodFormat} and {@link ISOPeriodFormat}. *

* PeriodFormatterBuilder is used for constructing formatters which are then * used to print or parse. The formatters are built by appending specific fields * or other formatters to an instance of this builder. *

* For example, a formatter that prints years and months, like "15 years and 8 months", * can be constructed as follows: *

*

 * PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
 *     .printZeroAlways()
 *     .appendYears()
 *     .appendSuffix(" year", " years")
 *     .appendSeparator(" and ")
 *     .printZeroRarelyLast()
 *     .appendMonths()
 *     .appendSuffix(" month", " months")
 *     .toFormatter();
 * 
*

* PeriodFormatterBuilder itself is mutable and not thread-safe, but the * formatters that it builds are thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 * @see PeriodFormat */ public class PeriodFormatterBuilder { private static final int PRINT_ZERO_RARELY_FIRST = 1; private static final int PRINT_ZERO_RARELY_LAST = 2; private static final int PRINT_ZERO_IF_SUPPORTED = 3; private static final int PRINT_ZERO_ALWAYS = 4; private static final int PRINT_ZERO_NEVER = 5; private static final int YEARS = 0; private static final int MONTHS = 1; private static final int WEEKS = 2; private static final int DAYS = 3; private static final int HOURS = 4; private static final int MINUTES = 5; private static final int SECONDS = 6; private static final int MILLIS = 7; private static final int SECONDS_MILLIS = 8; private static final int SECONDS_OPTIONAL_MILLIS = 9; private static final int MAX_FIELD = SECONDS_OPTIONAL_MILLIS; private int iMinPrintedDigits; private int iPrintZeroSetting; private int iMaxParsedDigits; private boolean iRejectSignedValues; private PeriodFieldAffix iPrefix; // List of Printers and Parsers used to build a final formatter. private List iElementPairs; /** Set to true if the formatter is not a printer. */ private boolean iNotPrinter; /** Set to true if the formatter is not a parser. */ private boolean iNotParser; // Last PeriodFormatter appended of each field type. private FieldFormatter[] iFieldFormatters; public PeriodFormatterBuilder() { clear(); } //----------------------------------------------------------------------- /** * Constructs a PeriodFormatter using all the appended elements. *

* This is the main method used by applications at the end of the build * process to create a usable formatter. *

* Subsequent changes to this builder do not affect the returned formatter. *

* The returned formatter may not support both printing and parsing. * The methods {@link PeriodFormatter#isPrinter()} and * {@link PeriodFormatter#isParser()} will help you determine the state * of the formatter. * * @return the newly created formatter * @throws IllegalStateException if the builder can produce neither a printer nor a parser */ public PeriodFormatter toFormatter() { PeriodFormatter formatter = toFormatter(iElementPairs, iNotPrinter, iNotParser); iFieldFormatters = (FieldFormatter[]) iFieldFormatters.clone(); return formatter; } /** * Internal method to create a PeriodPrinter instance using all the * appended elements. *

* Most applications will not use this method. * If you want a printer in an application, call {@link #toFormatter()} * and just use the printing API. *

* Subsequent changes to this builder do not affect the returned printer. * * @return the newly created printer, null if builder cannot create a printer */ public PeriodPrinter toPrinter() { if (iNotPrinter) { return null; } return toFormatter().getPrinter(); } /** * Internal method to create a PeriodParser instance using all the * appended elements. *

* Most applications will not use this method. * If you want a printer in an application, call {@link #toFormatter()} * and just use the printing API. *

* Subsequent changes to this builder do not affect the returned parser. * * @return the newly created parser, null if builder cannot create a parser */ public PeriodParser toParser() { if (iNotParser) { return null; } return toFormatter().getParser(); } //----------------------------------------------------------------------- /** * Clears out all the appended elements, allowing this builder to be reused. */ public void clear() { iMinPrintedDigits = 1; iPrintZeroSetting = PRINT_ZERO_RARELY_LAST; iMaxParsedDigits = 10; iRejectSignedValues = false; iPrefix = null; if (iElementPairs == null) { iElementPairs = new ArrayList(); } else { iElementPairs.clear(); } iNotPrinter = false; iNotParser = false; iFieldFormatters = new FieldFormatter[10]; } /** * Appends another formatter. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder append(PeriodFormatter formatter) { if (formatter == null) { throw new IllegalArgumentException("No formatter supplied"); } clearPrefix(); append0(formatter.getPrinter(), formatter.getParser()); return this; } /** * Appends a printer parser pair. *

* Either the printer or the parser may be null, in which case the builder will * be unable to produce a parser or printer repectively. * * @param printer appends a printer to the builder, null if printing is not supported * @param parser appends a parser to the builder, null if parsing is not supported * @return this PeriodFormatterBuilder * @throws IllegalArgumentException if both the printer and parser are null */ public PeriodFormatterBuilder append(PeriodPrinter printer, PeriodParser parser) { if (printer == null && parser == null) { throw new IllegalArgumentException("No printer or parser supplied"); } clearPrefix(); append0(printer, parser); return this; } /** * Instructs the printer to emit specific text, and the parser to expect it. * The parser is case-insensitive. * * @return this PeriodFormatterBuilder * @throws IllegalArgumentException if text is null */ public PeriodFormatterBuilder appendLiteral(String text) { if (text == null) { throw new IllegalArgumentException("Literal must not be null"); } clearPrefix(); Literal literal = new Literal(text); append0(literal, literal); return this; } /** * Set the minimum digits printed for the next and following appended * fields. By default, the minimum digits printed is one. If the field value * is zero, it is not printed unless a printZero rule is applied. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder minimumPrintedDigits(int minDigits) { iMinPrintedDigits = minDigits; return this; } /** * Set the maximum digits parsed for the next and following appended * fields. By default, the maximum digits parsed is ten. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder maximumParsedDigits(int maxDigits) { iMaxParsedDigits = maxDigits; return this; } /** * Reject signed values when parsing the next and following appended fields. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder rejectSignedValues(boolean v) { iRejectSignedValues = v; return this; } /** * Never print zero values for the next and following appended fields, * unless no fields would be printed. If no fields are printed, the printer * forces the last "printZeroRarely" field to print a zero. *

* This field setting is the default. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder printZeroRarelyLast() { iPrintZeroSetting = PRINT_ZERO_RARELY_LAST; return this; } /** * Never print zero values for the next and following appended fields, * unless no fields would be printed. If no fields are printed, the printer * forces the first "printZeroRarely" field to print a zero. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder printZeroRarelyFirst() { iPrintZeroSetting = PRINT_ZERO_RARELY_FIRST; return this; } /** * Print zero values for the next and following appened fields only if the * period supports it. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder printZeroIfSupported() { iPrintZeroSetting = PRINT_ZERO_IF_SUPPORTED; return this; } /** * Always print zero values for the next and following appended fields, * even if the period doesn't support it. The parser requires values for * fields that always print zero. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder printZeroAlways() { iPrintZeroSetting = PRINT_ZERO_ALWAYS; return this; } /** * Never print zero values for the next and following appended fields, * unless no fields would be printed. If no fields are printed, the printer * forces the last "printZeroRarely" field to print a zero. *

* This field setting is the default. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder printZeroNever() { iPrintZeroSetting = PRINT_ZERO_NEVER; return this; } //----------------------------------------------------------------------- /** * Append a field prefix which applies only to the next appended field. If * the field is not printed, neither is the prefix. * * @param text text to print before field only if field is printed * @return this PeriodFormatterBuilder * @see #appendSuffix */ public PeriodFormatterBuilder appendPrefix(String text) { if (text == null) { throw new IllegalArgumentException(); } return appendPrefix(new SimpleAffix(text)); } /** * Append a field prefix which applies only to the next appended field. If * the field is not printed, neither is the prefix. *

* During parsing, the singular and plural versions are accepted whether * or not the actual value matches plurality. * * @param singularText text to print if field value is one * @param pluralText text to print if field value is not one * @return this PeriodFormatterBuilder * @see #appendSuffix */ public PeriodFormatterBuilder appendPrefix(String singularText, String pluralText) { if (singularText == null || pluralText == null) { throw new IllegalArgumentException(); } return appendPrefix(new PluralAffix(singularText, pluralText)); } /** * Append a field prefix which applies only to the next appended field. If * the field is not printed, neither is the prefix. * * @param prefix custom prefix * @return this PeriodFormatterBuilder * @see #appendSuffix */ private PeriodFormatterBuilder appendPrefix(PeriodFieldAffix prefix) { if (prefix == null) { throw new IllegalArgumentException(); } if (iPrefix != null) { prefix = new CompositeAffix(iPrefix, prefix); } iPrefix = prefix; return this; } //----------------------------------------------------------------------- /** * Instruct the printer to emit an integer years field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendYears() { appendField(YEARS); return this; } /** * Instruct the printer to emit an integer months field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendMonths() { appendField(MONTHS); return this; } /** * Instruct the printer to emit an integer weeks field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendWeeks() { appendField(WEEKS); return this; } /** * Instruct the printer to emit an integer days field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendDays() { appendField(DAYS); return this; } /** * Instruct the printer to emit an integer hours field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendHours() { appendField(HOURS); return this; } /** * Instruct the printer to emit an integer minutes field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendMinutes() { appendField(MINUTES); return this; } /** * Instruct the printer to emit an integer seconds field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendSeconds() { appendField(SECONDS); return this; } /** * Instruct the printer to emit a combined seconds and millis field, if supported. * The millis will overflow into the seconds if necessary. * The millis are always output. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendSecondsWithMillis() { appendField(SECONDS_MILLIS); return this; } /** * Instruct the printer to emit a combined seconds and millis field, if supported. * The millis will overflow into the seconds if necessary. * The millis are only output if non-zero. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendSecondsWithOptionalMillis() { appendField(SECONDS_OPTIONAL_MILLIS); return this; } /** * Instruct the printer to emit an integer millis field, if supported. *

* The number of printed and parsed digits can be controlled using * {@link #minimumPrintedDigits(int)} and {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendMillis() { appendField(MILLIS); return this; } /** * Instruct the printer to emit an integer millis field, if supported. *

* The number of arsed digits can be controlled using {@link #maximumParsedDigits(int)}. * * @return this PeriodFormatterBuilder */ public PeriodFormatterBuilder appendMillis3Digit() { appendField(7, 3); return this; } private void appendField(int type) { appendField(type, iMinPrintedDigits); } private void appendField(int type, int minPrinted) { FieldFormatter field = new FieldFormatter(minPrinted, iPrintZeroSetting, iMaxParsedDigits, iRejectSignedValues, type, iFieldFormatters, iPrefix, null); append0(field, field); iFieldFormatters[type] = field; iPrefix = null; } //----------------------------------------------------------------------- /** * Append a field suffix which applies only to the last appended field. If * the field is not printed, neither is the suffix. * * @param text text to print after field only if field is printed * @return this PeriodFormatterBuilder * @throws IllegalStateException if no field exists to append to * @see #appendPrefix */ public PeriodFormatterBuilder appendSuffix(String text) { if (text == null) { throw new IllegalArgumentException(); } return appendSuffix(new SimpleAffix(text)); } /** * Append a field suffix which applies only to the last appended field. If * the field is not printed, neither is the suffix. *

* During parsing, the singular and plural versions are accepted whether or * not the actual value matches plurality. * * @param singularText text to print if field value is one * @param pluralText text to print if field value is not one * @return this PeriodFormatterBuilder * @throws IllegalStateException if no field exists to append to * @see #appendPrefix */ public PeriodFormatterBuilder appendSuffix(String singularText, String pluralText) { if (singularText == null || pluralText == null) { throw new IllegalArgumentException(); } return appendSuffix(new PluralAffix(singularText, pluralText)); } /** * Append a field suffix which applies only to the last appended field. If * the field is not printed, neither is the suffix. * * @param suffix custom suffix * @return this PeriodFormatterBuilder * @throws IllegalStateException if no field exists to append to * @see #appendPrefix */ private PeriodFormatterBuilder appendSuffix(PeriodFieldAffix suffix) { final Object originalPrinter; final Object originalParser; if (iElementPairs.size() > 0) { originalPrinter = iElementPairs.get(iElementPairs.size() - 2); originalParser = iElementPairs.get(iElementPairs.size() - 1); } else { originalPrinter = null; originalParser = null; } if (originalPrinter == null || originalParser == null || originalPrinter != originalParser || !(originalPrinter instanceof FieldFormatter)) { throw new IllegalStateException("No field to apply suffix to"); } clearPrefix(); FieldFormatter newField = new FieldFormatter((FieldFormatter) originalPrinter, suffix); iElementPairs.set(iElementPairs.size() - 2, newField); iElementPairs.set(iElementPairs.size() - 1, newField); iFieldFormatters[newField.getFieldType()] = newField; return this; } //----------------------------------------------------------------------- /** * Append a separator, which is output if fields are printed both before * and after the separator. *

* For example, builder.appendDays().appendSeparator(",").appendHours() * will only output the comma if both the days and hours fields are output. *

* The text will be parsed case-insensitively. *

* Note: appending a separator discontinues any further work on the latest * appended field. * * @param text the text to use as a separator * @return this PeriodFormatterBuilder * @throws IllegalStateException if this separator follows a previous one */ public PeriodFormatterBuilder appendSeparator(String text) { return appendSeparator(text, text, null, true, true); } /** * Append a separator, which is output only if fields are printed after the separator. *

* For example, * builder.appendDays().appendSeparatorIfFieldsAfter(",").appendHours() * will only output the comma if the hours fields is output. *

* The text will be parsed case-insensitively. *

* Note: appending a separator discontinues any further work on the latest * appended field. * * @param text the text to use as a separator * @return this PeriodFormatterBuilder * @throws IllegalStateException if this separator follows a previous one */ public PeriodFormatterBuilder appendSeparatorIfFieldsAfter(String text) { return appendSeparator(text, text, null, false, true); } /** * Append a separator, which is output only if fields are printed before the separator. *

* For example, * builder.appendDays().appendSeparatorIfFieldsBefore(",").appendHours() * will only output the comma if the days fields is output. *

* The text will be parsed case-insensitively. *

* Note: appending a separator discontinues any further work on the latest * appended field. * * @param text the text to use as a separator * @return this PeriodFormatterBuilder * @throws IllegalStateException if this separator follows a previous one */ public PeriodFormatterBuilder appendSeparatorIfFieldsBefore(String text) { return appendSeparator(text, text, null, true, false); } /** * Append a separator, which is output if fields are printed both before * and after the separator. *

* This method changes the separator depending on whether it is the last separator * to be output. *

* For example, builder.appendDays().appendSeparator(",", "&").appendHours().appendSeparator(",", "&").appendMinutes() * will output '1,2&3' if all three fields are output, '1&2' if two fields are output * and '1' if just one field is output. *

* The text will be parsed case-insensitively. *

* Note: appending a separator discontinues any further work on the latest * appended field. * * @param text the text to use as a separator * @param finalText the text used used if this is the final separator to be printed * @return this PeriodFormatterBuilder * @throws IllegalStateException if this separator follows a previous one */ public PeriodFormatterBuilder appendSeparator(String text, String finalText) { return appendSeparator(text, finalText, null, true, true); } /** * Append a separator, which is output if fields are printed both before * and after the separator. *

* This method changes the separator depending on whether it is the last separator * to be output. *

* For example, builder.appendDays().appendSeparator(",", "&").appendHours().appendSeparator(",", "&").appendMinutes() * will output '1,2&3' if all three fields are output, '1&2' if two fields are output * and '1' if just one field is output. *

* The text will be parsed case-insensitively. *

* Note: appending a separator discontinues any further work on the latest * appended field. * * @param text the text to use as a separator * @param finalText the text used used if this is the final separator to be printed * @param variants set of text values which are also acceptable when parsed * @return this PeriodFormatterBuilder * @throws IllegalStateException if this separator follows a previous one */ public PeriodFormatterBuilder appendSeparator(String text, String finalText, String[] variants) { return appendSeparator(text, finalText, variants, true, true); } private PeriodFormatterBuilder appendSeparator(String text, String finalText, String[] variants, boolean useBefore, boolean useAfter) { if (text == null || finalText == null) { throw new IllegalArgumentException(); } clearPrefix(); // optimise zero formatter case List pairs = iElementPairs; if (pairs.size() == 0) { if (useAfter && useBefore == false) { Separator separator = new Separator( text, finalText, variants, Literal.EMPTY, Literal.EMPTY, useBefore, useAfter); append0(separator, separator); } return this; } // find the last separator added int i; Separator lastSeparator = null; for (i=pairs.size(); --i>=0; ) { if (pairs.get(i) instanceof Separator) { lastSeparator = (Separator) pairs.get(i); pairs = pairs.subList(i + 1, pairs.size()); break; } i--; // element pairs } // merge formatters if (lastSeparator != null && pairs.size() == 0) { throw new IllegalStateException("Cannot have two adjacent separators"); } else { Object[] comp = createComposite(pairs); pairs.clear(); Separator separator = new Separator( text, finalText, variants, (PeriodPrinter) comp[0], (PeriodParser) comp[1], useBefore, useAfter); pairs.add(separator); pairs.add(separator); } return this; } //----------------------------------------------------------------------- private void clearPrefix() throws IllegalStateException { if (iPrefix != null) { throw new IllegalStateException("Prefix not followed by field"); } iPrefix = null; } private PeriodFormatterBuilder append0(PeriodPrinter printer, PeriodParser parser) { iElementPairs.add(printer); iElementPairs.add(parser); iNotPrinter |= (printer == null); iNotParser |= (parser == null); return this; } //----------------------------------------------------------------------- private static PeriodFormatter toFormatter(List elementPairs, boolean notPrinter, boolean notParser) { if (notPrinter && notParser) { throw new IllegalStateException("Builder has created neither a printer nor a parser"); } int size = elementPairs.size(); if (size >= 2 && elementPairs.get(0) instanceof Separator) { Separator sep = (Separator) elementPairs.get(0); if (sep.iAfterParser == null && sep.iAfterPrinter == null) { PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser); sep = sep.finish(f.getPrinter(), f.getParser()); return new PeriodFormatter(sep, sep); } } Object[] comp = createComposite(elementPairs); if (notPrinter) { return new PeriodFormatter(null, (PeriodParser) comp[1]); } else if (notParser) { return new PeriodFormatter((PeriodPrinter) comp[0], null); } else { return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]); } } private static Object[] createComposite(List elementPairs) { switch (elementPairs.size()) { case 0: return new Object[] {Literal.EMPTY, Literal.EMPTY}; case 1: return new Object[] {elementPairs.get(0), elementPairs.get(1)}; default: Composite comp = new Composite(elementPairs); return new Object[] {comp, comp}; } } //----------------------------------------------------------------------- /** * Defines a formatted field's prefix or suffix text. * This can be used for fields such as 'n hours' or 'nH' or 'Hour:n'. */ static interface PeriodFieldAffix { int calculatePrintedLength(int value); void printTo(StringBuffer buf, int value); void printTo(Writer out, int value) throws IOException; /** * @return new position after parsing affix, or ~position of failure */ int parse(String periodStr, int position); /** * @return position where affix starts, or original ~position if not found */ int scan(String periodStr, int position); } //----------------------------------------------------------------------- /** * Implements an affix where the text does not vary by the amount. */ static class SimpleAffix implements PeriodFieldAffix { private final String iText; SimpleAffix(String text) { iText = text; } public int calculatePrintedLength(int value) { return iText.length(); } public void printTo(StringBuffer buf, int value) { buf.append(iText); } public void printTo(Writer out, int value) throws IOException { out.write(iText); } public int parse(String periodStr, int position) { String text = iText; int textLength = text.length(); if (periodStr.regionMatches(true, position, text, 0, textLength)) { return position + textLength; } return ~position; } public int scan(String periodStr, final int position) { String text = iText; int textLength = text.length(); int sourceLength = periodStr.length(); search: for (int pos = position; pos < sourceLength; pos++) { if (periodStr.regionMatches(true, pos, text, 0, textLength)) { return pos; } // Only allow number characters to be skipped in search of suffix. switch (periodStr.charAt(pos)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case ',': case '+': case '-': break; default: break search; } } return ~position; } } //----------------------------------------------------------------------- /** * Implements an affix where the text varies by the amount of the field. * Only singular (1) and plural (not 1) are supported. */ static class PluralAffix implements PeriodFieldAffix { private final String iSingularText; private final String iPluralText; PluralAffix(String singularText, String pluralText) { iSingularText = singularText; iPluralText = pluralText; } public int calculatePrintedLength(int value) { return (value == 1 ? iSingularText : iPluralText).length(); } public void printTo(StringBuffer buf, int value) { buf.append(value == 1 ? iSingularText : iPluralText); } public void printTo(Writer out, int value) throws IOException { out.write(value == 1 ? iSingularText : iPluralText); } public int parse(String periodStr, int position) { String text1 = iPluralText; String text2 = iSingularText; if (text1.length() < text2.length()) { // Swap in order to match longer one first. String temp = text1; text1 = text2; text2 = temp; } if (periodStr.regionMatches (true, position, text1, 0, text1.length())) { return position + text1.length(); } if (periodStr.regionMatches (true, position, text2, 0, text2.length())) { return position + text2.length(); } return ~position; } public int scan(String periodStr, final int position) { String text1 = iPluralText; String text2 = iSingularText; if (text1.length() < text2.length()) { // Swap in order to match longer one first. String temp = text1; text1 = text2; text2 = temp; } int textLength1 = text1.length(); int textLength2 = text2.length(); int sourceLength = periodStr.length(); for (int pos = position; pos < sourceLength; pos++) { if (periodStr.regionMatches(true, pos, text1, 0, textLength1)) { return pos; } if (periodStr.regionMatches(true, pos, text2, 0, textLength2)) { return pos; } } return ~position; } } //----------------------------------------------------------------------- /** * Builds a composite affix by merging two other affix implementations. */ static class CompositeAffix implements PeriodFieldAffix { private final PeriodFieldAffix iLeft; private final PeriodFieldAffix iRight; CompositeAffix(PeriodFieldAffix left, PeriodFieldAffix right) { iLeft = left; iRight = right; } public int calculatePrintedLength(int value) { return iLeft.calculatePrintedLength(value) + iRight.calculatePrintedLength(value); } public void printTo(StringBuffer buf, int value) { iLeft.printTo(buf, value); iRight.printTo(buf, value); } public void printTo(Writer out, int value) throws IOException { iLeft.printTo(out, value); iRight.printTo(out, value); } public int parse(String periodStr, int position) { position = iLeft.parse(periodStr, position); if (position >= 0) { position = iRight.parse(periodStr, position); } return position; } public int scan(String periodStr, final int position) { int pos = iLeft.scan(periodStr, position); if (pos >= 0) { return iRight.scan(periodStr, pos); } return ~position; } } //----------------------------------------------------------------------- /** * Formats the numeric value of a field, potentially with prefix/suffix. */ static class FieldFormatter implements PeriodPrinter, PeriodParser { private final int iMinPrintedDigits; private final int iPrintZeroSetting; private final int iMaxParsedDigits; private final boolean iRejectSignedValues; /** The index of the field type, 0=year, etc. */ private final int iFieldType; /** * The array of the latest formatter added for each type. * This is shared between all the field formatters in a formatter. */ private final FieldFormatter[] iFieldFormatters; private final PeriodFieldAffix iPrefix; private final PeriodFieldAffix iSuffix; FieldFormatter(int minPrintedDigits, int printZeroSetting, int maxParsedDigits, boolean rejectSignedValues, int fieldType, FieldFormatter[] fieldFormatters, PeriodFieldAffix prefix, PeriodFieldAffix suffix) { iMinPrintedDigits = minPrintedDigits; iPrintZeroSetting = printZeroSetting; iMaxParsedDigits = maxParsedDigits; iRejectSignedValues = rejectSignedValues; iFieldType = fieldType; iFieldFormatters = fieldFormatters; iPrefix = prefix; iSuffix = suffix; } FieldFormatter(FieldFormatter field, PeriodFieldAffix suffix) { iMinPrintedDigits = field.iMinPrintedDigits; iPrintZeroSetting = field.iPrintZeroSetting; iMaxParsedDigits = field.iMaxParsedDigits; iRejectSignedValues = field.iRejectSignedValues; iFieldType = field.iFieldType; iFieldFormatters = field.iFieldFormatters; iPrefix = field.iPrefix; if (field.iSuffix != null) { suffix = new CompositeAffix(field.iSuffix, suffix); } iSuffix = suffix; } public int countFieldsToPrint(ReadablePeriod period, int stopAt, Locale locale) { if (stopAt <= 0) { return 0; } if (iPrintZeroSetting == PRINT_ZERO_ALWAYS || getFieldValue(period) != Long.MAX_VALUE) { return 1; } return 0; } public int calculatePrintedLength(ReadablePeriod period, Locale locale) { long valueLong = getFieldValue(period); if (valueLong == Long.MAX_VALUE) { return 0; } int sum = Math.max(FormatUtils.calculateDigitCount(valueLong), iMinPrintedDigits); if (iFieldType >= SECONDS_MILLIS) { // valueLong contains the seconds and millis fields // the minimum output is 0.000, which is 4 or 5 digits with a negative sum = (valueLong < 0 ? Math.max(sum, 5) : Math.max(sum, 4)); // plus one for the decimal point sum++; if (iFieldType == SECONDS_OPTIONAL_MILLIS && (Math.abs(valueLong) % DateTimeConstants.MILLIS_PER_SECOND) == 0) { sum -= 4; // remove three digits and decimal point } // reset valueLong to refer to the seconds part for the prefic/suffix calculation valueLong = valueLong / DateTimeConstants.MILLIS_PER_SECOND; } int value = (int) valueLong; if (iPrefix != null) { sum += iPrefix.calculatePrintedLength(value); } if (iSuffix != null) { sum += iSuffix.calculatePrintedLength(value); } return sum; } public void printTo(StringBuffer buf, ReadablePeriod period, Locale locale) { long valueLong = getFieldValue(period); if (valueLong == Long.MAX_VALUE) { return; } int value = (int) valueLong; if (iFieldType >= SECONDS_MILLIS) { value = (int) (valueLong / DateTimeConstants.MILLIS_PER_SECOND); } if (iPrefix != null) { iPrefix.printTo(buf, value); } int bufLen = buf.length(); int minDigits = iMinPrintedDigits; if (minDigits <= 1) { FormatUtils.appendUnpaddedInteger(buf, value); } else { FormatUtils.appendPaddedInteger(buf, value, minDigits); } if (iFieldType >= SECONDS_MILLIS) { int dp = (int) (Math.abs(valueLong) % DateTimeConstants.MILLIS_PER_SECOND); if (iFieldType == SECONDS_MILLIS || dp > 0) { if (valueLong < 0 && valueLong > -DateTimeConstants.MILLIS_PER_SECOND) { buf.insert(bufLen, '-'); } buf.append('.'); FormatUtils.appendPaddedInteger(buf, dp, 3); } } if (iSuffix != null) { iSuffix.printTo(buf, value); } } public void printTo(Writer out, ReadablePeriod period, Locale locale) throws IOException { long valueLong = getFieldValue(period); if (valueLong == Long.MAX_VALUE) { return; } int value = (int) valueLong; if (iFieldType >= SECONDS_MILLIS) { value = (int) (valueLong / DateTimeConstants.MILLIS_PER_SECOND); } if (iPrefix != null) { iPrefix.printTo(out, value); } int minDigits = iMinPrintedDigits; if (minDigits <= 1) { FormatUtils.writeUnpaddedInteger(out, value); } else { FormatUtils.writePaddedInteger(out, value, minDigits); } if (iFieldType >= SECONDS_MILLIS) { int dp = (int) (Math.abs(valueLong) % DateTimeConstants.MILLIS_PER_SECOND); if (iFieldType == SECONDS_MILLIS || dp > 0) { out.write('.'); FormatUtils.writePaddedInteger(out, dp, 3); } } if (iSuffix != null) { iSuffix.printTo(out, value); } } public int parseInto( ReadWritablePeriod period, String text, int position, Locale locale) { boolean mustParse = (iPrintZeroSetting == PRINT_ZERO_ALWAYS); // Shortcut test. if (position >= text.length()) { return mustParse ? ~position : position; } if (iPrefix != null) { position = iPrefix.parse(text, position); if (position >= 0) { // If prefix is found, then the parse must finish. mustParse = true; } else { // Prefix not found, so bail. if (!mustParse) { // It's okay because parsing of this field is not // required. Don't return an error. Fields down the // chain can continue on, trying to parse. return ~position; } return position; } } int suffixPos = -1; if (iSuffix != null && !mustParse) { // Pre-scan the suffix, to help determine if this field must be // parsed. suffixPos = iSuffix.scan(text, position); if (suffixPos >= 0) { // If suffix is found, then parse must finish. mustParse = true; } else { // Suffix not found, so bail. if (!mustParse) { // It's okay because parsing of this field is not // required. Don't return an error. Fields down the // chain can continue on, trying to parse. return ~suffixPos; } return suffixPos; } } if (!mustParse && !isSupported(period.getPeriodType(), iFieldType)) { // If parsing is not required and the field is not supported, // exit gracefully so that another parser can continue on. return position; } int limit; if (suffixPos > 0) { limit = Math.min(iMaxParsedDigits, suffixPos - position); } else { limit = Math.min(iMaxParsedDigits, text.length() - position); } // validate input number int length = 0; int fractPos = -1; boolean hasDigits = false; while (length < limit) { char c = text.charAt(position + length); // leading sign if (length == 0 && (c == '-' || c == '+') && !iRejectSignedValues) { boolean negative = c == '-'; // Next character must be a digit. if (length + 1 >= limit || (c = text.charAt(position + length + 1)) < '0' || c > '9') { break; } if (negative) { length++; } else { // Skip the '+' for parseInt to succeed. position++; } // Expand the limit to disregard the sign character. limit = Math.min(limit + 1, text.length() - position); continue; } // main number if (c >= '0' && c <= '9') { hasDigits = true; } else { if ((c == '.' || c == ',') && (iFieldType == SECONDS_MILLIS || iFieldType == SECONDS_OPTIONAL_MILLIS)) { if (fractPos >= 0) { // can't have two decimals break; } fractPos = position + length + 1; // Expand the limit to disregard the decimal point. limit = Math.min(limit + 1, text.length() - position); } else { break; } } length++; } if (!hasDigits) { return ~position; } if (suffixPos >= 0 && position + length != suffixPos) { // If there are additional non-digit characters before the // suffix is reached, then assume that the suffix found belongs // to a field not yet reached. Return original position so that // another parser can continue on. return position; } if (iFieldType != SECONDS_MILLIS && iFieldType != SECONDS_OPTIONAL_MILLIS) { // Handle common case. setFieldValue(period, iFieldType, parseInt(text, position, length)); } else if (fractPos < 0) { setFieldValue(period, SECONDS, parseInt(text, position, length)); setFieldValue(period, MILLIS, 0); } else { int wholeValue = parseInt(text, position, fractPos - position - 1); setFieldValue(period, SECONDS, wholeValue); int fractLen = position + length - fractPos; int fractValue; if (fractLen <= 0) { fractValue = 0; } else { if (fractLen >= 3) { fractValue = parseInt(text, fractPos, 3); } else { fractValue = parseInt(text, fractPos, fractLen); if (fractLen == 1) { fractValue *= 100; } else { fractValue *= 10; } } if (wholeValue < 0) { fractValue = -fractValue; } } setFieldValue(period, MILLIS, fractValue); } position += length; if (position >= 0 && iSuffix != null) { position = iSuffix.parse(text, position); } return position; } /** * @param text text to parse * @param position position in text * @param length exact count of characters to parse * @return parsed int value */ private int parseInt(String text, int position, int length) { if (length >= 10) { // Since value may exceed max, use stock parser which checks for this. return Integer.parseInt(text.substring(position, position + length)); } if (length <= 0) { return 0; } int value = text.charAt(position++); length--; boolean negative; if (value == '-') { if (--length < 0) { return 0; } negative = true; value = text.charAt(position++); } else { negative = false; } value -= '0'; while (length-- > 0) { value = ((value << 3) + (value << 1)) + text.charAt(position++) - '0'; } return negative ? -value : value; } /** * @return Long.MAX_VALUE if nothing to print, otherwise value */ long getFieldValue(ReadablePeriod period) { PeriodType type; if (iPrintZeroSetting == PRINT_ZERO_ALWAYS) { type = null; // Don't need to check if supported. } else { type = period.getPeriodType(); } if (type != null && isSupported(type, iFieldType) == false) { return Long.MAX_VALUE; } long value; switch (iFieldType) { default: return Long.MAX_VALUE; case YEARS: value = period.get(DurationFieldType.years()); break; case MONTHS: value = period.get(DurationFieldType.months()); break; case WEEKS: value = period.get(DurationFieldType.weeks()); break; case DAYS: value = period.get(DurationFieldType.days()); break; case HOURS: value = period.get(DurationFieldType.hours()); break; case MINUTES: value = period.get(DurationFieldType.minutes()); break; case SECONDS: value = period.get(DurationFieldType.seconds()); break; case MILLIS: value = period.get(DurationFieldType.millis()); break; case SECONDS_MILLIS: // drop through case SECONDS_OPTIONAL_MILLIS: int seconds = period.get(DurationFieldType.seconds()); int millis = period.get(DurationFieldType.millis()); value = (seconds * (long) DateTimeConstants.MILLIS_PER_SECOND) + millis; break; } // determine if period is zero and this is the last field if (value == 0) { switch (iPrintZeroSetting) { case PRINT_ZERO_NEVER: return Long.MAX_VALUE; case PRINT_ZERO_RARELY_LAST: if (isZero(period) && iFieldFormatters[iFieldType] == this) { for (int i = iFieldType + 1; i <= MAX_FIELD; i++) { if (isSupported(type, i) && iFieldFormatters[i] != null) { return Long.MAX_VALUE; } } } else { return Long.MAX_VALUE; } break; case PRINT_ZERO_RARELY_FIRST: if (isZero(period) && iFieldFormatters[iFieldType] == this) { int i = Math.min(iFieldType, 8); // line split out for IBM JDK i--; // see bug 1660490 for (; i >= 0 && i <= MAX_FIELD; i--) { if (isSupported(type, i) && iFieldFormatters[i] != null) { return Long.MAX_VALUE; } } } else { return Long.MAX_VALUE; } break; } } return value; } boolean isZero(ReadablePeriod period) { for (int i = 0, isize = period.size(); i < isize; i++) { if (period.getValue(i) != 0) { return false; } } return true; } boolean isSupported(PeriodType type, int field) { switch (field) { default: return false; case YEARS: return type.isSupported(DurationFieldType.years()); case MONTHS: return type.isSupported(DurationFieldType.months()); case WEEKS: return type.isSupported(DurationFieldType.weeks()); case DAYS: return type.isSupported(DurationFieldType.days()); case HOURS: return type.isSupported(DurationFieldType.hours()); case MINUTES: return type.isSupported(DurationFieldType.minutes()); case SECONDS: return type.isSupported(DurationFieldType.seconds()); case MILLIS: return type.isSupported(DurationFieldType.millis()); case SECONDS_MILLIS: // drop through case SECONDS_OPTIONAL_MILLIS: return type.isSupported(DurationFieldType.seconds()) || type.isSupported(DurationFieldType.millis()); } } void setFieldValue(ReadWritablePeriod period, int field, int value) { switch (field) { default: break; case YEARS: period.setYears(value); break; case MONTHS: period.setMonths(value); break; case WEEKS: period.setWeeks(value); break; case DAYS: period.setDays(value); break; case HOURS: period.setHours(value); break; case MINUTES: period.setMinutes(value); break; case SECONDS: period.setSeconds(value); break; case MILLIS: period.setMillis(value); break; } } int getFieldType() { return iFieldType; } } //----------------------------------------------------------------------- /** * Handles a simple literal piece of text. */ static class Literal implements PeriodPrinter, PeriodParser { static final Literal EMPTY = new Literal(""); private final String iText; Literal(String text) { iText = text; } public int countFieldsToPrint(ReadablePeriod period, int stopAt, Locale locale) { return 0; } public int calculatePrintedLength(ReadablePeriod period, Locale locale) { return iText.length(); } public void printTo(StringBuffer buf, ReadablePeriod period, Locale locale) { buf.append(iText); } public void printTo(Writer out, ReadablePeriod period, Locale locale) throws IOException { out.write(iText); } public int parseInto( ReadWritablePeriod period, String periodStr, int position, Locale locale) { if (periodStr.regionMatches(true, position, iText, 0, iText.length())) { return position + iText.length(); } return ~position; } } //----------------------------------------------------------------------- /** * Handles a separator, that splits the fields into multiple parts. * For example, the 'T' in the ISO8601 standard. */ static class Separator implements PeriodPrinter, PeriodParser { private final String iText; private final String iFinalText; private final String[] iParsedForms; private final boolean iUseBefore; private final boolean iUseAfter; private final PeriodPrinter iBeforePrinter; private volatile PeriodPrinter iAfterPrinter; private final PeriodParser iBeforeParser; private volatile PeriodParser iAfterParser; Separator(String text, String finalText, String[] variants, PeriodPrinter beforePrinter, PeriodParser beforeParser, boolean useBefore, boolean useAfter) { iText = text; iFinalText = finalText; if ((finalText == null || text.equals(finalText)) && (variants == null || variants.length == 0)) { iParsedForms = new String[] {text}; } else { // Filter and reverse sort the parsed forms. TreeSet parsedSet = new TreeSet(String.CASE_INSENSITIVE_ORDER); parsedSet.add(text); parsedSet.add(finalText); if (variants != null) { for (int i=variants.length; --i>=0; ) { parsedSet.add(variants[i]); } } ArrayList parsedList = new ArrayList(parsedSet); Collections.reverse(parsedList); iParsedForms = parsedList.toArray(new String[parsedList.size()]); } iBeforePrinter = beforePrinter; iBeforeParser = beforeParser; iUseBefore = useBefore; iUseAfter = useAfter; } public int countFieldsToPrint(ReadablePeriod period, int stopAt, Locale locale) { int sum = iBeforePrinter.countFieldsToPrint(period, stopAt, locale); if (sum < stopAt) { sum += iAfterPrinter.countFieldsToPrint(period, stopAt, locale); } return sum; } public int calculatePrintedLength(ReadablePeriod period, Locale locale) { PeriodPrinter before = iBeforePrinter; PeriodPrinter after = iAfterPrinter; int sum = before.calculatePrintedLength(period, locale) + after.calculatePrintedLength(period, locale); if (iUseBefore) { if (before.countFieldsToPrint(period, 1, locale) > 0) { if (iUseAfter) { int afterCount = after.countFieldsToPrint(period, 2, locale); if (afterCount > 0) { sum += (afterCount > 1 ? iText : iFinalText).length(); } } else { sum += iText.length(); } } } else if (iUseAfter && after.countFieldsToPrint(period, 1, locale) > 0) { sum += iText.length(); } return sum; } public void printTo(StringBuffer buf, ReadablePeriod period, Locale locale) { PeriodPrinter before = iBeforePrinter; PeriodPrinter after = iAfterPrinter; before.printTo(buf, period, locale); if (iUseBefore) { if (before.countFieldsToPrint(period, 1, locale) > 0) { if (iUseAfter) { int afterCount = after.countFieldsToPrint(period, 2, locale); if (afterCount > 0) { buf.append(afterCount > 1 ? iText : iFinalText); } } else { buf.append(iText); } } } else if (iUseAfter && after.countFieldsToPrint(period, 1, locale) > 0) { buf.append(iText); } after.printTo(buf, period, locale); } public void printTo(Writer out, ReadablePeriod period, Locale locale) throws IOException { PeriodPrinter before = iBeforePrinter; PeriodPrinter after = iAfterPrinter; before.printTo(out, period, locale); if (iUseBefore) { if (before.countFieldsToPrint(period, 1, locale) > 0) { if (iUseAfter) { int afterCount = after.countFieldsToPrint(period, 2, locale); if (afterCount > 0) { out.write(afterCount > 1 ? iText : iFinalText); } } else { out.write(iText); } } } else if (iUseAfter && after.countFieldsToPrint(period, 1, locale) > 0) { out.write(iText); } after.printTo(out, period, locale); } public int parseInto( ReadWritablePeriod period, String periodStr, int position, Locale locale) { int oldPos = position; position = iBeforeParser.parseInto(period, periodStr, position, locale); if (position < 0) { return position; } boolean found = false; int parsedFormLength = -1; if (position > oldPos) { // Consume this separator. String[] parsedForms = iParsedForms; int length = parsedForms.length; for (int i=0; i < length; i++) { String parsedForm = parsedForms[i]; if ((parsedForm == null || parsedForm.length() == 0) || periodStr.regionMatches (true, position, parsedForm, 0, parsedForm.length())) { parsedFormLength = (parsedForm == null ? 0 : parsedForm.length()); position += parsedFormLength; found = true; break; } } } oldPos = position; position = iAfterParser.parseInto(period, periodStr, position, locale); if (position < 0) { return position; } if (found && position == oldPos && parsedFormLength > 0) { // Separator should not have been supplied. return ~oldPos; } if (position > oldPos && !found && !iUseBefore) { // Separator was required. return ~oldPos; } return position; } Separator finish(PeriodPrinter afterPrinter, PeriodParser afterParser) { iAfterPrinter = afterPrinter; iAfterParser = afterParser; return this; } } //----------------------------------------------------------------------- /** * Composite implementation that merges other fields to create a full pattern. */ static class Composite implements PeriodPrinter, PeriodParser { private final PeriodPrinter[] iPrinters; private final PeriodParser[] iParsers; Composite(List elementPairs) { List printerList = new ArrayList(); List parserList = new ArrayList(); decompose(elementPairs, printerList, parserList); if (printerList.size() <= 0) { iPrinters = null; } else { iPrinters = printerList.toArray( new PeriodPrinter[printerList.size()]); } if (parserList.size() <= 0) { iParsers = null; } else { iParsers = parserList.toArray( new PeriodParser[parserList.size()]); } } public int countFieldsToPrint(ReadablePeriod period, int stopAt, Locale locale) { int sum = 0; PeriodPrinter[] printers = iPrinters; for (int i=printers.length; sum < stopAt && --i>=0; ) { sum += printers[i].countFieldsToPrint(period, Integer.MAX_VALUE, locale); } return sum; } public int calculatePrintedLength(ReadablePeriod period, Locale locale) { int sum = 0; PeriodPrinter[] printers = iPrinters; for (int i=printers.length; --i>=0; ) { sum += printers[i].calculatePrintedLength(period, locale); } return sum; } public void printTo(StringBuffer buf, ReadablePeriod period, Locale locale) { PeriodPrinter[] printers = iPrinters; int len = printers.length; for (int i=0; i= 0; i++) { position = parsers[i].parseInto(period, periodStr, position, locale); } return position; } private void decompose(List elementPairs, List printerList, List parserList) { int size = elementPairs.size(); for (int i=0; i list, Object[] array) { if (array != null) { for (int i=0; i * This class is the main API for printing and parsing used by most applications. * Instances of this class are created via one of three factory classes: *
    *
  • {@link DateTimeFormat} - formats by pattern and style
  • *
  • {@link ISODateTimeFormat} - ISO8601 formats
  • *
  • {@link DateTimeFormatterBuilder} - complex formats created via method calls
  • *
*

* An instance of this class holds a reference internally to one printer and * one parser. It is possible that one of these may be null, in which case the * formatter cannot print/parse. This can be checked via the {@link #isPrinter()} * and {@link #isParser()} methods. *

* The underlying printer/parser can be altered to behave exactly as required * by using one of the decorator modifiers: *

    *
  • {@link #withLocale(Locale)} - returns a new formatter that uses the specified locale
  • *
  • {@link #withZone(DateTimeZone)} - returns a new formatter that uses the specified time zone
  • *
  • {@link #withChronology(Chronology)} - returns a new formatter that uses the specified chronology
  • *
  • {@link #withOffsetParsed()} - returns a new formatter that returns the parsed time zone offset
  • *
  • {@link #withPivotYear(int)} - returns a new formatter with the specified pivot year
  • *
  • {@link #withDefaultYear(int)} - returns a new formatter with the specified default year
  • *
* Each of these returns a new formatter (instances of this class are immutable). *

* The main methods of the class are the printXxx and * parseXxx methods. These are used as follows: *

 * // print using the defaults (default locale, chronology/zone of the datetime)
 * String dateStr = formatter.print(dt);
 * // print using the French locale
 * String dateStr = formatter.withLocale(Locale.FRENCH).print(dt);
 * // print using the UTC zone
 * String dateStr = formatter.withZone(DateTimeZone.UTC).print(dt);
 * 
 * // parse using the Paris zone
 * DateTime date = formatter.withZone(DateTimeZone.forID("Europe/Paris")).parseDateTime(str);
 * 
* * @author Brian S O'Neill * @author Stephen Colebourne * @author Fredrik Borgh * @since 1.0 */ public class DateTimeFormatter { /** The internal printer used to output the datetime. */ private final DateTimePrinter iPrinter; /** The internal parser used to output the datetime. */ private final DateTimeParser iParser; /** The locale to use for printing and parsing. */ private final Locale iLocale; /** Whether the offset is parsed. */ private final boolean iOffsetParsed; /** The chronology to use as an override. */ private final Chronology iChrono; /** The zone to use as an override. */ private final DateTimeZone iZone; /** The pivot year to use for two-digit year parsing. */ private final Integer iPivotYear; /** The default year for parsing month/day without year. */ private final int iDefaultYear; /** * Creates a new formatter, however you will normally use the factory * or the builder. * * @param printer the internal printer, null if cannot print * @param parser the internal parser, null if cannot parse */ public DateTimeFormatter( DateTimePrinter printer, DateTimeParser parser) { super(); iPrinter = printer; iParser = parser; iLocale = null; iOffsetParsed = false; iChrono = null; iZone = null; iPivotYear = null; iDefaultYear = 2000; } /** * Constructor. */ private DateTimeFormatter( DateTimePrinter printer, DateTimeParser parser, Locale locale, boolean offsetParsed, Chronology chrono, DateTimeZone zone, Integer pivotYear, int defaultYear) { super(); iPrinter = printer; iParser = parser; iLocale = locale; iOffsetParsed = offsetParsed; iChrono = chrono; iZone = zone; iPivotYear = pivotYear; iDefaultYear = defaultYear; } //----------------------------------------------------------------------- /** * Is this formatter capable of printing. * * @return true if this is a printer */ public boolean isPrinter() { return (iPrinter != null); } /** * Gets the internal printer object that performs the real printing work. * * @return the internal printer; is null if printing not supported */ public DateTimePrinter getPrinter() { return iPrinter; } /** * Is this formatter capable of parsing. * * @return true if this is a parser */ public boolean isParser() { return (iParser != null); } /** * Gets the internal parser object that performs the real parsing work. * * @return the internal parser; is null if parsing not supported */ public DateTimeParser getParser() { return iParser; } //----------------------------------------------------------------------- /** * Returns a new formatter with a different locale that will be used * for printing and parsing. *

* A DateTimeFormatter is immutable, so a new instance is returned, * and the original is unaltered and still usable. * * @param locale the locale to use; if null, formatter uses default locale * at invocation time * @return the new formatter */ public DateTimeFormatter withLocale(Locale locale) { if (locale == getLocale() || (locale != null && locale.equals(getLocale()))) { return this; } return new DateTimeFormatter(iPrinter, iParser, locale, iOffsetParsed, iChrono, iZone, iPivotYear, iDefaultYear); } /** * Gets the locale that will be used for printing and parsing. * * @return the locale to use; if null, formatter uses default locale at * invocation time */ public Locale getLocale() { return iLocale; } //----------------------------------------------------------------------- /** * Returns a new formatter that will create a datetime with a time zone * equal to that of the offset of the parsed string. *

* After calling this method, a string '2004-06-09T10:20:30-08:00' will * create a datetime with a zone of -08:00 (a fixed zone, with no daylight * savings rules). If the parsed string represents a local time (no zone * offset) the parsed datetime will be in the default zone. *

* Calling this method sets the override zone to null. * Calling the override zone method sets this flag off. * * @return the new formatter */ public DateTimeFormatter withOffsetParsed() { if (iOffsetParsed == true) { return this; } return new DateTimeFormatter(iPrinter, iParser, iLocale, true, iChrono, null, iPivotYear, iDefaultYear); } /** * Checks whether the offset from the string is used as the zone of * the parsed datetime. * * @return true if the offset from the string is used as the zone */ public boolean isOffsetParsed() { return iOffsetParsed; } //----------------------------------------------------------------------- /** * Returns a new formatter that will use the specified chronology in * preference to that of the printed object, or ISO on a parse. *

* When printing, this chronolgy will be used in preference to the chronology * from the datetime that would otherwise be used. *

* When parsing, this chronology will be set on the parsed datetime. *

* A null chronology means no-override. * If both an override chronology and an override zone are set, the * override zone will take precedence over the zone in the chronology. * * @param chrono the chronology to use as an override * @return the new formatter */ public DateTimeFormatter withChronology(Chronology chrono) { if (iChrono == chrono) { return this; } return new DateTimeFormatter(iPrinter, iParser, iLocale, iOffsetParsed, chrono, iZone, iPivotYear, iDefaultYear); } /** * Gets the chronology to use as an override. * * @return the chronology to use as an override */ public Chronology getChronology() { return iChrono; } /** * Gets the chronology to use as an override. * * @return the chronology to use as an override * @deprecated Use the method with the correct spelling */ @Deprecated public Chronology getChronolgy() { return iChrono; } //----------------------------------------------------------------------- /** * Returns a new formatter that will use the UTC zone in preference * to the zone of the printed object, or default zone on a parse. *

* When printing, UTC will be used in preference to the zone * from the datetime that would otherwise be used. *

* When parsing, UTC will be set on the parsed datetime. *

* If both an override chronology and an override zone are set, the * override zone will take precedence over the zone in the chronology. * * @return the new formatter, never null * @since 2.0 */ public DateTimeFormatter withZoneUTC() { return withZone(DateTimeZone.UTC); } /** * Returns a new formatter that will use the specified zone in preference * to the zone of the printed object, or default zone on a parse. *

* When printing, this zone will be used in preference to the zone * from the datetime that would otherwise be used. *

* When parsing, this zone will be set on the parsed datetime. *

* A null zone means of no-override. * If both an override chronology and an override zone are set, the * override zone will take precedence over the zone in the chronology. * * @param zone the zone to use as an override * @return the new formatter */ public DateTimeFormatter withZone(DateTimeZone zone) { if (iZone == zone) { return this; } return new DateTimeFormatter(iPrinter, iParser, iLocale, false, iChrono, zone, iPivotYear, iDefaultYear); } /** * Gets the zone to use as an override. * * @return the zone to use as an override */ public DateTimeZone getZone() { return iZone; } //----------------------------------------------------------------------- /** * Returns a new formatter that will use the specified pivot year for two * digit year parsing in preference to that stored in the parser. *

* This setting is useful for changing the pivot year of formats built * using a pattern - {@link DateTimeFormat#forPattern(String)}. *

* When parsing, this pivot year is used. Null means no-override. * There is no effect when printing. *

* The pivot year enables a two digit year to be converted to a four * digit year. The pivot represents the year in the middle of the * supported range of years. Thus the full range of years that will * be built is (pivot - 50) .. (pivot + 49). * *

     * pivot   supported range   00 is   20 is   40 is   60 is   80 is
     * ---------------------------------------------------------------
     * 1950      1900..1999      1900    1920    1940    1960    1980
     * 1975      1925..2024      2000    2020    1940    1960    1980
     * 2000      1950..2049      2000    2020    2040    1960    1980
     * 2025      1975..2074      2000    2020    2040    2060    1980
     * 2050      2000..2099      2000    2020    2040    2060    2080
     * 
* * @param pivotYear the pivot year to use as an override when parsing * @return the new formatter * @since 1.1 */ public DateTimeFormatter withPivotYear(Integer pivotYear) { if (iPivotYear == pivotYear || (iPivotYear != null && iPivotYear.equals(pivotYear))) { return this; } return new DateTimeFormatter(iPrinter, iParser, iLocale, iOffsetParsed, iChrono, iZone, pivotYear, iDefaultYear); } /** * Returns a new formatter that will use the specified pivot year for two * digit year parsing in preference to that stored in the parser. *

* This setting is useful for changing the pivot year of formats built * using a pattern - {@link DateTimeFormat#forPattern(String)}. *

* When parsing, this pivot year is used. * There is no effect when printing. *

* The pivot year enables a two digit year to be converted to a four * digit year. The pivot represents the year in the middle of the * supported range of years. Thus the full range of years that will * be built is (pivot - 50) .. (pivot + 49). * *

     * pivot   supported range   00 is   20 is   40 is   60 is   80 is
     * ---------------------------------------------------------------
     * 1950      1900..1999      1900    1920    1940    1960    1980
     * 1975      1925..2024      2000    2020    1940    1960    1980
     * 2000      1950..2049      2000    2020    2040    1960    1980
     * 2025      1975..2074      2000    2020    2040    2060    1980
     * 2050      2000..2099      2000    2020    2040    2060    2080
     * 
* * @param pivotYear the pivot year to use as an override when parsing * @return the new formatter * @since 1.1 */ public DateTimeFormatter withPivotYear(int pivotYear) { return withPivotYear(Integer.valueOf(pivotYear)); } /** * Gets the pivot year to use as an override. * * @return the pivot year to use as an override * @since 1.1 */ public Integer getPivotYear() { return iPivotYear; } //----------------------------------------------------------------------- /** * Returns a new formatter that will use the specified default year. *

* The default year is used when parsing in the case where there is a * month or a day but not a year. Specifically, it is used if there is * a field parsed with a duration between the length of a month and the * length of a day inclusive. *

* This value is typically used to move the year from 1970 to a leap year * to enable February 29th to be parsed. * Unless customised, the year 2000 is used. *

* This setting has no effect when printing. * * @param defaultYear the default year to use * @return the new formatter, not null * @since 2.0 */ public DateTimeFormatter withDefaultYear(int defaultYear) { return new DateTimeFormatter(iPrinter, iParser, iLocale, iOffsetParsed, iChrono, iZone, iPivotYear, defaultYear); } /** * Gets the default year for parsing months and days. * * @return the default year for parsing months and days * @since 2.0 */ public int getDefaultYear() { return iDefaultYear; } //----------------------------------------------------------------------- /** * Prints a ReadableInstant, using the chronology supplied by the instant. * * @param buf the destination to format to, not null * @param instant instant to format, null means now */ public void printTo(StringBuffer buf, ReadableInstant instant) { long millis = DateTimeUtils.getInstantMillis(instant); Chronology chrono = DateTimeUtils.getInstantChronology(instant); printTo(buf, millis, chrono); } /** * Prints a ReadableInstant, using the chronology supplied by the instant. * * @param out the destination to format to, not null * @param instant instant to format, null means now */ public void printTo(Writer out, ReadableInstant instant) throws IOException { long millis = DateTimeUtils.getInstantMillis(instant); Chronology chrono = DateTimeUtils.getInstantChronology(instant); printTo(out, millis, chrono); } /** * Prints a ReadableInstant, using the chronology supplied by the instant. * * @param appendable the destination to format to, not null * @param instant instant to format, null means now * @since 2.0 */ public void printTo(Appendable appendable, ReadableInstant instant) throws IOException { appendable.append(print(instant)); } //----------------------------------------------------------------------- /** * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, * using ISO chronology in the default DateTimeZone. * * @param buf the destination to format to, not null * @param instant millis since 1970-01-01T00:00:00Z */ public void printTo(StringBuffer buf, long instant) { printTo(buf, instant, null); } /** * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, * using ISO chronology in the default DateTimeZone. * * @param out the destination to format to, not null * @param instant millis since 1970-01-01T00:00:00Z */ public void printTo(Writer out, long instant) throws IOException { printTo(out, instant, null); } /** * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, * using ISO chronology in the default DateTimeZone. * * @param appendable the destination to format to, not null * @param instant millis since 1970-01-01T00:00:00Z * @since 2.0 */ public void printTo(Appendable appendable, long instant) throws IOException { appendable.append(print(instant)); } //----------------------------------------------------------------------- /** * Prints a ReadablePartial. *

* Neither the override chronology nor the override zone are used * by this method. * * @param buf the destination to format to, not null * @param partial partial to format */ public void printTo(StringBuffer buf, ReadablePartial partial) { DateTimePrinter printer = requirePrinter(); if (partial == null) { throw new IllegalArgumentException("The partial must not be null"); } printer.printTo(buf, partial, iLocale); } /** * Prints a ReadablePartial. *

* Neither the override chronology nor the override zone are used * by this method. * * @param out the destination to format to, not null * @param partial partial to format */ public void printTo(Writer out, ReadablePartial partial) throws IOException { DateTimePrinter printer = requirePrinter(); if (partial == null) { throw new IllegalArgumentException("The partial must not be null"); } printer.printTo(out, partial, iLocale); } /** * Prints a ReadablePartial. *

* Neither the override chronology nor the override zone are used * by this method. * * @param appendable the destination to format to, not null * @param partial partial to format * @since 2.0 */ public void printTo(Appendable appendable, ReadablePartial partial) throws IOException { appendable.append(print(partial)); } //----------------------------------------------------------------------- /** * Prints a ReadableInstant to a String. *

* This method will use the override zone and the override chronololgy if * they are set. Otherwise it will use the chronology and zone of the instant. * * @param instant instant to format, null means now * @return the printed result */ public String print(ReadableInstant instant) { StringBuffer buf = new StringBuffer(requirePrinter().estimatePrintedLength()); printTo(buf, instant); return buf.toString(); } /** * Prints a millisecond instant to a String. *

* This method will use the override zone and the override chronololgy if * they are set. Otherwise it will use the ISO chronology and default zone. * * @param instant millis since 1970-01-01T00:00:00Z * @return the printed result */ public String print(long instant) { StringBuffer buf = new StringBuffer(requirePrinter().estimatePrintedLength()); printTo(buf, instant); return buf.toString(); } /** * Prints a ReadablePartial to a new String. *

* Neither the override chronology nor the override zone are used * by this method. * * @param partial partial to format * @return the printed result */ public String print(ReadablePartial partial) { StringBuffer buf = new StringBuffer(requirePrinter().estimatePrintedLength()); printTo(buf, partial); return buf.toString(); } private void printTo(StringBuffer buf, long instant, Chronology chrono) { DateTimePrinter printer = requirePrinter(); chrono = selectChronology(chrono); // Shift instant into local time (UTC) to avoid excessive offset // calculations when printing multiple fields in a composite printer. DateTimeZone zone = chrono.getZone(); int offset = zone.getOffset(instant); long adjustedInstant = instant + offset; if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) { // Time zone offset overflow, so revert to UTC. zone = DateTimeZone.UTC; offset = 0; adjustedInstant = instant; } printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale); } private void printTo(Writer buf, long instant, Chronology chrono) throws IOException { DateTimePrinter printer = requirePrinter(); chrono = selectChronology(chrono); // Shift instant into local time (UTC) to avoid excessive offset // calculations when printing multiple fields in a composite printer. DateTimeZone zone = chrono.getZone(); int offset = zone.getOffset(instant); long adjustedInstant = instant + offset; if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) { // Time zone offset overflow, so revert to UTC. zone = DateTimeZone.UTC; offset = 0; adjustedInstant = instant; } printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale); } /** * Checks whether printing is supported. * * @throws UnsupportedOperationException if printing is not supported */ private DateTimePrinter requirePrinter() { DateTimePrinter printer = iPrinter; if (printer == null) { throw new UnsupportedOperationException("Printing not supported"); } return printer; } //----------------------------------------------------------------------- /** * Parses a datetime from the given text, at the given position, saving the * result into the fields of the given ReadWritableInstant. If the parse * succeeds, the return value is the new text position. Note that the parse * may succeed without fully reading the text and in this case those fields * that were read will be set. *

* Only those fields present in the string will be changed in the specified * instant. All other fields will remain unaltered. Thus if the string only * contains a year and a month, then the day and time will be retained from * the input instant. If this is not the behaviour you want, then reset the * fields before calling this method, or use {@link #parseDateTime(String)} * or {@link #parseMutableDateTime(String)}. *

* If it fails, the return value is negative, but the instant may still be * modified. To determine the position where the parse failed, apply the * one's complement operator (~) on the return value. *

* This parse method ignores the {@link #getDefaultYear() default year} and * parses using the year from the supplied instant based on the chronology * and time-zone of the supplied instant. *

* The parse will use the chronology of the instant. * * @param instant an instant that will be modified, not null * @param text the text to parse * @param position position to start parsing from * @return new position, negative value means parse failed - * apply complement operator (~) to get position of failure * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the instant is null * @throws IllegalArgumentException if any field is out of range */ public int parseInto(ReadWritableInstant instant, String text, int position) { DateTimeParser parser = requireParser(); if (instant == null) { throw new IllegalArgumentException("Instant must not be null"); } long instantMillis = instant.getMillis(); Chronology chrono = instant.getChronology(); int defaultYear = DateTimeUtils.getChronology(chrono).year().get(instantMillis); long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis); chrono = selectChronology(chrono); DateTimeParserBucket bucket = new DateTimeParserBucket( instantLocal, chrono, iLocale, iPivotYear, defaultYear); int newPos = parser.parseInto(bucket, text, position); instant.setMillis(bucket.computeMillis(false, text)); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } instant.setChronology(chrono); if (iZone != null) { instant.setZone(iZone); } return newPos; } /** * Parses a datetime from the given text, returning the number of * milliseconds since the epoch, 1970-01-01T00:00:00Z. *

* The parse will use the ISO chronology, and the default time zone. * If the text contains a time zone string then that will be taken into account. * * @param text text to parse * @return parsed value expressed in milliseconds since the epoch * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the text to parse is invalid */ public long parseMillis(String text) { DateTimeParser parser = requireParser(); Chronology chrono = selectChronology(iChrono); DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { return bucket.computeMillis(true, text); } } else { newPos = ~newPos; } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); } /** * Parses only the local date from the given text, returning a new LocalDate. *

* This will parse the text fully according to the formatter, using the UTC zone. * Once parsed, only the local date will be used. * This means that any parsed time, time-zone or offset field is completely ignored. * It also means that the zone and offset-parsed settings are ignored. * * @param text the text to parse, not null * @return the parsed date, never null * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the text to parse is invalid * @since 2.0 */ public LocalDate parseLocalDate(String text) { return parseLocalDateTime(text).toLocalDate(); } /** * Parses only the local time from the given text, returning a new LocalTime. *

* This will parse the text fully according to the formatter, using the UTC zone. * Once parsed, only the local time will be used. * This means that any parsed date, time-zone or offset field is completely ignored. * It also means that the zone and offset-parsed settings are ignored. * * @param text the text to parse, not null * @return the parsed time, never null * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the text to parse is invalid * @since 2.0 */ public LocalTime parseLocalTime(String text) { return parseLocalDateTime(text).toLocalTime(); } /** * Parses only the local date-time from the given text, returning a new LocalDateTime. *

* This will parse the text fully according to the formatter, using the UTC zone. * Once parsed, only the local date-time will be used. * This means that any parsed time-zone or offset field is completely ignored. * It also means that the zone and offset-parsed settings are ignored. * * @param text the text to parse, not null * @return the parsed date-time, never null * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the text to parse is invalid * @since 2.0 */ public LocalDateTime parseLocalDateTime(String text) { DateTimeParser parser = requireParser(); Chronology chrono = selectChronology(null).withUTC(); // always use UTC, avoiding DST gaps DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { long millis = bucket.computeMillis(true, text); if (bucket.getOffsetInteger() != null) { // treat withOffsetParsed() as being true int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } return new LocalDateTime(millis, chrono); } } else { newPos = ~newPos; } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); } /** * Parses a date-time from the given text, returning a new DateTime. *

* The parse will use the zone and chronology specified on this formatter. *

* If the text contains a time zone string then that will be taken into * account in adjusting the time of day as follows. * If the {@link #withOffsetParsed()} has been called, then the resulting * DateTime will have a fixed offset based on the parsed time zone. * Otherwise the resulting DateTime will have the zone of this formatter, * but the parsed zone may have caused the time to be adjusted. * * @param text the text to parse, not null * @return the parsed date-time, never null * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the text to parse is invalid */ public DateTime parseDateTime(String text) { DateTimeParser parser = requireParser(); Chronology chrono = selectChronology(null); DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { long millis = bucket.computeMillis(true, text); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } DateTime dt = new DateTime(millis, chrono); if (iZone != null) { dt = dt.withZone(iZone); } return dt; } } else { newPos = ~newPos; } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); } /** * Parses a date-time from the given text, returning a new MutableDateTime. *

* The parse will use the zone and chronology specified on this formatter. *

* If the text contains a time zone string then that will be taken into * account in adjusting the time of day as follows. * If the {@link #withOffsetParsed()} has been called, then the resulting * DateTime will have a fixed offset based on the parsed time zone. * Otherwise the resulting DateTime will have the zone of this formatter, * but the parsed zone may have caused the time to be adjusted. * * @param text the text to parse, not null * @return the parsed date-time, never null * @throws UnsupportedOperationException if parsing is not supported * @throws IllegalArgumentException if the text to parse is invalid */ public MutableDateTime parseMutableDateTime(String text) { DateTimeParser parser = requireParser(); Chronology chrono = selectChronology(null); DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); if (newPos >= 0) { if (newPos >= text.length()) { long millis = bucket.computeMillis(true, text); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } MutableDateTime dt = new MutableDateTime(millis, chrono); if (iZone != null) { dt.setZone(iZone); } return dt; } } else { newPos = ~newPos; } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); } /** * Checks whether parsing is supported. * * @throws UnsupportedOperationException if parsing is not supported */ private DateTimeParser requireParser() { DateTimeParser parser = iParser; if (parser == null) { throw new UnsupportedOperationException("Parsing not supported"); } return parser; } //----------------------------------------------------------------------- /** * Determines the correct chronology to use. * * @param chrono the proposed chronology * @return the actual chronology */ private Chronology selectChronology(Chronology chrono) { chrono = DateTimeUtils.getChronology(chrono); if (iChrono != null) { chrono = iChrono; } if (iZone != null) { chrono = chrono.withZone(iZone); } return chrono; } } joda-time-2.3/src/main/java/org/joda/time/format/messages_de.properties0000644000175000017500000000122411564251363025547 0ustar ebourgebourgPeriodFormat.space=\ PeriodFormat.comma=, PeriodFormat.commandand=,und PeriodFormat.commaspaceand=, und PeriodFormat.commaspace=, PeriodFormat.spaceandspace=\ und PeriodFormat.year=\ Jahr PeriodFormat.years=\ Jahre PeriodFormat.month=\ Monat PeriodFormat.months=\ Monate PeriodFormat.week=\ Woche PeriodFormat.weeks=\ Wochen PeriodFormat.day=\ Tag PeriodFormat.days=\ Tage PeriodFormat.hour=\ Stunde PeriodFormat.hours=\ Stunden PeriodFormat.minute=\ Minute PeriodFormat.minutes=\ Minuten PeriodFormat.second=\ Sekunde PeriodFormat.seconds=\ Sekunden PeriodFormat.millisecond=\ Millisekunde PeriodFormat.milliseconds=\ Millisekunden joda-time-2.3/src/main/java/org/joda/time/format/DateTimeParser.java0000644000175000017500000000452011564251363024670 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; /** * Internal interface for parsing textual representations of datetimes. *

* Application users will rarely use this class directly. Instead, you * will use one of the factory classes to create a {@link DateTimeFormatter}. *

* The factory classes are:
* - {@link DateTimeFormatterBuilder}
* - {@link DateTimeFormat}
* - {@link ISODateTimeFormat}
* * @author Brian S O'Neill * @see DateTimeFormatter * @see DateTimeFormatterBuilder * @see DateTimeFormat * @since 1.0 */ public interface DateTimeParser { /** * Returns the expected maximum number of characters consumed. * The actual amount should rarely exceed this estimate. * * @return the estimated length */ int estimateParsedLength(); /** * Parse an element from the given text, saving any fields into the given * DateTimeParserBucket. If the parse succeeds, the return value is the new * text position. Note that the parse may succeed without fully reading the * text. *

* If it fails, the return value is negative. To determine the position * where the parse failed, apply the one's complement operator (~) on the * return value. * * @param bucket field are saved into this, not null * @param text the text to parse, not null * @param position position to start parsing from * @return new position, negative value means parse failed - * apply complement operator (~) to get position of failure * @throws IllegalArgumentException if any field is out of range */ int parseInto(DateTimeParserBucket bucket, String text, int position); } joda-time-2.3/src/main/java/org/joda/time/format/ISODateTimeFormat.java0000644000175000017500000021634412200512742025235 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.joda.time.DateTimeFieldType; /** * Factory that creates instances of DateTimeFormatter for the ISO8601 standard. *

* Datetime formatting is performed by the {@link DateTimeFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link DateTimeFormat} and {@link DateTimeFormatterBuilder}. *

* ISO8601 is the international standard for data interchange. It defines a * framework, rather than an absolute standard. As a result this provider has a * number of methods that represent common uses of the framework. The most common * formats are {@link #date() date}, {@link #time() time}, and {@link #dateTime() dateTime}. *

* For example, to format a date time in ISO format: *

 * DateTime dt = new DateTime();
 * DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
 * String str = fmt.print(dt);
 * 
*

* It is important to understand that these formatters are not linked to * the ISOChronology. These formatters may be used with any * chronology, however there may be certain side effects with more unusual * chronologies. For example, the ISO formatters rely on dayOfWeek being * single digit, dayOfMonth being two digit and dayOfYear being three digit. * A chronology with a ten day week would thus cause issues. However, in * general, it is safe to use these formatters with other chronologies. *

* ISODateTimeFormat is thread-safe and immutable, and the formatters it * returns are as well. * * @author Brian S O'Neill * @since 1.0 * @see DateTimeFormat * @see DateTimeFormatterBuilder */ public class ISODateTimeFormat { /** * Constructor. * * @since 1.1 (previously private) */ protected ISODateTimeFormat() { super(); } //----------------------------------------------------------------------- /** * Returns a formatter that outputs only those fields specified. *

* This method examines the fields provided and returns an ISO-style * formatter that best fits. This can be useful for outputting * less-common ISO styles, such as YearMonth (YYYY-MM) or MonthDay (--MM-DD). *

* The list provided may have overlapping fields, such as dayOfWeek and * dayOfMonth. In this case, the style is chosen based on the following * list, thus in the example, the calendar style is chosen as dayOfMonth * is higher in priority than dayOfWeek: *

    *
  • monthOfYear - calendar date style *
  • dayOfYear - ordinal date style *
  • weekOfWeekYear - week date style *
  • dayOfMonth - calendar date style *
  • dayOfWeek - week date style *
  • year *
  • weekyear *
* The supported formats are: *
     * Extended      Basic       Fields
     * 2005-03-25    20050325    year/monthOfYear/dayOfMonth
     * 2005-03       2005-03     year/monthOfYear
     * 2005--25      2005--25    year/dayOfMonth *
     * 2005          2005        year
     * --03-25       --0325      monthOfYear/dayOfMonth
     * --03          --03        monthOfYear
     * ---03         ---03       dayOfMonth
     * 2005-084      2005084     year/dayOfYear
     * -084          -084        dayOfYear
     * 2005-W12-5    2005W125    weekyear/weekOfWeekyear/dayOfWeek
     * 2005-W-5      2005W-5     weekyear/dayOfWeek *
     * 2005-W12      2005W12     weekyear/weekOfWeekyear
     * -W12-5        -W125       weekOfWeekyear/dayOfWeek
     * -W12          -W12        weekOfWeekyear
     * -W-5          -W-5        dayOfWeek
     * 10:20:30.040  102030.040  hour/minute/second/milli
     * 10:20:30      102030      hour/minute/second
     * 10:20         1020        hour/minute
     * 10            10          hour
     * -20:30.040    -2030.040   minute/second/milli
     * -20:30        -2030       minute/second
     * -20           -20         minute
     * --30.040      --30.040    second/milli
     * --30          --30        second
     * ---.040       ---.040     milli *
     * 10-30.040     10-30.040   hour/second/milli *
     * 10:20-.040    1020-.040   hour/minute/milli *
     * 10-30         10-30       hour/second *
     * 10--.040      10--.040    hour/milli *
     * -20-.040      -20-.040    minute/milli *
     *   plus datetime formats like {date}T{time}
     * 
* * indiates that this is not an official ISO format and can be excluded * by passing in strictISO as true. *

* This method can side effect the input collection of fields. * If the input collection is modifiable, then each field that was added to * the formatter will be removed from the collection, including any duplicates. * If the input collection is unmodifiable then no side effect occurs. *

* This side effect processing is useful if you need to know whether all * the fields were converted into the formatter or not. To achieve this, * pass in a modifiable list, and check that it is empty on exit. * * @param fields the fields to get a formatter for, not null, * updated by the method call unless unmodifiable, * removing those fields built in the formatter * @param extended true to use the extended format (with separators) * @param strictISO true to stick exactly to ISO8601, false to include additional formats * @return a suitable formatter * @throws IllegalArgumentException if there is no format for the fields * @since 1.1 */ public static DateTimeFormatter forFields( Collection fields, boolean extended, boolean strictISO) { if (fields == null || fields.size() == 0) { throw new IllegalArgumentException("The fields must not be null or empty"); } Set workingFields = new HashSet(fields); int inputSize = workingFields.size(); boolean reducedPrec = false; DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); // date if (workingFields.contains(DateTimeFieldType.monthOfYear())) { reducedPrec = dateByMonth(bld, workingFields, extended, strictISO); } else if (workingFields.contains(DateTimeFieldType.dayOfYear())) { reducedPrec = dateByOrdinal(bld, workingFields, extended, strictISO); } else if (workingFields.contains(DateTimeFieldType.weekOfWeekyear())) { reducedPrec = dateByWeek(bld, workingFields, extended, strictISO); } else if (workingFields.contains(DateTimeFieldType.dayOfMonth())) { reducedPrec = dateByMonth(bld, workingFields, extended, strictISO); } else if (workingFields.contains(DateTimeFieldType.dayOfWeek())) { reducedPrec = dateByWeek(bld, workingFields, extended, strictISO); } else if (workingFields.remove(DateTimeFieldType.year())) { bld.append(Constants.ye); reducedPrec = true; } else if (workingFields.remove(DateTimeFieldType.weekyear())) { bld.append(Constants.we); reducedPrec = true; } boolean datePresent = (workingFields.size() < inputSize); // time time(bld, workingFields, extended, strictISO, reducedPrec, datePresent); // result if (bld.canBuildFormatter() == false) { throw new IllegalArgumentException("No valid format for fields: " + fields); } // side effect the input collection to indicate the processed fields // handling unmodifiable collections with no side effect try { fields.retainAll(workingFields); } catch (UnsupportedOperationException ex) { // ignore, so we can handle unmodifiable collections } return bld.toFormatter(); } //----------------------------------------------------------------------- /** * Creates a date using the calendar date format. * Specification reference: 5.2.1. * * @param bld the builder * @param fields the fields * @param extended true to use extended format * @param strictISO true to only allow ISO formats * @return true if reduced precision * @since 1.1 */ private static boolean dateByMonth( DateTimeFormatterBuilder bld, Collection fields, boolean extended, boolean strictISO) { boolean reducedPrec = false; if (fields.remove(DateTimeFieldType.year())) { bld.append(Constants.ye); if (fields.remove(DateTimeFieldType.monthOfYear())) { if (fields.remove(DateTimeFieldType.dayOfMonth())) { // YYYY-MM-DD/YYYYMMDD appendSeparator(bld, extended); bld.appendMonthOfYear(2); appendSeparator(bld, extended); bld.appendDayOfMonth(2); } else { // YYYY-MM/YYYY-MM bld.appendLiteral('-'); bld.appendMonthOfYear(2); reducedPrec = true; } } else { if (fields.remove(DateTimeFieldType.dayOfMonth())) { // YYYY--DD/YYYY--DD (non-iso) checkNotStrictISO(fields, strictISO); bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendDayOfMonth(2); } else { // YYYY/YYYY reducedPrec = true; } } } else if (fields.remove(DateTimeFieldType.monthOfYear())) { bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendMonthOfYear(2); if (fields.remove(DateTimeFieldType.dayOfMonth())) { // --MM-DD/--MMDD appendSeparator(bld, extended); bld.appendDayOfMonth(2); } else { // --MM/--MM reducedPrec = true; } } else if (fields.remove(DateTimeFieldType.dayOfMonth())) { // ---DD/---DD bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendLiteral('-'); bld.appendDayOfMonth(2); } return reducedPrec; } //----------------------------------------------------------------------- /** * Creates a date using the ordinal date format. * Specification reference: 5.2.2. * * @param bld the builder * @param fields the fields * @param extended true to use extended format * @param strictISO true to only allow ISO formats * @since 1.1 */ private static boolean dateByOrdinal( DateTimeFormatterBuilder bld, Collection fields, boolean extended, boolean strictISO) { boolean reducedPrec = false; if (fields.remove(DateTimeFieldType.year())) { bld.append(Constants.ye); if (fields.remove(DateTimeFieldType.dayOfYear())) { // YYYY-DDD/YYYYDDD appendSeparator(bld, extended); bld.appendDayOfYear(3); } else { // YYYY/YYYY reducedPrec = true; } } else if (fields.remove(DateTimeFieldType.dayOfYear())) { // -DDD/-DDD bld.appendLiteral('-'); bld.appendDayOfYear(3); } return reducedPrec; } //----------------------------------------------------------------------- /** * Creates a date using the calendar date format. * Specification reference: 5.2.3. * * @param bld the builder * @param fields the fields * @param extended true to use extended format * @param strictISO true to only allow ISO formats * @since 1.1 */ private static boolean dateByWeek( DateTimeFormatterBuilder bld, Collection fields, boolean extended, boolean strictISO) { boolean reducedPrec = false; if (fields.remove(DateTimeFieldType.weekyear())) { bld.append(Constants.we); if (fields.remove(DateTimeFieldType.weekOfWeekyear())) { appendSeparator(bld, extended); bld.appendLiteral('W'); bld.appendWeekOfWeekyear(2); if (fields.remove(DateTimeFieldType.dayOfWeek())) { // YYYY-WWW-D/YYYYWWWD appendSeparator(bld, extended); bld.appendDayOfWeek(1); } else { // YYYY-WWW/YYYY-WWW reducedPrec = true; } } else { if (fields.remove(DateTimeFieldType.dayOfWeek())) { // YYYY-W-D/YYYYW-D (non-iso) checkNotStrictISO(fields, strictISO); appendSeparator(bld, extended); bld.appendLiteral('W'); bld.appendLiteral('-'); bld.appendDayOfWeek(1); } else { // YYYY/YYYY reducedPrec = true; } } } else if (fields.remove(DateTimeFieldType.weekOfWeekyear())) { bld.appendLiteral('-'); bld.appendLiteral('W'); bld.appendWeekOfWeekyear(2); if (fields.remove(DateTimeFieldType.dayOfWeek())) { // -WWW-D/-WWWD appendSeparator(bld, extended); bld.appendDayOfWeek(1); } else { // -WWW/-WWW reducedPrec = true; } } else if (fields.remove(DateTimeFieldType.dayOfWeek())) { // -W-D/-W-D bld.appendLiteral('-'); bld.appendLiteral('W'); bld.appendLiteral('-'); bld.appendDayOfWeek(1); } return reducedPrec; } //----------------------------------------------------------------------- /** * Adds the time fields to the builder. * Specification reference: 5.3.1. * * @param bld the builder * @param fields the fields * @param extended whether to use the extended format * @param strictISO whether to be strict * @param reducedPrec whether the date was reduced precision * @param datePresent whether there was a date * @since 1.1 */ private static void time( DateTimeFormatterBuilder bld, Collection fields, boolean extended, boolean strictISO, boolean reducedPrec, boolean datePresent) { boolean hour = fields.remove(DateTimeFieldType.hourOfDay()); boolean minute = fields.remove(DateTimeFieldType.minuteOfHour()); boolean second = fields.remove(DateTimeFieldType.secondOfMinute()); boolean milli = fields.remove(DateTimeFieldType.millisOfSecond()); if (!hour && !minute && !second && !milli) { return; } if (hour || minute || second || milli) { if (strictISO && reducedPrec) { throw new IllegalArgumentException("No valid ISO8601 format for fields because Date was reduced precision: " + fields); } if (datePresent) { bld.appendLiteral('T'); } } if (hour && minute && second || (hour && !second && !milli)) { // OK - HMSm/HMS/HM/H - valid in combination with date } else { if (strictISO && datePresent) { throw new IllegalArgumentException("No valid ISO8601 format for fields because Time was truncated: " + fields); } if (!hour && (minute && second || (minute && !milli) || second)) { // OK - MSm/MS/M/Sm/S - valid ISO formats } else { if (strictISO) { throw new IllegalArgumentException("No valid ISO8601 format for fields: " + fields); } } } if (hour) { bld.appendHourOfDay(2); } else if (minute || second || milli) { bld.appendLiteral('-'); } if (extended && hour && minute) { bld.appendLiteral(':'); } if (minute) { bld.appendMinuteOfHour(2); } else if (second || milli) { bld.appendLiteral('-'); } if (extended && minute && second) { bld.appendLiteral(':'); } if (second) { bld.appendSecondOfMinute(2); } else if (milli) { bld.appendLiteral('-'); } if (milli) { bld.appendLiteral('.'); bld.appendMillisOfSecond(3); } } //----------------------------------------------------------------------- /** * Checks that the iso only flag is not set, throwing an exception if it is. * * @param fields the fields * @param strictISO true if only ISO formats allowed * @since 1.1 */ private static void checkNotStrictISO(Collection fields, boolean strictISO) { if (strictISO) { throw new IllegalArgumentException("No valid ISO8601 format for fields: " + fields); } } /** * Appends the separator if necessary. * * @param bld the builder * @param extended whether to append the separator * @param sep the separator * @since 1.1 */ private static void appendSeparator(DateTimeFormatterBuilder bld, boolean extended) { if (extended) { bld.appendLiteral('-'); } } //----------------------------------------------------------------------- /** * Returns a generic ISO date parser for parsing dates with a possible zone. *

* It accepts formats described by the following syntax: *

     * date              = date-element ['T' offset]
     * date-element      = std-date-element | ord-date-element | week-date-element
     * std-date-element  = yyyy ['-' MM ['-' dd]]
     * ord-date-element  = yyyy ['-' DDD]
     * week-date-element = xxxx '-W' ww ['-' e]
     * offset            = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
     * 
*/ public static DateTimeFormatter dateParser() { return Constants.dp; } /** * Returns a generic ISO date parser for parsing local dates. * This parser is initialised with the local (UTC) time zone. *

* It accepts formats described by the following syntax: *

     * date-element      = std-date-element | ord-date-element | week-date-element
     * std-date-element  = yyyy ['-' MM ['-' dd]]
     * ord-date-element  = yyyy ['-' DDD]
     * week-date-element = xxxx '-W' ww ['-' e]
     * 
* @since 1.3 */ public static DateTimeFormatter localDateParser() { return Constants.ldp; } /** * Returns a generic ISO date parser for parsing dates. *

* It accepts formats described by the following syntax: *

     * date-element      = std-date-element | ord-date-element | week-date-element
     * std-date-element  = yyyy ['-' MM ['-' dd]]
     * ord-date-element  = yyyy ['-' DDD]
     * week-date-element = xxxx '-W' ww ['-' e]
     * 
*/ public static DateTimeFormatter dateElementParser() { return Constants.dpe; } /** * Returns a generic ISO time parser for parsing times with a possible zone. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. *

* It accepts formats described by the following syntax: *

     * time           = ['T'] time-element [offset]
     * time-element   = HH [minute-element] | [fraction]
     * minute-element = ':' mm [second-element] | [fraction]
     * second-element = ':' ss [fraction]
     * fraction       = ('.' | ',') digit+
     * offset         = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
     * 
*/ public static DateTimeFormatter timeParser() { return Constants.tp; } /** * Returns a generic ISO time parser for parsing local times. * This parser is initialised with the local (UTC) time zone. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. *

* It accepts formats described by the following syntax: *

     * time           = ['T'] time-element
     * time-element   = HH [minute-element] | [fraction]
     * minute-element = ':' mm [second-element] | [fraction]
     * second-element = ':' ss [fraction]
     * fraction       = ('.' | ',') digit+
     * 
* @since 1.3 */ public static DateTimeFormatter localTimeParser() { return Constants.ltp; } /** * Returns a generic ISO time parser. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. *

* It accepts formats described by the following syntax: *

     * time-element   = HH [minute-element] | [fraction]
     * minute-element = ':' mm [second-element] | [fraction]
     * second-element = ':' ss [fraction]
     * fraction       = ('.' | ',') digit+
     * 
*/ public static DateTimeFormatter timeElementParser() { return Constants.tpe; } /** * Returns a generic ISO datetime parser which parses either a date or * a time or both. The parser is strict by default, thus time string {@code 24:00} cannot be parsed. *

* It accepts formats described by the following syntax: *

     * datetime          = time | date-opt-time
     * time              = 'T' time-element [offset]
     * date-opt-time     = date-element ['T' [time-element] [offset]]
     * date-element      = std-date-element | ord-date-element | week-date-element
     * std-date-element  = yyyy ['-' MM ['-' dd]]
     * ord-date-element  = yyyy ['-' DDD]
     * week-date-element = xxxx '-W' ww ['-' e]
     * time-element      = HH [minute-element] | [fraction]
     * minute-element    = ':' mm [second-element] | [fraction]
     * second-element    = ':' ss [fraction]
     * fraction          = ('.' | ',') digit+
     * offset            = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
     * 
*/ public static DateTimeFormatter dateTimeParser() { return Constants.dtp; } /** * Returns a generic ISO datetime parser where the date is mandatory and * the time is optional. This parser can parse zoned datetimes. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. *

* It accepts formats described by the following syntax: *

     * date-opt-time     = date-element ['T' [time-element] [offset]]
     * date-element      = std-date-element | ord-date-element | week-date-element
     * std-date-element  = yyyy ['-' MM ['-' dd]]
     * ord-date-element  = yyyy ['-' DDD]
     * week-date-element = xxxx '-W' ww ['-' e]
     * time-element      = HH [minute-element] | [fraction]
     * minute-element    = ':' mm [second-element] | [fraction]
     * second-element    = ':' ss [fraction]
     * fraction          = ('.' | ',') digit+
     * 
* @since 1.3 */ public static DateTimeFormatter dateOptionalTimeParser() { return Constants.dotp; } /** * Returns a generic ISO datetime parser where the date is mandatory and * the time is optional. This parser only parses local datetimes. * This parser is initialised with the local (UTC) time zone. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. *

* It accepts formats described by the following syntax: *

     * datetime          = date-element ['T' time-element]
     * date-element      = std-date-element | ord-date-element | week-date-element
     * std-date-element  = yyyy ['-' MM ['-' dd]]
     * ord-date-element  = yyyy ['-' DDD]
     * week-date-element = xxxx '-W' ww ['-' e]
     * time-element      = HH [minute-element] | [fraction]
     * minute-element    = ':' mm [second-element] | [fraction]
     * second-element    = ':' ss [fraction]
     * fraction          = ('.' | ',') digit+
     * 
* @since 1.3 */ public static DateTimeFormatter localDateOptionalTimeParser() { return Constants.ldotp; } //----------------------------------------------------------------------- /** * Returns a formatter for a full date as four digit year, two digit month * of year, and two digit day of month (yyyy-MM-dd). * * @return a formatter for yyyy-MM-dd */ public static DateTimeFormatter date() { return yearMonthDay(); } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, three digit fraction of second, and * time zone offset (HH:mm:ss.SSSZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for HH:mm:ss.SSSZZ */ public static DateTimeFormatter time() { return Constants.t; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and time zone offset (HH:mm:ssZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for HH:mm:ssZZ */ public static DateTimeFormatter timeNoMillis() { return Constants.tx; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, three digit fraction of second, and * time zone offset prefixed by 'T' ('T'HH:mm:ss.SSSZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for 'T'HH:mm:ss.SSSZZ */ public static DateTimeFormatter tTime() { return Constants.tt; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and time zone offset prefixed * by 'T' ('T'HH:mm:ssZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for 'T'HH:mm:ssZZ */ public static DateTimeFormatter tTimeNoMillis() { return Constants.ttx; } /** * Returns a formatter that combines a full date and time, separated by a 'T' * (yyyy-MM-dd'T'HH:mm:ss.SSSZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSSZZ */ public static DateTimeFormatter dateTime() { return Constants.dt; } /** * Returns a formatter that combines a full date and time without millis, * separated by a 'T' (yyyy-MM-dd'T'HH:mm:ssZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ssZZ */ public static DateTimeFormatter dateTimeNoMillis() { return Constants.dtx; } /** * Returns a formatter for a full ordinal date, using a four * digit year and three digit dayOfYear (yyyy-DDD). * * @return a formatter for yyyy-DDD * @since 1.1 */ public static DateTimeFormatter ordinalDate() { return Constants.od; } /** * Returns a formatter for a full ordinal date and time, using a four * digit year and three digit dayOfYear (yyyy-DDD'T'HH:mm:ss.SSSZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyy-DDD'T'HH:mm:ss.SSSZZ * @since 1.1 */ public static DateTimeFormatter ordinalDateTime() { return Constants.odt; } /** * Returns a formatter for a full ordinal date and time without millis, * using a four digit year and three digit dayOfYear (yyyy-DDD'T'HH:mm:ssZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyy-DDD'T'HH:mm:ssZZ * @since 1.1 */ public static DateTimeFormatter ordinalDateTimeNoMillis() { return Constants.odtx; } /** * Returns a formatter for a full date as four digit weekyear, two digit * week of weekyear, and one digit day of week (xxxx-'W'ww-e). * * @return a formatter for xxxx-'W'ww-e */ public static DateTimeFormatter weekDate() { return Constants.wwd; } /** * Returns a formatter that combines a full weekyear date and time, * separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ss.SSSZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for xxxx-'W'ww-e'T'HH:mm:ss.SSSZZ */ public static DateTimeFormatter weekDateTime() { return Constants.wdt; } /** * Returns a formatter that combines a full weekyear date and time without millis, * separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ssZZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for xxxx-'W'ww-e'T'HH:mm:ssZZ */ public static DateTimeFormatter weekDateTimeNoMillis() { return Constants.wdtx; } //----------------------------------------------------------------------- /** * Returns a basic formatter for a full date as four digit year, two digit * month of year, and two digit day of month (yyyyMMdd). * * @return a formatter for yyyyMMdd */ public static DateTimeFormatter basicDate() { return Constants.bd; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, three digit millis, and time zone * offset (HHmmss.SSSZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for HHmmss.SSSZ */ public static DateTimeFormatter basicTime() { return Constants.bt; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, and time zone offset (HHmmssZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for HHmmssZ */ public static DateTimeFormatter basicTimeNoMillis() { return Constants.btx; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, three digit millis, and time zone * offset prefixed by 'T' ('T'HHmmss.SSSZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for 'T'HHmmss.SSSZ */ public static DateTimeFormatter basicTTime() { return Constants.btt; } /** * Returns a basic formatter for a two digit hour of day, two digit minute * of hour, two digit second of minute, and time zone offset prefixed by 'T' * ('T'HHmmssZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for 'T'HHmmssZ */ public static DateTimeFormatter basicTTimeNoMillis() { return Constants.bttx; } /** * Returns a basic formatter that combines a basic date and time, separated * by a 'T' (yyyyMMdd'T'HHmmss.SSSZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyyMMdd'T'HHmmss.SSSZ */ public static DateTimeFormatter basicDateTime() { return Constants.bdt; } /** * Returns a basic formatter that combines a basic date and time without millis, * separated by a 'T' (yyyyMMdd'T'HHmmssZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyyMMdd'T'HHmmssZ */ public static DateTimeFormatter basicDateTimeNoMillis() { return Constants.bdtx; } /** * Returns a formatter for a full ordinal date, using a four * digit year and three digit dayOfYear (yyyyDDD). * * @return a formatter for yyyyDDD * @since 1.1 */ public static DateTimeFormatter basicOrdinalDate() { return Constants.bod; } /** * Returns a formatter for a full ordinal date and time, using a four * digit year and three digit dayOfYear (yyyyDDD'T'HHmmss.SSSZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyyDDD'T'HHmmss.SSSZ * @since 1.1 */ public static DateTimeFormatter basicOrdinalDateTime() { return Constants.bodt; } /** * Returns a formatter for a full ordinal date and time without millis, * using a four digit year and three digit dayOfYear (yyyyDDD'T'HHmmssZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for yyyyDDD'T'HHmmssZ * @since 1.1 */ public static DateTimeFormatter basicOrdinalDateTimeNoMillis() { return Constants.bodtx; } /** * Returns a basic formatter for a full date as four digit weekyear, two * digit week of weekyear, and one digit day of week (xxxx'W'wwe). * * @return a formatter for xxxx'W'wwe */ public static DateTimeFormatter basicWeekDate() { return Constants.bwd; } /** * Returns a basic formatter that combines a basic weekyear date and time, * separated by a 'T' (xxxx'W'wwe'T'HHmmss.SSSZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for xxxx'W'wwe'T'HHmmss.SSSZ */ public static DateTimeFormatter basicWeekDateTime() { return Constants.bwdt; } /** * Returns a basic formatter that combines a basic weekyear date and time * without millis, separated by a 'T' (xxxx'W'wwe'T'HHmmssZ). * The time zone offset is 'Z' for zero, and of the form '\u00b1HHmm' for non-zero. * The parser is strict by default, thus time string {@code 24:00} cannot be parsed. * * @return a formatter for xxxx'W'wwe'T'HHmmssZ */ public static DateTimeFormatter basicWeekDateTimeNoMillis() { return Constants.bwdtx; } //----------------------------------------------------------------------- /** * Returns a formatter for a four digit year. (yyyy) * * @return a formatter for yyyy */ public static DateTimeFormatter year() { return Constants.ye; } /** * Returns a formatter for a four digit year and two digit month of * year. (yyyy-MM) * * @return a formatter for yyyy-MM */ public static DateTimeFormatter yearMonth() { return Constants.ym; } /** * Returns a formatter for a four digit year, two digit month of year, and * two digit day of month. (yyyy-MM-dd) * * @return a formatter for yyyy-MM-dd */ public static DateTimeFormatter yearMonthDay() { return Constants.ymd; } /** * Returns a formatter for a four digit weekyear. (xxxx) * * @return a formatter for xxxx */ public static DateTimeFormatter weekyear() { return Constants.we; } /** * Returns a formatter for a four digit weekyear and two digit week of * weekyear. (xxxx-'W'ww) * * @return a formatter for xxxx-'W'ww */ public static DateTimeFormatter weekyearWeek() { return Constants.ww; } /** * Returns a formatter for a four digit weekyear, two digit week of * weekyear, and one digit day of week. (xxxx-'W'ww-e) * * @return a formatter for xxxx-'W'ww-e */ public static DateTimeFormatter weekyearWeekDay() { return Constants.wwd; } /** * Returns a formatter for a two digit hour of day. (HH) * * @return a formatter for HH */ public static DateTimeFormatter hour() { return Constants.hde; } /** * Returns a formatter for a two digit hour of day and two digit minute of * hour. (HH:mm) * * @return a formatter for HH:mm */ public static DateTimeFormatter hourMinute() { return Constants.hm; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, and two digit second of minute. (HH:mm:ss) * * @return a formatter for HH:mm:ss */ public static DateTimeFormatter hourMinuteSecond() { return Constants.hms; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and three digit fraction of * second (HH:mm:ss.SSS). Parsing will parse up to 3 fractional second * digits. * * @return a formatter for HH:mm:ss.SSS */ public static DateTimeFormatter hourMinuteSecondMillis() { return Constants.hmsl; } /** * Returns a formatter for a two digit hour of day, two digit minute of * hour, two digit second of minute, and three digit fraction of * second (HH:mm:ss.SSS). Parsing will parse up to 9 fractional second * digits, throwing away all except the first three. * * @return a formatter for HH:mm:ss.SSS */ public static DateTimeFormatter hourMinuteSecondFraction() { return Constants.hmsf; } /** * Returns a formatter that combines a full date and two digit hour of * day. (yyyy-MM-dd'T'HH) * * @return a formatter for yyyy-MM-dd'T'HH */ public static DateTimeFormatter dateHour() { return Constants.dh; } /** * Returns a formatter that combines a full date, two digit hour of day, * and two digit minute of hour. (yyyy-MM-dd'T'HH:mm) * * @return a formatter for yyyy-MM-dd'T'HH:mm */ public static DateTimeFormatter dateHourMinute() { return Constants.dhm; } /** * Returns a formatter that combines a full date, two digit hour of day, * two digit minute of hour, and two digit second of * minute. (yyyy-MM-dd'T'HH:mm:ss) * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss */ public static DateTimeFormatter dateHourMinuteSecond() { return Constants.dhms; } /** * Returns a formatter that combines a full date, two digit hour of day, * two digit minute of hour, two digit second of minute, and three digit * fraction of second (yyyy-MM-dd'T'HH:mm:ss.SSS). Parsing will parse up * to 3 fractional second digits. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS */ public static DateTimeFormatter dateHourMinuteSecondMillis() { return Constants.dhmsl; } /** * Returns a formatter that combines a full date, two digit hour of day, * two digit minute of hour, two digit second of minute, and three digit * fraction of second (yyyy-MM-dd'T'HH:mm:ss.SSS). Parsing will parse up * to 9 fractional second digits, throwing away all except the first three. * * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS */ public static DateTimeFormatter dateHourMinuteSecondFraction() { return Constants.dhmsf; } //----------------------------------------------------------------------- static final class Constants { private static final DateTimeFormatter ye = yearElement(), // year element (yyyy) mye = monthElement(), // monthOfYear element (-MM) dme = dayOfMonthElement(), // dayOfMonth element (-dd) we = weekyearElement(), // weekyear element (xxxx) wwe = weekElement(), // weekOfWeekyear element (-ww) dwe = dayOfWeekElement(), // dayOfWeek element (-ee) dye = dayOfYearElement(), // dayOfYear element (-DDD) hde = hourElement(), // hourOfDay element (HH) mhe = minuteElement(), // minuteOfHour element (:mm) sme = secondElement(), // secondOfMinute element (:ss) fse = fractionElement(), // fractionOfSecond element (.SSSSSSSSS) ze = offsetElement(), // zone offset element lte = literalTElement(), // literal 'T' element //y, // year (same as year element) ym = yearMonth(), // year month ymd = yearMonthDay(), // year month day //w, // weekyear (same as weekyear element) ww = weekyearWeek(), // weekyear week wwd = weekyearWeekDay(), // weekyear week day //h, // hour (same as hour element) hm = hourMinute(), // hour minute hms = hourMinuteSecond(), // hour minute second hmsl = hourMinuteSecondMillis(), // hour minute second millis hmsf = hourMinuteSecondFraction(), // hour minute second fraction dh = dateHour(), // date hour dhm = dateHourMinute(), // date hour minute dhms = dateHourMinuteSecond(), // date hour minute second dhmsl = dateHourMinuteSecondMillis(), // date hour minute second millis dhmsf = dateHourMinuteSecondFraction(), // date hour minute second fraction //d, // date (same as ymd) t = time(), // time tx = timeNoMillis(), // time no millis tt = tTime(), // Ttime ttx = tTimeNoMillis(), // Ttime no millis dt = dateTime(), // date time dtx = dateTimeNoMillis(), // date time no millis //wd, // week date (same as wwd) wdt = weekDateTime(), // week date time wdtx = weekDateTimeNoMillis(), // week date time no millis od = ordinalDate(), // ordinal date (same as yd) odt = ordinalDateTime(), // ordinal date time odtx = ordinalDateTimeNoMillis(), // ordinal date time no millis bd = basicDate(), // basic date bt = basicTime(), // basic time btx = basicTimeNoMillis(), // basic time no millis btt = basicTTime(), // basic Ttime bttx = basicTTimeNoMillis(), // basic Ttime no millis bdt = basicDateTime(), // basic date time bdtx = basicDateTimeNoMillis(), // basic date time no millis bod = basicOrdinalDate(), // basic ordinal date bodt = basicOrdinalDateTime(), // basic ordinal date time bodtx = basicOrdinalDateTimeNoMillis(), // basic ordinal date time no millis bwd = basicWeekDate(), // basic week date bwdt = basicWeekDateTime(), // basic week date time bwdtx = basicWeekDateTimeNoMillis(), // basic week date time no millis dpe = dateElementParser(), // date parser element tpe = timeElementParser(), // time parser element dp = dateParser(), // date parser ldp = localDateParser(), // local date parser tp = timeParser(), // time parser ltp = localTimeParser(), // local time parser dtp = dateTimeParser(), // date time parser dotp = dateOptionalTimeParser(), // date optional time parser ldotp = localDateOptionalTimeParser(); // local date optional time parser //----------------------------------------------------------------------- private static DateTimeFormatter dateParser() { if (dp == null) { DateTimeParser tOffset = new DateTimeFormatterBuilder() .appendLiteral('T') .append(offsetElement()).toParser(); return new DateTimeFormatterBuilder() .append(dateElementParser()) .appendOptional(tOffset) .toFormatter(); } return dp; } private static DateTimeFormatter localDateParser() { if (ldp == null) { return dateElementParser().withZoneUTC(); } return ldp; } private static DateTimeFormatter dateElementParser() { if (dpe == null) { return new DateTimeFormatterBuilder() .append(null, new DateTimeParser[] { new DateTimeFormatterBuilder() .append(yearElement()) .appendOptional (new DateTimeFormatterBuilder() .append(monthElement()) .appendOptional(dayOfMonthElement().getParser()) .toParser()) .toParser(), new DateTimeFormatterBuilder() .append(weekyearElement()) .append(weekElement()) .appendOptional(dayOfWeekElement().getParser()) .toParser(), new DateTimeFormatterBuilder() .append(yearElement()) .append(dayOfYearElement()) .toParser() }) .toFormatter(); } return dpe; } private static DateTimeFormatter timeParser() { if (tp == null) { return new DateTimeFormatterBuilder() .appendOptional(literalTElement().getParser()) .append(timeElementParser()) .appendOptional(offsetElement().getParser()) .toFormatter(); } return tp; } private static DateTimeFormatter localTimeParser() { if (ltp == null) { return new DateTimeFormatterBuilder() .appendOptional(literalTElement().getParser()) .append(timeElementParser()) .toFormatter().withZoneUTC(); } return ltp; } private static DateTimeFormatter timeElementParser() { if (tpe == null) { // Decimal point can be either '.' or ',' DateTimeParser decimalPoint = new DateTimeFormatterBuilder() .append(null, new DateTimeParser[] { new DateTimeFormatterBuilder() .appendLiteral('.') .toParser(), new DateTimeFormatterBuilder() .appendLiteral(',') .toParser() }) .toParser(); return new DateTimeFormatterBuilder() // time-element .append(hourElement()) .append (null, new DateTimeParser[] { new DateTimeFormatterBuilder() // minute-element .append(minuteElement()) .append (null, new DateTimeParser[] { new DateTimeFormatterBuilder() // second-element .append(secondElement()) // second fraction .appendOptional(new DateTimeFormatterBuilder() .append(decimalPoint) .appendFractionOfSecond(1, 9) .toParser()) .toParser(), // minute fraction new DateTimeFormatterBuilder() .append(decimalPoint) .appendFractionOfMinute(1, 9) .toParser(), null }) .toParser(), // hour fraction new DateTimeFormatterBuilder() .append(decimalPoint) .appendFractionOfHour(1, 9) .toParser(), null }) .toFormatter(); } return tpe; } private static DateTimeFormatter dateTimeParser() { if (dtp == null) { // This is different from the general time parser in that the 'T' // is required. DateTimeParser time = new DateTimeFormatterBuilder() .appendLiteral('T') .append(timeElementParser()) .appendOptional(offsetElement().getParser()) .toParser(); return new DateTimeFormatterBuilder() .append(null, new DateTimeParser[] {time, dateOptionalTimeParser().getParser()}) .toFormatter(); } return dtp; } private static DateTimeFormatter dateOptionalTimeParser() { if (dotp == null) { DateTimeParser timeOrOffset = new DateTimeFormatterBuilder() .appendLiteral('T') .appendOptional(timeElementParser().getParser()) .appendOptional(offsetElement().getParser()) .toParser(); return new DateTimeFormatterBuilder() .append(dateElementParser()) .appendOptional(timeOrOffset) .toFormatter(); } return dotp; } private static DateTimeFormatter localDateOptionalTimeParser() { if (ldotp == null) { DateTimeParser time = new DateTimeFormatterBuilder() .appendLiteral('T') .append(timeElementParser()) .toParser(); return new DateTimeFormatterBuilder() .append(dateElementParser()) .appendOptional(time) .toFormatter().withZoneUTC(); } return ldotp; } //----------------------------------------------------------------------- private static DateTimeFormatter time() { if (t == null) { return new DateTimeFormatterBuilder() .append(hourMinuteSecondFraction()) .append(offsetElement()) .toFormatter(); } return t; } private static DateTimeFormatter timeNoMillis() { if (tx == null) { return new DateTimeFormatterBuilder() .append(hourMinuteSecond()) .append(offsetElement()) .toFormatter(); } return tx; } private static DateTimeFormatter tTime() { if (tt == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(time()) .toFormatter(); } return tt; } private static DateTimeFormatter tTimeNoMillis() { if (ttx == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(timeNoMillis()) .toFormatter(); } return ttx; } private static DateTimeFormatter dateTime() { if (dt == null) { return new DateTimeFormatterBuilder() .append(date()) .append(tTime()) .toFormatter(); } return dt; } private static DateTimeFormatter dateTimeNoMillis() { if (dtx == null) { return new DateTimeFormatterBuilder() .append(date()) .append(tTimeNoMillis()) .toFormatter(); } return dtx; } private static DateTimeFormatter ordinalDate() { if (od == null) { return new DateTimeFormatterBuilder() .append(yearElement()) .append(dayOfYearElement()) .toFormatter(); } return od; } private static DateTimeFormatter ordinalDateTime() { if (odt == null) { return new DateTimeFormatterBuilder() .append(ordinalDate()) .append(tTime()) .toFormatter(); } return odt; } private static DateTimeFormatter ordinalDateTimeNoMillis() { if (odtx == null) { return new DateTimeFormatterBuilder() .append(ordinalDate()) .append(tTimeNoMillis()) .toFormatter(); } return odtx; } private static DateTimeFormatter weekDateTime() { if (wdt == null) { return new DateTimeFormatterBuilder() .append(weekDate()) .append(tTime()) .toFormatter(); } return wdt; } private static DateTimeFormatter weekDateTimeNoMillis() { if (wdtx == null) { return new DateTimeFormatterBuilder() .append(weekDate()) .append(tTimeNoMillis()) .toFormatter(); } return wdtx; } //----------------------------------------------------------------------- private static DateTimeFormatter basicDate() { if (bd == null) { return new DateTimeFormatterBuilder() .appendYear(4, 4) .appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2) .appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2) .toFormatter(); } return bd; } private static DateTimeFormatter basicTime() { if (bt == null) { return new DateTimeFormatterBuilder() .appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2) .appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2) .appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2) .appendLiteral('.') .appendFractionOfSecond(3, 9) .appendTimeZoneOffset("Z", false, 2, 2) .toFormatter(); } return bt; } private static DateTimeFormatter basicTimeNoMillis() { if (btx == null) { return new DateTimeFormatterBuilder() .appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2) .appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2) .appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2) .appendTimeZoneOffset("Z", false, 2, 2) .toFormatter(); } return btx; } private static DateTimeFormatter basicTTime() { if (btt == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(basicTime()) .toFormatter(); } return btt; } private static DateTimeFormatter basicTTimeNoMillis() { if (bttx == null) { return new DateTimeFormatterBuilder() .append(literalTElement()) .append(basicTimeNoMillis()) .toFormatter(); } return bttx; } private static DateTimeFormatter basicDateTime() { if (bdt == null) { return new DateTimeFormatterBuilder() .append(basicDate()) .append(basicTTime()) .toFormatter(); } return bdt; } private static DateTimeFormatter basicDateTimeNoMillis() { if (bdtx == null) { return new DateTimeFormatterBuilder() .append(basicDate()) .append(basicTTimeNoMillis()) .toFormatter(); } return bdtx; } private static DateTimeFormatter basicOrdinalDate() { if (bod == null) { return new DateTimeFormatterBuilder() .appendYear(4, 4) .appendFixedDecimal(DateTimeFieldType.dayOfYear(), 3) .toFormatter(); } return bod; } private static DateTimeFormatter basicOrdinalDateTime() { if (bodt == null) { return new DateTimeFormatterBuilder() .append(basicOrdinalDate()) .append(basicTTime()) .toFormatter(); } return bodt; } private static DateTimeFormatter basicOrdinalDateTimeNoMillis() { if (bodtx == null) { return new DateTimeFormatterBuilder() .append(basicOrdinalDate()) .append(basicTTimeNoMillis()) .toFormatter(); } return bodtx; } private static DateTimeFormatter basicWeekDate() { if (bwd == null) { return new DateTimeFormatterBuilder() .appendWeekyear(4, 4) .appendLiteral('W') .appendFixedDecimal(DateTimeFieldType.weekOfWeekyear(), 2) .appendFixedDecimal(DateTimeFieldType.dayOfWeek(), 1) .toFormatter(); } return bwd; } private static DateTimeFormatter basicWeekDateTime() { if (bwdt == null) { return new DateTimeFormatterBuilder() .append(basicWeekDate()) .append(basicTTime()) .toFormatter(); } return bwdt; } private static DateTimeFormatter basicWeekDateTimeNoMillis() { if (bwdtx == null) { return new DateTimeFormatterBuilder() .append(basicWeekDate()) .append(basicTTimeNoMillis()) .toFormatter(); } return bwdtx; } //----------------------------------------------------------------------- private static DateTimeFormatter yearMonth() { if (ym == null) { return new DateTimeFormatterBuilder() .append(yearElement()) .append(monthElement()) .toFormatter(); } return ym; } private static DateTimeFormatter yearMonthDay() { if (ymd == null) { return new DateTimeFormatterBuilder() .append(yearElement()) .append(monthElement()) .append(dayOfMonthElement()) .toFormatter(); } return ymd; } private static DateTimeFormatter weekyearWeek() { if (ww == null) { return new DateTimeFormatterBuilder() .append(weekyearElement()) .append(weekElement()) .toFormatter(); } return ww; } private static DateTimeFormatter weekyearWeekDay() { if (wwd == null) { return new DateTimeFormatterBuilder() .append(weekyearElement()) .append(weekElement()) .append(dayOfWeekElement()) .toFormatter(); } return wwd; } private static DateTimeFormatter hourMinute() { if (hm == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .toFormatter(); } return hm; } private static DateTimeFormatter hourMinuteSecond() { if (hms == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .append(secondElement()) .toFormatter(); } return hms; } private static DateTimeFormatter hourMinuteSecondMillis() { if (hmsl == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .append(secondElement()) .appendLiteral('.') .appendFractionOfSecond(3, 3) .toFormatter(); } return hmsl; } private static DateTimeFormatter hourMinuteSecondFraction() { if (hmsf == null) { return new DateTimeFormatterBuilder() .append(hourElement()) .append(minuteElement()) .append(secondElement()) .append(fractionElement()) .toFormatter(); } return hmsf; } private static DateTimeFormatter dateHour() { if (dh == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hour()) .toFormatter(); } return dh; } private static DateTimeFormatter dateHourMinute() { if (dhm == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinute()) .toFormatter(); } return dhm; } private static DateTimeFormatter dateHourMinuteSecond() { if (dhms == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinuteSecond()) .toFormatter(); } return dhms; } private static DateTimeFormatter dateHourMinuteSecondMillis() { if (dhmsl == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinuteSecondMillis()) .toFormatter(); } return dhmsl; } private static DateTimeFormatter dateHourMinuteSecondFraction() { if (dhmsf == null) { return new DateTimeFormatterBuilder() .append(date()) .append(literalTElement()) .append(hourMinuteSecondFraction()) .toFormatter(); } return dhmsf; } //----------------------------------------------------------------------- private static DateTimeFormatter yearElement() { if (ye == null) { return new DateTimeFormatterBuilder() .appendYear(4, 9) .toFormatter(); } return ye; } private static DateTimeFormatter monthElement() { if (mye == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') .appendMonthOfYear(2) .toFormatter(); } return mye; } private static DateTimeFormatter dayOfMonthElement() { if (dme == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') .appendDayOfMonth(2) .toFormatter(); } return dme; } private static DateTimeFormatter weekyearElement() { if (we == null) { return new DateTimeFormatterBuilder() .appendWeekyear(4, 9) .toFormatter(); } return we; } private static DateTimeFormatter weekElement() { if (wwe == null) { return new DateTimeFormatterBuilder() .appendLiteral("-W") .appendWeekOfWeekyear(2) .toFormatter(); } return wwe; } private static DateTimeFormatter dayOfWeekElement() { if (dwe == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') .appendDayOfWeek(1) .toFormatter(); } return dwe; } private static DateTimeFormatter dayOfYearElement() { if (dye == null) { return new DateTimeFormatterBuilder() .appendLiteral('-') .appendDayOfYear(3) .toFormatter(); } return dye; } private static DateTimeFormatter literalTElement() { if (lte == null) { return new DateTimeFormatterBuilder() .appendLiteral('T') .toFormatter(); } return lte; } private static DateTimeFormatter hourElement() { if (hde == null) { return new DateTimeFormatterBuilder() .appendHourOfDay(2) .toFormatter(); } return hde; } private static DateTimeFormatter minuteElement() { if (mhe == null) { return new DateTimeFormatterBuilder() .appendLiteral(':') .appendMinuteOfHour(2) .toFormatter(); } return mhe; } private static DateTimeFormatter secondElement() { if (sme == null) { return new DateTimeFormatterBuilder() .appendLiteral(':') .appendSecondOfMinute(2) .toFormatter(); } return sme; } private static DateTimeFormatter fractionElement() { if (fse == null) { return new DateTimeFormatterBuilder() .appendLiteral('.') // Support parsing up to nanosecond precision even though // those extra digits will be dropped. .appendFractionOfSecond(3, 9) .toFormatter(); } return fse; } private static DateTimeFormatter offsetElement() { if (ze == null) { return new DateTimeFormatterBuilder() .appendTimeZoneOffset("Z", true, 2, 4) .toFormatter(); } return ze; } } } joda-time-2.3/src/main/java/org/joda/time/format/messages_ja.properties0000644000175000017500000000122212071610306025535 0ustar ebourgebourgPeriodFormat.space= PeriodFormat.comma= PeriodFormat.commandand= PeriodFormat.commaspaceand= PeriodFormat.commaspace= PeriodFormat.spaceandspace= PeriodFormat.year=\u5E74 PeriodFormat.years=\u5E74 PeriodFormat.month=\u304B\u6708 PeriodFormat.months=\u304B\u6708 PeriodFormat.week=\u9031\u9593 PeriodFormat.weeks=\u9031\u9593 PeriodFormat.day=\u65E5 PeriodFormat.days=\u65E5 PeriodFormat.hour=\u6642\u9593 PeriodFormat.hours=\u6642\u9593 PeriodFormat.minute=\u5206 PeriodFormat.minutes=\u5206 PeriodFormat.second=\u79D2 PeriodFormat.seconds=\u79D2 PeriodFormat.millisecond=\u30DF\u30EA\u79D2 PeriodFormat.milliseconds=\u30DF\u30EA\u79D2 joda-time-2.3/src/main/java/org/joda/time/format/PeriodFormatter.java0000644000175000017500000002611611763631023025126 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.IOException; import java.io.Writer; import java.util.Locale; import org.joda.time.MutablePeriod; import org.joda.time.Period; import org.joda.time.PeriodType; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadablePeriod; /** * Controls the printing and parsing of a time period to and from a string. *

* This class is the main API for printing and parsing used by most applications. * Instances of this class are created via one of three factory classes: *

    *
  • {@link PeriodFormat} - formats by pattern and style
  • *
  • {@link ISOPeriodFormat} - ISO8601 formats
  • *
  • {@link PeriodFormatterBuilder} - complex formats created via method calls
  • *
*

* An instance of this class holds a reference internally to one printer and * one parser. It is possible that one of these may be null, in which case the * formatter cannot print/parse. This can be checked via the {@link #isPrinter()} * and {@link #isParser()} methods. *

* The underlying printer/parser can be altered to behave exactly as required * by using a decorator modifier: *

    *
  • {@link #withLocale(Locale)} - returns a new formatter that uses the specified locale
  • *
* This returns a new formatter (instances of this class are immutable). *

* The main methods of the class are the printXxx and * parseXxx methods. These are used as follows: *

 * // print using the default locale
 * String periodStr = formatter.print(period);
 * // print using the French locale
 * String periodStr = formatter.withLocale(Locale.FRENCH).print(period);
 * 
 * // parse using the French locale
 * Period date = formatter.withLocale(Locale.FRENCH).parsePeriod(str);
 * 
* * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public class PeriodFormatter { /** The internal printer used to output the datetime. */ private final PeriodPrinter iPrinter; /** The internal parser used to output the datetime. */ private final PeriodParser iParser; /** The locale to use for printing and parsing. */ private final Locale iLocale; /** The period type used in parsing. */ private final PeriodType iParseType; /** * Creates a new formatter, however you will normally use the factory * or the builder. * * @param printer the internal printer, null if cannot print * @param parser the internal parser, null if cannot parse */ public PeriodFormatter( PeriodPrinter printer, PeriodParser parser) { super(); iPrinter = printer; iParser = parser; iLocale = null; iParseType = null; } /** * Constructor. * * @param printer the internal printer, null if cannot print * @param parser the internal parser, null if cannot parse * @param locale the locale to use * @param type the parse period type */ private PeriodFormatter( PeriodPrinter printer, PeriodParser parser, Locale locale, PeriodType type) { super(); iPrinter = printer; iParser = parser; iLocale = locale; iParseType = type; } //----------------------------------------------------------------------- /** * Is this formatter capable of printing. * * @return true if this is a printer */ public boolean isPrinter() { return (iPrinter != null); } /** * Gets the internal printer object that performs the real printing work. * * @return the internal printer */ public PeriodPrinter getPrinter() { return iPrinter; } /** * Is this formatter capable of parsing. * * @return true if this is a parser */ public boolean isParser() { return (iParser != null); } /** * Gets the internal parser object that performs the real parsing work. * * @return the internal parser */ public PeriodParser getParser() { return iParser; } //----------------------------------------------------------------------- /** * Returns a new formatter with a different locale that will be used * for printing and parsing. *

* A PeriodFormatter is immutable, so a new instance is returned, * and the original is unaltered and still usable. * * @param locale the locale to use * @return the new formatter */ public PeriodFormatter withLocale(Locale locale) { if (locale == getLocale() || (locale != null && locale.equals(getLocale()))) { return this; } return new PeriodFormatter(iPrinter, iParser, locale, iParseType); } /** * Gets the locale that will be used for printing and parsing. * * @return the locale to use */ public Locale getLocale() { return iLocale; } //----------------------------------------------------------------------- /** * Returns a new formatter with a different PeriodType for parsing. *

* A PeriodFormatter is immutable, so a new instance is returned, * and the original is unaltered and still usable. * * @param type the type to use in parsing * @return the new formatter */ public PeriodFormatter withParseType(PeriodType type) { if (type == iParseType) { return this; } return new PeriodFormatter(iPrinter, iParser, iLocale, type); } /** * Gets the PeriodType that will be used for parsing. * * @return the parse type to use */ public PeriodType getParseType() { return iParseType; } //----------------------------------------------------------------------- /** * Prints a ReadablePeriod to a StringBuffer. * * @param buf the formatted period is appended to this buffer * @param period the period to format, not null */ public void printTo(StringBuffer buf, ReadablePeriod period) { checkPrinter(); checkPeriod(period); getPrinter().printTo(buf, period, iLocale); } /** * Prints a ReadablePeriod to a Writer. * * @param out the formatted period is written out * @param period the period to format, not null */ public void printTo(Writer out, ReadablePeriod period) throws IOException { checkPrinter(); checkPeriod(period); getPrinter().printTo(out, period, iLocale); } /** * Prints a ReadablePeriod to a new String. * * @param period the period to format, not null * @return the printed result */ public String print(ReadablePeriod period) { checkPrinter(); checkPeriod(period); PeriodPrinter printer = getPrinter(); StringBuffer buf = new StringBuffer(printer.calculatePrintedLength(period, iLocale)); printer.printTo(buf, period, iLocale); return buf.toString(); } /** * Checks whether printing is supported. * * @throws UnsupportedOperationException if printing is not supported */ private void checkPrinter() { if (iPrinter == null) { throw new UnsupportedOperationException("Printing not supported"); } } /** * Checks whether the period is non-null. * * @throws IllegalArgumentException if the period is null */ private void checkPeriod(ReadablePeriod period) { if (period == null) { throw new IllegalArgumentException("Period must not be null"); } } //----------------------------------------------------------------------- /** * Parses a period from the given text, at the given position, saving the * result into the fields of the given ReadWritablePeriod. If the parse * succeeds, the return value is the new text position. Note that the parse * may succeed without fully reading the text. *

* The parse type of the formatter is not used by this method. *

* If it fails, the return value is negative, but the period may still be * modified. To determine the position where the parse failed, apply the * one's complement operator (~) on the return value. * * @param period a period that will be modified * @param text text to parse * @param position position to start parsing from * @return new position, if negative, parse failed. Apply complement * operator (~) to get position of failure * @throws IllegalArgumentException if any field is out of range */ public int parseInto(ReadWritablePeriod period, String text, int position) { checkParser(); checkPeriod(period); return getParser().parseInto(period, text, position, iLocale); } /** * Parses a period from the given text, returning a new Period. * * @param text text to parse * @return parsed value in a Period object * @throws IllegalArgumentException if any field is out of range */ public Period parsePeriod(String text) { checkParser(); return parseMutablePeriod(text).toPeriod(); } /** * Parses a period from the given text, returning a new MutablePeriod. * * @param text text to parse * @return parsed value in a MutablePeriod object * @throws IllegalArgumentException if any field is out of range */ public MutablePeriod parseMutablePeriod(String text) { checkParser(); MutablePeriod period = new MutablePeriod(0, iParseType); int newPos = getParser().parseInto(period, text, 0, iLocale); if (newPos >= 0) { if (newPos >= text.length()) { return period; } } else { newPos = ~newPos; } throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); } /** * Checks whether parsing is supported. * * @throws UnsupportedOperationException if parsing is not supported */ private void checkParser() { if (iParser == null) { throw new UnsupportedOperationException("Parsing not supported"); } } } joda-time-2.3/src/main/java/org/joda/time/format/messages_nl.properties0000644000175000017500000000121111564251363025564 0ustar ebourgebourgPeriodFormat.space=\ PeriodFormat.comma=, PeriodFormat.commandand=,en PeriodFormat.commaspaceand=, en PeriodFormat.commaspace=, PeriodFormat.spaceandspace=\ en PeriodFormat.year=\ jaar PeriodFormat.years=\ jaar PeriodFormat.month=\ maand PeriodFormat.months=\ maanden PeriodFormat.week=\ week PeriodFormat.weeks=\ weken PeriodFormat.day=\ dag PeriodFormat.days=\ dagen PeriodFormat.hour=\ uur PeriodFormat.hours=\ uur PeriodFormat.minute=\ minuut PeriodFormat.minutes=\ minuten PeriodFormat.second=\ seconde PeriodFormat.seconds=\ seconden PeriodFormat.millisecond=\ milliseconde PeriodFormat.milliseconds=\ milliseconden joda-time-2.3/src/main/java/org/joda/time/format/ISOPeriodFormat.java0000644000175000017500000001616411564251363024774 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; /** * Factory that creates instances of PeriodFormatter for the ISO8601 standard. *

* Period formatting is performed by the {@link PeriodFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link PeriodFormat} and {@link PeriodFormatterBuilder}. *

* ISOPeriodFormat is thread-safe and immutable, and the formatters it * returns are as well. * * @author Brian S O'Neill * @since 1.0 * @see PeriodFormat * @see PeriodFormatterBuilder */ public class ISOPeriodFormat { /** Cache of standard format. */ private static PeriodFormatter cStandard; /** Cache of alternate months format. */ private static PeriodFormatter cAlternate; /** Cache of alternate extended months format. */ private static PeriodFormatter cAlternateExtended; /** Cache of alternate weeks format. */ private static PeriodFormatter cAlternateWithWeeks; /** Cache of alternate extended weeks format. */ private static PeriodFormatter cAlternateExtendedWihWeeks; /** * Constructor. * * @since 1.1 (previously private) */ protected ISOPeriodFormat() { super(); } //----------------------------------------------------------------------- /** * The standard ISO format - PyYmMwWdDThHmMsS. * Milliseconds are not output. * Note that the ISO8601 standard actually indicates weeks should not * be shown if any other field is present and vice versa. * * @return the formatter */ public static PeriodFormatter standard() { if (cStandard == null) { cStandard = new PeriodFormatterBuilder() .appendLiteral("P") .appendYears() .appendSuffix("Y") .appendMonths() .appendSuffix("M") .appendWeeks() .appendSuffix("W") .appendDays() .appendSuffix("D") .appendSeparatorIfFieldsAfter("T") .appendHours() .appendSuffix("H") .appendMinutes() .appendSuffix("M") .appendSecondsWithOptionalMillis() .appendSuffix("S") .toFormatter(); } return cStandard; } /** * The alternate ISO format, PyyyymmddThhmmss, which excludes weeks. *

* Even if weeks are present in the period, they are not output. * Fractional seconds (milliseconds) will appear if required. * * @return the formatter */ public static PeriodFormatter alternate() { if (cAlternate == null) { cAlternate = new PeriodFormatterBuilder() .appendLiteral("P") .printZeroAlways() .minimumPrintedDigits(4) .appendYears() .minimumPrintedDigits(2) .appendMonths() .appendDays() .appendSeparatorIfFieldsAfter("T") .appendHours() .appendMinutes() .appendSecondsWithOptionalMillis() .toFormatter(); } return cAlternate; } /** * The alternate ISO format, Pyyyy-mm-ddThh:mm:ss, which excludes weeks. *

* Even if weeks are present in the period, they are not output. * Fractional seconds (milliseconds) will appear if required. * * @return the formatter */ public static PeriodFormatter alternateExtended() { if (cAlternateExtended == null) { cAlternateExtended = new PeriodFormatterBuilder() .appendLiteral("P") .printZeroAlways() .minimumPrintedDigits(4) .appendYears() .appendSeparator("-") .minimumPrintedDigits(2) .appendMonths() .appendSeparator("-") .appendDays() .appendSeparatorIfFieldsAfter("T") .appendHours() .appendSeparator(":") .appendMinutes() .appendSeparator(":") .appendSecondsWithOptionalMillis() .toFormatter(); } return cAlternateExtended; } /** * The alternate ISO format, PyyyyWwwddThhmmss, which excludes months. *

* Even if months are present in the period, they are not output. * Fractional seconds (milliseconds) will appear if required. * * @return the formatter */ public static PeriodFormatter alternateWithWeeks() { if (cAlternateWithWeeks == null) { cAlternateWithWeeks = new PeriodFormatterBuilder() .appendLiteral("P") .printZeroAlways() .minimumPrintedDigits(4) .appendYears() .minimumPrintedDigits(2) .appendPrefix("W") .appendWeeks() .appendDays() .appendSeparatorIfFieldsAfter("T") .appendHours() .appendMinutes() .appendSecondsWithOptionalMillis() .toFormatter(); } return cAlternateWithWeeks; } /** * The alternate ISO format, Pyyyy-Www-ddThh:mm:ss, which excludes months. *

* Even if months are present in the period, they are not output. * Fractional seconds (milliseconds) will appear if required. * * @return the formatter */ public static PeriodFormatter alternateExtendedWithWeeks() { if (cAlternateExtendedWihWeeks == null) { cAlternateExtendedWihWeeks = new PeriodFormatterBuilder() .appendLiteral("P") .printZeroAlways() .minimumPrintedDigits(4) .appendYears() .appendSeparator("-") .minimumPrintedDigits(2) .appendPrefix("W") .appendWeeks() .appendSeparator("-") .appendDays() .appendSeparatorIfFieldsAfter("T") .appendHours() .appendSeparator(":") .appendMinutes() .appendSeparator(":") .appendSecondsWithOptionalMillis() .toFormatter(); } return cAlternateExtendedWihWeeks; } } joda-time-2.3/src/main/java/org/joda/time/format/messages_fr.properties0000644000175000017500000000122411564251363025566 0ustar ebourgebourgPeriodFormat.space=\ PeriodFormat.comma=, PeriodFormat.commandand=,et PeriodFormat.commaspaceand=, et PeriodFormat.commaspace=, PeriodFormat.spaceandspace=\ et PeriodFormat.year=\ année PeriodFormat.years=\ années PeriodFormat.month=\ mois PeriodFormat.months=\ mois PeriodFormat.week=\ semaine PeriodFormat.weeks=\ semaines PeriodFormat.day=\ jour PeriodFormat.days=\ jours PeriodFormat.hour=\ heure PeriodFormat.hours=\ heures PeriodFormat.minute=\ minute PeriodFormat.minutes=\ minutes PeriodFormat.second=\ seconde PeriodFormat.seconds=\ secondes PeriodFormat.millisecond=\ milliseconde PeriodFormat.milliseconds=\ millisecondes joda-time-2.3/src/main/java/org/joda/time/format/messages_pt.properties0000644000175000017500000000120711564251363025603 0ustar ebourgebourgPeriodFormat.space=\ PeriodFormat.comma=, PeriodFormat.commandand=,e PeriodFormat.commaspaceand=, e PeriodFormat.commaspace=, PeriodFormat.spaceandspace=\ e PeriodFormat.year=\ ano PeriodFormat.years=\ anos PeriodFormat.month=\ mês PeriodFormat.months=\ meses PeriodFormat.week=\ semana PeriodFormat.weeks=\ semanas PeriodFormat.day=\ dia PeriodFormat.days=\ dias PeriodFormat.hour=\ hora PeriodFormat.hours=\ horas PeriodFormat.minute=\ minuto PeriodFormat.minutes=\ minutos PeriodFormat.second=\ segundo PeriodFormat.seconds=\ segundos PeriodFormat.millisecond=\ milissegundo PeriodFormat.milliseconds=\ milissegundos joda-time-2.3/src/main/java/org/joda/time/format/DateTimeParserBucket.java0000644000175000017500000004530112072543746026034 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.Arrays; import java.util.Locale; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.IllegalFieldValueException; import org.joda.time.IllegalInstantException; /** * DateTimeParserBucket is an advanced class, intended mainly for parser * implementations. It can also be used during normal parsing operations to * capture more information about the parse. *

* This class allows fields to be saved in any order, but be physically set in * a consistent order. This is useful for parsing against formats that allow * field values to contradict each other. *

* Field values are applied in an order where the "larger" fields are set * first, making their value less likely to stick. A field is larger than * another when it's range duration is longer. If both ranges are the same, * then the larger field has the longer duration. If it cannot be determined * which field is larger, then the fields are set in the order they were saved. *

* For example, these fields were saved in this order: dayOfWeek, monthOfYear, * dayOfMonth, dayOfYear. When computeMillis is called, the fields are set in * this order: monthOfYear, dayOfYear, dayOfMonth, dayOfWeek. *

* DateTimeParserBucket is mutable and not thread-safe. * * @author Brian S O'Neill * @author Fredrik Borgh * @since 1.0 */ public class DateTimeParserBucket { /** The chronology to use for parsing. */ private final Chronology iChrono; private final long iMillis; /** The parsed zone, initialised to formatter zone. */ private DateTimeZone iZone; /** The parsed offset. */ private Integer iOffset; /** The locale to use for parsing. */ private Locale iLocale; /** Used for parsing two-digit years. */ private Integer iPivotYear; /** Used for parsing month/day without year. */ private int iDefaultYear; private SavedField[] iSavedFields = new SavedField[8]; private int iSavedFieldsCount; private boolean iSavedFieldsShared; private Object iSavedState; /** * Constructs a bucket. * * @param instantLocal the initial millis from 1970-01-01T00:00:00, local time * @param chrono the chronology to use * @param locale the locale to use * @deprecated Use longer constructor */ @Deprecated public DateTimeParserBucket(long instantLocal, Chronology chrono, Locale locale) { this(instantLocal, chrono, locale, null, 2000); } /** * Constructs a bucket, with the option of specifying the pivot year for * two-digit year parsing. * * @param instantLocal the initial millis from 1970-01-01T00:00:00, local time * @param chrono the chronology to use * @param locale the locale to use * @param pivotYear the pivot year to use when parsing two-digit years * @since 1.1 * @deprecated Use longer constructor */ @Deprecated public DateTimeParserBucket(long instantLocal, Chronology chrono, Locale locale, Integer pivotYear) { this(instantLocal, chrono, locale, pivotYear, 2000); } /** * Constructs a bucket, with the option of specifying the pivot year for * two-digit year parsing. * * @param instantLocal the initial millis from 1970-01-01T00:00:00, local time * @param chrono the chronology to use * @param locale the locale to use * @param pivotYear the pivot year to use when parsing two-digit years * @since 2.0 */ public DateTimeParserBucket(long instantLocal, Chronology chrono, Locale locale, Integer pivotYear, int defaultYear) { super(); chrono = DateTimeUtils.getChronology(chrono); iMillis = instantLocal; iZone = chrono.getZone(); iChrono = chrono.withUTC(); iLocale = (locale == null ? Locale.getDefault() : locale); iPivotYear = pivotYear; iDefaultYear = defaultYear; } //----------------------------------------------------------------------- /** * Gets the chronology of the bucket, which will be a local (UTC) chronology. */ public Chronology getChronology() { return iChrono; } //----------------------------------------------------------------------- /** * Returns the locale to be used during parsing. * * @return the locale to use */ public Locale getLocale() { return iLocale; } //----------------------------------------------------------------------- /** * Returns the time zone used by computeMillis. */ public DateTimeZone getZone() { return iZone; } /** * Set a time zone to be used when computeMillis is called. */ public void setZone(DateTimeZone zone) { iSavedState = null; iZone = zone; } //----------------------------------------------------------------------- /** * Returns the time zone offset in milliseconds used by computeMillis. * @deprecated use Integer version */ @Deprecated public int getOffset() { return (iOffset != null ? iOffset : 0); } /** * Returns the time zone offset in milliseconds used by computeMillis. */ public Integer getOffsetInteger() { return iOffset; } /** * Set a time zone offset to be used when computeMillis is called. * @deprecated use Integer version */ @Deprecated public void setOffset(int offset) { iSavedState = null; iOffset = offset; } /** * Set a time zone offset to be used when computeMillis is called. */ public void setOffset(Integer offset) { iSavedState = null; iOffset = offset; } //----------------------------------------------------------------------- /** * Returns the default year used when information is incomplete. *

* This is used for two-digit years and when the largest parsed field is * months or days. *

* A null value for two-digit years means to use the value from DateTimeFormatterBuilder. * A null value for month/day only parsing will cause the default of 2000 to be used. * * @return Integer value of the pivot year, null if not set * @since 1.1 */ public Integer getPivotYear() { return iPivotYear; } /** * Sets the pivot year to use when parsing two digit years. *

* If the value is set to null, this will indicate that default * behaviour should be used. * * @param pivotYear the pivot year to use * @since 1.1 */ public void setPivotYear(Integer pivotYear) { iPivotYear = pivotYear; } //----------------------------------------------------------------------- /** * Saves a datetime field value. * * @param field the field, whose chronology must match that of this bucket * @param value the value */ public void saveField(DateTimeField field, int value) { saveField(new SavedField(field, value)); } /** * Saves a datetime field value. * * @param fieldType the field type * @param value the value */ public void saveField(DateTimeFieldType fieldType, int value) { saveField(new SavedField(fieldType.getField(iChrono), value)); } /** * Saves a datetime field text value. * * @param fieldType the field type * @param text the text value * @param locale the locale to use */ public void saveField(DateTimeFieldType fieldType, String text, Locale locale) { saveField(new SavedField(fieldType.getField(iChrono), text, locale)); } private void saveField(SavedField field) { SavedField[] savedFields = iSavedFields; int savedFieldsCount = iSavedFieldsCount; if (savedFieldsCount == savedFields.length || iSavedFieldsShared) { // Expand capacity or merely copy if saved fields are shared. SavedField[] newArray = new SavedField [savedFieldsCount == savedFields.length ? savedFieldsCount * 2 : savedFields.length]; System.arraycopy(savedFields, 0, newArray, 0, savedFieldsCount); iSavedFields = savedFields = newArray; iSavedFieldsShared = false; } iSavedState = null; savedFields[savedFieldsCount] = field; iSavedFieldsCount = savedFieldsCount + 1; } /** * Saves the state of this bucket, returning it in an opaque object. Call * restoreState to undo any changes that were made since the state was * saved. Calls to saveState may be nested. * * @return opaque saved state, which may be passed to restoreState */ public Object saveState() { if (iSavedState == null) { iSavedState = new SavedState(); } return iSavedState; } /** * Restores the state of this bucket from a previously saved state. The * state object passed into this method is not consumed, and it can be used * later to restore to that state again. * * @param savedState opaque saved state, returned from saveState * @return true state object is valid and state restored */ public boolean restoreState(Object savedState) { if (savedState instanceof SavedState) { if (((SavedState) savedState).restoreState(this)) { iSavedState = savedState; return true; } } return false; } /** * Computes the parsed datetime by setting the saved fields. * This method is idempotent, but it is not thread-safe. * * @return milliseconds since 1970-01-01T00:00:00Z * @throws IllegalArgumentException if any field is out of range */ public long computeMillis() { return computeMillis(false, null); } /** * Computes the parsed datetime by setting the saved fields. * This method is idempotent, but it is not thread-safe. * * @param resetFields false by default, but when true, unsaved field values are cleared * @return milliseconds since 1970-01-01T00:00:00Z * @throws IllegalArgumentException if any field is out of range */ public long computeMillis(boolean resetFields) { return computeMillis(resetFields, null); } /** * Computes the parsed datetime by setting the saved fields. * This method is idempotent, but it is not thread-safe. * * @param resetFields false by default, but when true, unsaved field values are cleared * @param text optional text being parsed, to be included in any error message * @return milliseconds since 1970-01-01T00:00:00Z * @throws IllegalArgumentException if any field is out of range * @since 1.3 */ public long computeMillis(boolean resetFields, String text) { SavedField[] savedFields = iSavedFields; int count = iSavedFieldsCount; if (iSavedFieldsShared) { iSavedFields = savedFields = (SavedField[])iSavedFields.clone(); iSavedFieldsShared = false; } sort(savedFields, count); if (count > 0) { // alter base year for parsing if first field is month or day DurationField months = DurationFieldType.months().getField(iChrono); DurationField days = DurationFieldType.days().getField(iChrono); DurationField first = savedFields[0].iField.getDurationField(); if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) { saveField(DateTimeFieldType.year(), iDefaultYear); return computeMillis(resetFields, text); } } long millis = iMillis; try { for (int i = 0; i < count; i++) { millis = savedFields[i].set(millis, resetFields); } if (resetFields) { for (int i = 0; i < count; i++) { millis = savedFields[i].set(millis, i == (count - 1)); } } } catch (IllegalFieldValueException e) { if (text != null) { e.prependMessage("Cannot parse \"" + text + '"'); } throw e; } if (iOffset != null) { millis -= iOffset; } else if (iZone != null) { int offset = iZone.getOffsetFromLocal(millis); millis -= offset; if (offset != iZone.getOffset(millis)) { String message = "Illegal instant due to time zone offset transition (" + iZone + ')'; if (text != null) { message = "Cannot parse \"" + text + "\": " + message; } throw new IllegalInstantException(message); } } return millis; } /** * Sorts elements [0,high). Calling java.util.Arrays isn't always the right * choice since it always creates an internal copy of the array, even if it * doesn't need to. If the array slice is small enough, an insertion sort * is chosen instead, but it doesn't need a copy! *

* This method has a modified version of that insertion sort, except it * doesn't create an unnecessary array copy. If high is over 10, then * java.util.Arrays is called, which will perform a merge sort, which is * faster than insertion sort on large lists. *

* The end result is much greater performance when computeMillis is called. * Since the amount of saved fields is small, the insertion sort is a * better choice. Additional performance is gained since there is no extra * array allocation and copying. Also, the insertion sort here does not * perform any casting operations. The version in java.util.Arrays performs * casts within the insertion sort loop. */ private static void sort(SavedField[] array, int high) { if (high > 10) { Arrays.sort(array, 0, high); } else { for (int i=0; i0 && (array[j-1]).compareTo(array[j])>0; j--) { SavedField t = array[j]; array[j] = array[j-1]; array[j-1] = t; } } } } class SavedState { final DateTimeZone iZone; final Integer iOffset; final SavedField[] iSavedFields; final int iSavedFieldsCount; SavedState() { this.iZone = DateTimeParserBucket.this.iZone; this.iOffset = DateTimeParserBucket.this.iOffset; this.iSavedFields = DateTimeParserBucket.this.iSavedFields; this.iSavedFieldsCount = DateTimeParserBucket.this.iSavedFieldsCount; } boolean restoreState(DateTimeParserBucket enclosing) { if (enclosing != DateTimeParserBucket.this) { return false; } enclosing.iZone = this.iZone; enclosing.iOffset = this.iOffset; enclosing.iSavedFields = this.iSavedFields; if (this.iSavedFieldsCount < enclosing.iSavedFieldsCount) { // Since count is being restored to a lower count, the // potential exists for new saved fields to destroy data being // shared by another state. Set this flag such that the array // of saved fields is cloned prior to modification. enclosing.iSavedFieldsShared = true; } enclosing.iSavedFieldsCount = this.iSavedFieldsCount; return true; } } static class SavedField implements Comparable { final DateTimeField iField; final int iValue; final String iText; final Locale iLocale; SavedField(DateTimeField field, int value) { iField = field; iValue = value; iText = null; iLocale = null; } SavedField(DateTimeField field, String text, Locale locale) { iField = field; iValue = 0; iText = text; iLocale = locale; } long set(long millis, boolean reset) { if (iText == null) { millis = iField.set(millis, iValue); } else { millis = iField.set(millis, iText, iLocale); } if (reset) { millis = iField.roundFloor(millis); } return millis; } /** * The field with the longer range duration is ordered first, where * null is considered infinite. If the ranges match, then the field * with the longer duration is ordered first. */ public int compareTo(SavedField obj) { DateTimeField other = obj.iField; int result = compareReverse (iField.getRangeDurationField(), other.getRangeDurationField()); if (result != 0) { return result; } return compareReverse (iField.getDurationField(), other.getDurationField()); } } static int compareReverse(DurationField a, DurationField b) { if (a == null || !a.isSupported()) { if (b == null || !b.isSupported()) { return 0; } return -1; } if (b == null || !b.isSupported()) { return 1; } return -a.compareTo(b); } } joda-time-2.3/src/main/java/org/joda/time/format/package.html0000644000175000017500000000276411564251363023445 0ustar ebourgebourg org.joda.time.format package

Provides printing and parsing support for instants and durations. This package contains simple and advanced classes for formatting.

Formatters are defined by interfaces, and instances are obtained from factory classes. Most datetime formatters can be obtained from DateTimeFormat and ISODateTimeFormat. More advanced formatters can be built by using DateTimeFormatterBuilder.

Similarly there are also classes for parsing and printing periods. Most period formatters can be obtained from the factory classes PeriodFormat and ISOPeriodFormat. More advanced formatters can be built by using PeriodFormatterBuilder.

joda-time-2.3/src/main/java/org/joda/time/format/DateTimePrinter.java0000644000175000017500000000756711564251363025075 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.IOException; import java.io.Writer; import java.util.Locale; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.ReadablePartial; /** * Internal interface for creating textual representations of datetimes. *

* Application users will rarely use this class directly. Instead, you * will use one of the factory classes to create a {@link DateTimeFormatter}. *

* The factory classes are:
* - {@link DateTimeFormatterBuilder}
* - {@link DateTimeFormat}
* - {@link ISODateTimeFormat}
* * @author Brian S O'Neill * @author Stephen Colebourne * @see DateTimeFormatterBuilder * @see DateTimeFormat * @see ISODateTimeFormat * @since 1.0 */ public interface DateTimePrinter { /** * Returns the expected maximum number of characters produced. * The actual amount should rarely exceed this estimate. * * @return the estimated length */ int estimatePrintedLength(); //----------------------------------------------------------------------- /** * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, * using the given Chronology. * * @param buf formatted instant is appended to this buffer, not null * @param instant millis since 1970-01-01T00:00:00Z * @param chrono the chronology to use, not null * @param displayOffset if a time zone offset is printed, force it to use * this millisecond value * @param displayZone the time zone to use, null means local time * @param locale the locale to use, null means default locale */ void printTo(StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale); /** * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, * using the given Chronology. * * @param out formatted instant is written out * @param instant millis since 1970-01-01T00:00:00Z * @param chrono the chronology to use, not null * @param displayOffset if a time zone offset is printed, force it to use * this millisecond value * @param displayZone the time zone to use, null means local time * @param locale the locale to use, null means default locale */ void printTo(Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException; //----------------------------------------------------------------------- /** * Prints a ReadablePartial. * * @param buf formatted partial is appended to this buffer, not null * @param partial partial to format, not null * @param locale the locale to use, null means default locale */ void printTo(StringBuffer buf, ReadablePartial partial, Locale locale); /** * Prints a ReadablePartial. * * @param out formatted partial is written out, not null * @param partial partial to format, not null * @param locale the locale to use, null means default locale */ void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException; } joda-time-2.3/src/main/java/org/joda/time/format/FormatUtils.java0000644000175000017500000003135711564251363024300 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.io.IOException; import java.io.Writer; /** * Utility methods used by formatters. *

* FormatUtils is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public class FormatUtils { private static final double LOG_10 = Math.log(10); /** * Restricted constructor. */ private FormatUtils() { } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and appends it to the given buffer. * *

This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void appendPaddedInteger(StringBuffer buf, int value, int size) { if (value < 0) { buf.append('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { for (; size > 10; size--) { buf.append('0'); } buf.append("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { for (; size > 1; size--) { buf.append('0'); } buf.append((char)(value + '0')); } else if (value < 100) { for (; size > 2; size--) { buf.append('0'); } // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; buf.append((char) (d + '0')); // Append remainder by calculating (value - d * 10). buf.append((char) (value - (d << 3) - (d << 1) + '0')); } else { int digits; if (value < 1000) { digits = 3; } else if (value < 10000) { digits = 4; } else { digits = (int)(Math.log(value) / LOG_10) + 1; } for (; size > digits; size--) { buf.append('0'); } buf.append(Integer.toString(value)); } } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and appends it to the given buffer. * *

This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void appendPaddedInteger(StringBuffer buf, long value, int size) { int intValue = (int)value; if (intValue == value) { appendPaddedInteger(buf, intValue, size); } else if (size <= 19) { buf.append(Long.toString(value)); } else { if (value < 0) { buf.append('-'); if (value != Long.MIN_VALUE) { value = -value; } else { for (; size > 19; size--) { buf.append('0'); } buf.append("9223372036854775808"); return; } } int digits = (int)(Math.log(value) / LOG_10) + 1; for (; size > digits; size--) { buf.append('0'); } buf.append(Long.toString(value)); } } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and writes it to the given writer. * *

This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void writePaddedInteger(Writer out, int value, int size) throws IOException { if (value < 0) { out.write('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { for (; size > 10; size--) { out.write('0'); } out.write("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { for (; size > 1; size--) { out.write('0'); } out.write(value + '0'); } else if (value < 100) { for (; size > 2; size--) { out.write('0'); } // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; out.write(d + '0'); // Append remainder by calculating (value - d * 10). out.write(value - (d << 3) - (d << 1) + '0'); } else { int digits; if (value < 1000) { digits = 3; } else if (value < 10000) { digits = 4; } else { digits = (int)(Math.log(value) / LOG_10) + 1; } for (; size > digits; size--) { out.write('0'); } out.write(Integer.toString(value)); } } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and writes it to the given writer. * *

This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void writePaddedInteger(Writer out, long value, int size) throws IOException { int intValue = (int)value; if (intValue == value) { writePaddedInteger(out, intValue, size); } else if (size <= 19) { out.write(Long.toString(value)); } else { if (value < 0) { out.write('-'); if (value != Long.MIN_VALUE) { value = -value; } else { for (; size > 19; size--) { out.write('0'); } out.write("9223372036854775808"); return; } } int digits = (int)(Math.log(value) / LOG_10) + 1; for (; size > digits; size--) { out.write('0'); } out.write(Long.toString(value)); } } /** * Converts an integer to a string, and appends it to the given buffer. * *

This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string */ public static void appendUnpaddedInteger(StringBuffer buf, int value) { if (value < 0) { buf.append('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { buf.append("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { buf.append((char)(value + '0')); } else if (value < 100) { // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; buf.append((char) (d + '0')); // Append remainder by calculating (value - d * 10). buf.append((char) (value - (d << 3) - (d << 1) + '0')); } else { buf.append(Integer.toString(value)); } } /** * Converts an integer to a string, and appends it to the given buffer. * *

This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string */ public static void appendUnpaddedInteger(StringBuffer buf, long value) { int intValue = (int)value; if (intValue == value) { appendUnpaddedInteger(buf, intValue); } else { buf.append(Long.toString(value)); } } /** * Converts an integer to a string, and writes it to the given writer. * *

This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string */ public static void writeUnpaddedInteger(Writer out, int value) throws IOException { if (value < 0) { out.write('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { out.write("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { out.write(value + '0'); } else if (value < 100) { // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; out.write(d + '0'); // Append remainder by calculating (value - d * 10). out.write(value - (d << 3) - (d << 1) + '0'); } else { out.write(Integer.toString(value)); } } /** * Converts an integer to a string, and writes it to the given writer. * *

This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string */ public static void writeUnpaddedInteger(Writer out, long value) throws IOException { int intValue = (int)value; if (intValue == value) { writeUnpaddedInteger(out, intValue); } else { out.write(Long.toString(value)); } } /** * Calculates the number of decimal digits for the given value, * including the sign. */ public static int calculateDigitCount(long value) { if (value < 0) { if (value != Long.MIN_VALUE) { return calculateDigitCount(-value) + 1; } else { return 20; } } return (value < 10 ? 1 : (value < 100 ? 2 : (value < 1000 ? 3 : (value < 10000 ? 4 : ((int)(Math.log(value) / LOG_10) + 1))))); } static int parseTwoDigits(String text, int position) { int value = text.charAt(position) - '0'; return ((value << 3) + (value << 1)) + text.charAt(position + 1) - '0'; } static String createErrorMessage(final String text, final int errorPos) { int sampleLen = errorPos + 32; String sampleText; if (text.length() <= sampleLen + 3) { sampleText = text; } else { sampleText = text.substring(0, sampleLen).concat("..."); } if (errorPos <= 0) { return "Invalid format: \"" + sampleText + '"'; } if (errorPos >= text.length()) { return "Invalid format: \"" + sampleText + "\" is too short"; } return "Invalid format: \"" + sampleText + "\" is malformed at \"" + sampleText.substring(errorPos) + '"'; } } joda-time-2.3/src/main/java/org/joda/time/ReadableDateTime.java0000644000175000017500000001310511567200522023634 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; /** * Defines an instant in time that can be queried using datetime fields. *

* The implementation of this interface may be mutable or immutable. * This interface only gives access to retrieve data, never to change it. *

* Methods in your application should be defined using ReadableDateTime * as a parameter if the method only wants to read the datetime, and not perform * any advanced manipulations. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public interface ReadableDateTime extends ReadableInstant { /** * Get the day of week field value. *

* The values for the day of week are defined in {@link DateTimeConstants}. * * @return the day of week */ int getDayOfWeek(); /** * Get the day of month field value. * * @return the day of month */ int getDayOfMonth(); /** * Get the day of year field value. * * @return the day of year */ int getDayOfYear(); /** * Get the week of weekyear field value. *

* This field is associated with the "weekyear" via {@link #getWeekyear()}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * * @return the week of a week based year */ int getWeekOfWeekyear(); /** * Get the weekyear field value. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. * * @return the year of a week based year */ int getWeekyear(); /** * Get the month of year field value. * * @return the month of year */ int getMonthOfYear(); /** * Get the year field value. * * @return the year */ int getYear(); /** * Get the year of era field value. * * @return the year of era */ int getYearOfEra(); /** * Get the year of century field value. * * @return the year of century */ int getYearOfCentury(); /** * Get the year of era field value. * * @return the year of era */ int getCenturyOfEra(); /** * Get the era field value. * * @return the era */ int getEra(); // Time field access methods //----------------------------------------------------------- /** * Get the millis of second field value. * * @return the millis of second */ int getMillisOfSecond(); /** * Get the millis of day field value. * * @return the millis of day */ int getMillisOfDay(); /** * Get the second of minute field value. * * @return the second of minute */ int getSecondOfMinute(); /** * Get the second of day field value. * * @return the second of day */ int getSecondOfDay(); /** * Get the minute of hour field value. * * @return the minute of hour */ int getMinuteOfHour(); /** * Get the minute of day field value. * * @return the minute of day */ int getMinuteOfDay(); /** * Get the hour of day field value. * * @return the hour of day */ int getHourOfDay(); /** * Get this object as a DateTime. *

* If the implementation of the interface is a DateTime, it is returned directly. * * @return a DateTime using the same millis */ DateTime toDateTime(); /** * Get this object as a MutableDateTime, always returning a new instance. * * @return a MutableDateTime using the same millis */ MutableDateTime toMutableDateTime(); /** * Output the instant using the specified format pattern. * * @param pattern pattern specification * @throws IllegalArgumentException if pattern is invalid * @see org.joda.time.format.DateTimeFormat */ String toString(String pattern) throws IllegalArgumentException; /** * Output the instant using the specified format pattern. * * @param pattern pattern specification * @param locale Locale to use, or null for default * @throws IllegalArgumentException if pattern is invalid * @see org.joda.time.format.DateTimeFormat */ String toString(String pattern, Locale locale) throws IllegalArgumentException; } joda-time-2.3/src/main/java/org/joda/time/base/0000755000175000017500000000000012205344143020565 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/base/AbstractDateTime.java0000644000175000017500000002466511567200522024627 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.ReadableDateTime; import org.joda.time.format.DateTimeFormat; /** * AbstractDateTime provides the common behaviour for datetime classes. *

* This class should generally not be used directly by API users. * The {@link ReadableDateTime} interface should be used when different * kinds of date/time objects are to be referenced. *

* Whenever you want to implement ReadableDateTime you should * extend this class. *

* AbstractDateTime subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractDateTime extends AbstractInstant implements ReadableDateTime { /** * Constructor. */ protected AbstractDateTime() { super(); } //----------------------------------------------------------------------- /** * Get the value of one of the fields of a datetime. *

* This method uses the chronology of the datetime to obtain the value. * It is essentially a generic way of calling one of the get methods. * * @param type a field type, usually obtained from DateTimeFieldType * @return the value of that field * @throws IllegalArgumentException if the field type is null */ public int get(DateTimeFieldType type) { if (type == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } return type.getField(getChronology()).get(getMillis()); } //----------------------------------------------------------------------- /** * Get the era field value. * * @return the era */ public int getEra() { return getChronology().era().get(getMillis()); } /** * Get the year of era field value. * * @return the year of era */ public int getCenturyOfEra() { return getChronology().centuryOfEra().get(getMillis()); } /** * Get the year of era field value. * * @return the year of era */ public int getYearOfEra() { return getChronology().yearOfEra().get(getMillis()); } /** * Get the year of century field value. * * @return the year of century */ public int getYearOfCentury() { return getChronology().yearOfCentury().get(getMillis()); } /** * Get the year field value. * * @return the year */ public int getYear() { return getChronology().year().get(getMillis()); } /** * Get the weekyear field value. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. * * @return the year of a week based year */ public int getWeekyear() { return getChronology().weekyear().get(getMillis()); } /** * Get the month of year field value. * * @return the month of year */ public int getMonthOfYear() { return getChronology().monthOfYear().get(getMillis()); } /** * Get the week of weekyear field value. *

* This field is associated with the "weekyear" via {@link #getWeekyear()}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * * @return the week of a week based year */ public int getWeekOfWeekyear() { return getChronology().weekOfWeekyear().get(getMillis()); } /** * Get the day of year field value. * * @return the day of year */ public int getDayOfYear() { return getChronology().dayOfYear().get(getMillis()); } /** * Get the day of month field value. *

* The values for the day of month are defined in {@link org.joda.time.DateTimeConstants}. * * @return the day of month */ public int getDayOfMonth() { return getChronology().dayOfMonth().get(getMillis()); } /** * Get the day of week field value. *

* The values for the day of week are defined in {@link org.joda.time.DateTimeConstants}. * * @return the day of week */ public int getDayOfWeek() { return getChronology().dayOfWeek().get(getMillis()); } //----------------------------------------------------------------------- /** * Get the hour of day field value. * * @return the hour of day */ public int getHourOfDay() { return getChronology().hourOfDay().get(getMillis()); } /** * Get the minute of day field value. * * @return the minute of day */ public int getMinuteOfDay() { return getChronology().minuteOfDay().get(getMillis()); } /** * Get the minute of hour field value. * * @return the minute of hour */ public int getMinuteOfHour() { return getChronology().minuteOfHour().get(getMillis()); } /** * Get the second of day field value. * * @return the second of day */ public int getSecondOfDay() { return getChronology().secondOfDay().get(getMillis()); } /** * Get the second of minute field value. * * @return the second of minute */ public int getSecondOfMinute() { return getChronology().secondOfMinute().get(getMillis()); } /** * Get the millis of day field value. * * @return the millis of day */ public int getMillisOfDay() { return getChronology().millisOfDay().get(getMillis()); } /** * Get the millis of second field value. * * @return the millis of second */ public int getMillisOfSecond() { return getChronology().millisOfSecond().get(getMillis()); } //----------------------------------------------------------------------- /** * Get the date time as a java.util.Calendar, assigning * exactly the same millisecond instant. * The locale is passed in, enabling Calendar to select the correct * localized subclass. *

* The JDK and Joda-Time both have time zone implementations and these * differ in accuracy. Joda-Time's implementation is generally more up to * date and thus more accurate - for example JDK1.3 has no historical data. * The effect of this is that the field values of the Calendar * may differ from those of this object, even though the milliseond value * is the same. Most of the time this just means that the JDK field values * are wrong, as our time zone information is more up to date. * * @param locale the locale to get the Calendar for, or default if null * @return a localized Calendar initialised with this datetime */ public Calendar toCalendar(Locale locale) { if (locale == null) { locale = Locale.getDefault(); } DateTimeZone zone = getZone(); Calendar cal = Calendar.getInstance(zone.toTimeZone(), locale); cal.setTime(toDate()); return cal; } /** * Get the date time as a java.util.GregorianCalendar, * assigning exactly the same millisecond instant. *

* The JDK and Joda-Time both have time zone implementations and these * differ in accuracy. Joda-Time's implementation is generally more up to * date and thus more accurate - for example JDK1.3 has no historical data. * The effect of this is that the field values of the Calendar * may differ from those of this object, even though the milliseond value * is the same. Most of the time this just means that the JDK field values * are wrong, as our time zone information is more up to date. * * @return a GregorianCalendar initialised with this datetime */ public GregorianCalendar toGregorianCalendar() { DateTimeZone zone = getZone(); GregorianCalendar cal = new GregorianCalendar(zone.toTimeZone()); cal.setTime(toDate()); return cal; } //----------------------------------------------------------------------- /** * Output the instant using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the instant using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) throws IllegalArgumentException { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } } joda-time-2.3/src/main/java/org/joda/time/base/BasePartial.java0000644000175000017500000003015711600101003023605 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.io.Serializable; import java.util.Locale; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.ReadablePartial; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.PartialConverter; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * BasePartial is an abstract implementation of ReadablePartial that stores * data in array and Chronology fields. *

* This class should generally not be used directly by API users. * The {@link org.joda.time.ReadablePartial} interface should be used when different * kinds of partial objects are to be referenced. *

* BasePartial subclasses may be mutable and not thread-safe. * * @author Stephen Colebourne * @since 1.0 */ public abstract class BasePartial extends AbstractPartial implements ReadablePartial, Serializable { /** Serialization version */ private static final long serialVersionUID = 2353678632973660L; /** The chronology in use */ private final Chronology iChronology; /** The values of each field in this partial */ private final int[] iValues; //----------------------------------------------------------------------- /** * Constructs a partial with the current time, using ISOChronology in * the default zone to extract the fields. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). */ protected BasePartial() { this(DateTimeUtils.currentTimeMillis(), null); } /** * Constructs a partial with the current time, using the specified chronology * and zone to extract the fields. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param chronology the chronology, null means ISOChronology in the default zone */ protected BasePartial(Chronology chronology) { this(DateTimeUtils.currentTimeMillis(), chronology); } /** * Constructs a partial extracting the partial fields from the specified * milliseconds using the ISOChronology in the default zone. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ protected BasePartial(long instant) { this(instant, null); } /** * Constructs a partial extracting the partial fields from the specified * milliseconds using the chronology provided. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in the default zone */ protected BasePartial(long instant, Chronology chronology) { super(); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); iValues = chronology.get(this, instant); } /** * Constructs a partial from an Object that represents a time, using the * specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param instant the datetime object * @param chronology the chronology, null means use converter * @throws IllegalArgumentException if the date is invalid */ protected BasePartial(Object instant, Chronology chronology) { super(); PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); chronology = converter.getChronology(instant, chronology); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); iValues = converter.getPartialValues(this, instant, chronology); } /** * Constructs a partial from an Object that represents a time, using the * specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param instant the datetime object * @param chronology the chronology, null means use converter * @param parser if converting from a String, the given parser is preferred * @throws IllegalArgumentException if the date is invalid * @since 1.3 */ protected BasePartial(Object instant, Chronology chronology, DateTimeFormatter parser) { super(); PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); chronology = converter.getChronology(instant, chronology); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); iValues = converter.getPartialValues(this, instant, chronology, parser); } /** * Constructs a partial with specified time field values and chronology. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). *

* The array of values is assigned (not cloned) to the new instance. * * @param values the new set of values * @param chronology the chronology, null means ISOChronology in the default zone * @throws IllegalArgumentException if the values are invalid */ protected BasePartial(int[] values, Chronology chronology) { super(); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); chronology.validate(this, values); iValues = values; } /** * Private constructor to be used by subclasses only which performs no validation. *

* Data is assigned (not cloned) to the new instance. * * @param base the base partial * @param values the new set of values, not cloned, null means use base */ protected BasePartial(BasePartial base, int[] values) { super(); iChronology = base.iChronology; iValues = values; } /** * Private constructor to be used by subclasses only which performs no validation. *

* Data is assigned (not cloned) to the new instance. * This should not be used by mutable subclasses. * * @param base the base partial * @param chrono the chronology to use, null means use base */ protected BasePartial(BasePartial base, Chronology chrono) { super(); iChronology = chrono.withUTC(); iValues = base.iValues; } //----------------------------------------------------------------------- /** * Gets the value of the field at the specifed index. * * @param index the index * @return the value * @throws IndexOutOfBoundsException if the index is invalid */ public int getValue(int index) { return iValues[index]; } /** * Gets an array of the value of each of the fields that this partial supports. *

* The fields are returned largest to smallest, for example Hour, Minute, Second. * Each value corresponds to the same array index as getFields() * * @return the current values of each field (cloned), largest to smallest */ public int[] getValues() { return (int[]) iValues.clone(); } /** * Gets the chronology of the partial which is never null. *

* The {@link Chronology} is the calculation engine behind the partial and * provides conversion and validation of the fields in a particular calendar system. * * @return the chronology, never null */ public Chronology getChronology() { return iChronology; } //----------------------------------------------------------------------- /** * Sets the value of the field at the specified index. *

* In version 2.0 and later, this method copies the array into the original. * This is because the instance variable has been changed to be final to satisfy the Java Memory Model. * This only impacts subclasses that are mutable. * * @param index the index * @param value the value to set * @throws IndexOutOfBoundsException if the index is invalid */ protected void setValue(int index, int value) { DateTimeField field = getField(index); int[] values = field.set(this, index, iValues, value); System.arraycopy(values, 0, iValues, 0, iValues.length); } /** * Sets the values of all fields. *

* In version 2.0 and later, this method copies the array into the original. * This is because the instance variable has been changed to be final to satisfy the Java Memory Model. * This only impacts subclasses that are mutable. * * @param values the array of values */ protected void setValues(int[] values) { getChronology().validate(this, values); System.arraycopy(values, 0, iValues, 0, iValues.length); } //----------------------------------------------------------------------- /** * Output the date using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the date using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) throws IllegalArgumentException { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } } joda-time-2.3/src/main/java/org/joda/time/base/BaseDuration.java0000644000175000017500000002514311600100601024000 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.io.Serializable; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.Interval; import org.joda.time.Period; import org.joda.time.PeriodType; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.DurationConverter; import org.joda.time.field.FieldUtils; /** * BaseDuration is an abstract implementation of ReadableDuration that stores * data in a long duration milliseconds field. *

* This class should generally not be used directly by API users. * The {@link ReadableDuration} interface should be used when different * kinds of duration objects are to be referenced. *

* BaseDuration subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class BaseDuration extends AbstractDuration implements ReadableDuration, Serializable { /** Serialization version */ private static final long serialVersionUID = 2581698638990L; /** The duration length */ private volatile long iMillis; /** * Creates a duration from the given millisecond duration. * * @param duration the duration, in milliseconds */ protected BaseDuration(long duration) { super(); iMillis = duration; } /** * Creates a duration from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @throws ArithmeticException if the duration exceeds a 64 bit long */ protected BaseDuration(long startInstant, long endInstant) { super(); iMillis = FieldUtils.safeAdd(endInstant, -startInstant); } /** * Creates a duration from the given interval endpoints. * * @param start interval start, null means now * @param end interval end, null means now * @throws ArithmeticException if the duration exceeds a 64 bit long */ protected BaseDuration(ReadableInstant start, ReadableInstant end) { super(); if (start == end) { iMillis = 0L; } else { long startMillis = DateTimeUtils.getInstantMillis(start); long endMillis = DateTimeUtils.getInstantMillis(end); iMillis = FieldUtils.safeAdd(endMillis, -startMillis); } } /** * Creates a duration from the specified object using the * {@link org.joda.time.convert.ConverterManager ConverterManager}. * * @param duration duration to convert * @throws IllegalArgumentException if duration is invalid */ protected BaseDuration(Object duration) { super(); DurationConverter converter = ConverterManager.getInstance().getDurationConverter(duration); iMillis = converter.getDurationMillis(duration); } //----------------------------------------------------------------------- /** * Gets the length of this duration in milliseconds. * * @return the length of the duration in milliseconds. */ public long getMillis() { return iMillis; } //----------------------------------------------------------------------- /** * Sets the length of this duration in milliseconds. * * @param duration the new length of the duration */ protected void setMillis(long duration) { iMillis = duration; } //----------------------------------------------------------------------- /** * Converts this duration to a Period instance using the specified period type * and the ISO chronology. *

* Only precise fields in the period type will be used. * At most these are hours, minutes, seconds and millis - the period * type may restrict the selection further. *

* For more control over the conversion process, you must pair the duration with * an instant, see {@link #toPeriodFrom(ReadableInstant, PeriodType)}. * * @param type the period type to use, null means standard * @return a Period created using the millisecond duration from this instance */ public Period toPeriod(PeriodType type) { return new Period(getMillis(), type); } /** * Converts this duration to a Period instance using the standard period type * and the specified chronology. *

* Only precise fields in the period type will be used. * Exactly which fields are precise depends on the chronology. * Only the time fields are precise for ISO chronology with a time zone. * However, ISO UTC also has precise days and weeks. *

* For more control over the conversion process, you must pair the duration with * an instant, see {@link #toPeriodFrom(ReadableInstant)} and * {@link #toPeriodTo(ReadableInstant)} * * @param chrono the chronology to use, null means ISO default * @return a Period created using the millisecond duration from this instance */ public Period toPeriod(Chronology chrono) { return new Period(getMillis(), chrono); } /** * Converts this duration to a Period instance using the specified period type * and chronology. *

* Only precise fields in the period type will be used. * Exactly which fields are precise depends on the chronology. * Only the time fields are precise for ISO chronology with a time zone. * However, ISO UTC also has precise days and weeks. *

* For more control over the conversion process, you must pair the duration with * an instant, see {@link #toPeriodFrom(ReadableInstant, PeriodType)} and * {@link #toPeriodTo(ReadableInstant, PeriodType)} * * @param type the period type to use, null means standard * @param chrono the chronology to use, null means ISO default * @return a Period created using the millisecond duration from this instance */ public Period toPeriod(PeriodType type, Chronology chrono) { return new Period(getMillis(), type, chrono); } /** * Converts this duration to a Period instance by adding the duration to a start * instant to obtain an interval using the standard period type. *

* This conversion will determine the fields of a period accurately. * The results are based on the instant millis, the chronology of the instant, * the standard period type and the length of this duration. * * @param startInstant the instant to calculate the period from, null means now * @return a Period created using the millisecond duration from this instance */ public Period toPeriodFrom(ReadableInstant startInstant) { return new Period(startInstant, this); } /** * Converts this duration to a Period instance by adding the duration to a start * instant to obtain an interval. *

* This conversion will determine the fields of a period accurately. * The results are based on the instant millis, the chronology of the instant, * the period type and the length of this duration. * * @param startInstant the instant to calculate the period from, null means now * @param type the period type determining how to split the duration into fields, null means All type * @return a Period created using the millisecond duration from this instance */ public Period toPeriodFrom(ReadableInstant startInstant, PeriodType type) { return new Period(startInstant, this, type); } /** * Converts this duration to a Period instance by subtracting the duration * from an end instant to obtain an interval using the standard period * type. *

* This conversion will determine the fields of a period accurately. * The results are based on the instant millis, the chronology of the instant, * the standard period type and the length of this duration. * * @param endInstant the instant to calculate the period to, null means now * @return a Period created using the millisecond duration from this instance */ public Period toPeriodTo(ReadableInstant endInstant) { return new Period(this, endInstant); } /** * Converts this duration to a Period instance by subtracting the duration * from an end instant to obtain an interval using the standard period * type. *

* This conversion will determine the fields of a period accurately. * The results are based on the instant millis, the chronology of the instant, * the period type and the length of this duration. * * @param endInstant the instant to calculate the period to, null means now * @param type the period type determining how to split the duration into fields, null means All type * @return a Period created using the millisecond duration from this instance */ public Period toPeriodTo(ReadableInstant endInstant, PeriodType type) { return new Period(this, endInstant, type); } /** * Converts this duration to an Interval starting at the specified instant. * * @param startInstant the instant to start the interval at, null means now * @return an Interval starting at the specified instant */ public Interval toIntervalFrom(ReadableInstant startInstant) { return new Interval(startInstant, this); } /** * Converts this duration to an Interval ending at the specified instant. * * @param endInstant the instant to end the interval at, null means now * @return an Interval ending at the specified instant */ public Interval toIntervalTo(ReadableInstant endInstant) { return new Interval(this, endInstant); } } joda-time-2.3/src/main/java/org/joda/time/base/BaseSingleFieldPeriod.java0000644000175000017500000003146712162055431025567 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.io.Serializable; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.MutablePeriod; import org.joda.time.Period; import org.joda.time.PeriodType; import org.joda.time.ReadableInstant; import org.joda.time.ReadablePartial; import org.joda.time.ReadablePeriod; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.FieldUtils; /** * BaseSingleFieldPeriod is an abstract implementation of ReadablePeriod that * manages a single duration field, such as days or minutes. *

* This class should generally not be used directly by API users. * The {@link ReadablePeriod} interface should be used when different * kinds of period objects are to be referenced. *

* BaseSingleFieldPeriod subclasses may be mutable and not thread-safe. * * @author Stephen Colebourne * @since 1.4 */ public abstract class BaseSingleFieldPeriod implements ReadablePeriod, Comparable, Serializable { /** Serialization version. */ private static final long serialVersionUID = 9386874258972L; /** The start of 1972. */ private static final long START_1972 = 2L * 365L * 86400L * 1000L; /** The period in the units of this period. */ private volatile int iPeriod; //----------------------------------------------------------------------- /** * Calculates the number of whole units between the two specified datetimes. * * @param start the start instant, validated to not be null * @param end the end instant, validated to not be null * @param field the field type to use, must not be null * @return the period * @throws IllegalArgumentException if the instants are null or invalid */ protected static int between(ReadableInstant start, ReadableInstant end, DurationFieldType field) { if (start == null || end == null) { throw new IllegalArgumentException("ReadableInstant objects must not be null"); } Chronology chrono = DateTimeUtils.getInstantChronology(start); int amount = field.getField(chrono).getDifference(end.getMillis(), start.getMillis()); return amount; } //----------------------------------------------------------------------- /** * Calculates the number of whole units between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalDate objects. * * @param start the start partial date, validated to not be null * @param end the end partial date, validated to not be null * @param zeroInstance the zero instance constant, must not be null * @return the period * @throws IllegalArgumentException if the partials are null or invalid */ protected static int between(ReadablePartial start, ReadablePartial end, ReadablePeriod zeroInstance) { if (start == null || end == null) { throw new IllegalArgumentException("ReadablePartial objects must not be null"); } if (start.size() != end.size()) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } for (int i = 0, isize = start.size(); i < isize; i++) { if (start.getFieldType(i) != end.getFieldType(i)) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } } if (DateTimeUtils.isContiguous(start) == false) { throw new IllegalArgumentException("ReadablePartial objects must be contiguous"); } Chronology chrono = DateTimeUtils.getChronology(start.getChronology()).withUTC(); int[] values = chrono.get(zeroInstance, chrono.set(start, START_1972), chrono.set(end, START_1972)); return values[0]; } /** * Creates a new instance representing the number of complete standard length units * in the specified period. *

* This factory method converts all fields from the period to hours using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. *

    *
  • One week consists of 7 days. *
  • One day consists of 24 hours. *
  • One hour consists of 60 minutes. *
  • One minute consists of 60 seconds. *
  • One second consists of 1000 milliseconds. *
* Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of hours from, must not be null * @param millisPerUnit the number of milliseconds in one standard unit of this period * @throws IllegalArgumentException if the period contains imprecise duration values */ protected static int standardPeriodIn(ReadablePeriod period, long millisPerUnit) { if (period == null) { return 0; } Chronology iso = ISOChronology.getInstanceUTC(); long duration = 0L; for (int i = 0; i < period.size(); i++) { int value = period.getValue(i); if (value != 0) { DurationField field = period.getFieldType(i).getField(iso); if (field.isPrecise() == false) { throw new IllegalArgumentException( "Cannot convert period to duration as " + field.getName() + " is not precise in the period " + period); } duration = FieldUtils.safeAdd(duration, FieldUtils.safeMultiply(field.getUnitMillis(), value)); } } return FieldUtils.safeToInt(duration / millisPerUnit); } //----------------------------------------------------------------------- /** * Creates a new instance representing the specified period. * * @param period the period to represent */ protected BaseSingleFieldPeriod(int period) { super(); iPeriod = period; } //----------------------------------------------------------------------- /** * Gets the amount of this period. * * @return the period value */ protected int getValue() { return iPeriod; } /** * Sets the amount of this period. * To make a subclass immutable you must declare it final, or block this method. * * @param value the period value */ protected void setValue(int value) { iPeriod = value; } //----------------------------------------------------------------------- /** * Gets the single duration field type. * * @return the duration field type, not null */ public abstract DurationFieldType getFieldType(); /** * Gets the period type which matches the duration field type. * * @return the period type, not null */ public abstract PeriodType getPeriodType(); //----------------------------------------------------------------------- /** * Gets the number of fields that this period supports, which is one. * * @return the number of fields supported, which is one */ public int size() { return 1; } /** * Gets the field type at the specified index. *

* The only index supported by this period is zero which returns the * field type of this class. * * @param index the index to retrieve, which must be zero * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public DurationFieldType getFieldType(int index) { if (index != 0) { throw new IndexOutOfBoundsException(String.valueOf(index)); } return getFieldType(); } /** * Gets the value at the specified index. *

* The only index supported by this period is zero. * * @param index the index to retrieve, which must be zero * @return the value of the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public int getValue(int index) { if (index != 0) { throw new IndexOutOfBoundsException(String.valueOf(index)); } return getValue(); } /** * Gets the value of a duration field represented by this period. *

* If the field type specified does not match the type used by this class * then zero is returned. * * @param type the field type to query, null returns zero * @return the value of that field, zero if field not supported */ public int get(DurationFieldType type) { if (type == getFieldType()) { return getValue(); } return 0; } /** * Checks whether the duration field specified is supported by this period. * * @param type the type to check, may be null which returns false * @return true if the field is supported */ public boolean isSupported(DurationFieldType type) { return (type == getFieldType()); } //----------------------------------------------------------------------- /** * Get this period as an immutable Period object. * The period will use PeriodType.standard(). * * @return a Period representing the same number of days */ public Period toPeriod() { return Period.ZERO.withFields(this); } /** * Get this object as a MutablePeriod. *

* This will always return a new MutablePeriod with the same fields. * The period will use PeriodType.standard(). * * @return a MutablePeriod using the same field set and values */ public MutablePeriod toMutablePeriod() { MutablePeriod period = new MutablePeriod(); period.add(this); return period; } //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based on the * value of each field. All ReadablePeriod instances are accepted, but only * those with a matching PeriodType can return true. * * @param period a readable period to check against * @return true if all the field values are equal, false if * not or the period is null or of an incorrect type */ public boolean equals(Object period) { if (this == period) { return true; } if (period instanceof ReadablePeriod == false) { return false; } ReadablePeriod other = (ReadablePeriod) period; return (other.getPeriodType() == getPeriodType() && other.getValue(0) == getValue()); } /** * Gets a hash code for the period as defined by ReadablePeriod. * * @return a hash code */ public int hashCode() { int total = 17; total = 27 * total + getValue(); total = 27 * total + getFieldType().hashCode(); return total; } /** * Compares this period to another object of the same class. * * @param other the other period, must not be null * @return zero if equal, positive if greater, negative if less * @throws NullPointerException if the other period is null * @throws ClassCastException if the other period is of a different type */ public int compareTo(BaseSingleFieldPeriod other) { if (other.getClass() != getClass()) { throw new ClassCastException(getClass() + " cannot be compared to " + other.getClass()); } int otherValue = other.getValue(); int thisValue = getValue(); if (thisValue > otherValue) { return 1; } if (thisValue < otherValue) { return -1; } return 0; } } joda-time-2.3/src/main/java/org/joda/time/base/AbstractPartial.java0000644000175000017500000003601611567200522024520 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DurationFieldType; import org.joda.time.ReadableInstant; import org.joda.time.ReadablePartial; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; /** * AbstractPartial provides a standard base implementation of most methods * in the ReadablePartial interface. *

* Calculations on are performed using a {@link Chronology}. * This chronology is set to be in the UTC time zone for all calculations. *

* The methods on this class use {@link ReadablePartial#size()}, * {@link AbstractPartial#getField(int, Chronology)} and * {@link ReadablePartial#getValue(int)} to calculate their results. * Subclasses may have a better implementation. *

* AbstractPartial allows subclasses may be mutable and not thread-safe. * * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractPartial implements ReadablePartial, Comparable { //----------------------------------------------------------------------- /** * Constructor. */ protected AbstractPartial() { super(); } //----------------------------------------------------------------------- /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field * @throws IndexOutOfBoundsException if the index is invalid */ protected abstract DateTimeField getField(int index, Chronology chrono); //----------------------------------------------------------------------- /** * Gets the field type at the specifed index. * * @param index the index * @return the field type * @throws IndexOutOfBoundsException if the index is invalid */ public DateTimeFieldType getFieldType(int index) { return getField(index, getChronology()).getType(); } /** * Gets an array of the field types that this partial supports. *

* The fields are returned largest to smallest, for example Hour, Minute, Second. * * @return the fields supported in an array that may be altered, largest to smallest */ public DateTimeFieldType[] getFieldTypes() { DateTimeFieldType[] result = new DateTimeFieldType[size()]; for (int i = 0; i < result.length; i++) { result[i] = getFieldType(i); } return result; } /** * Gets the field at the specifed index. * * @param index the index * @return the field * @throws IndexOutOfBoundsException if the index is invalid */ public DateTimeField getField(int index) { return getField(index, getChronology()); } /** * Gets an array of the fields that this partial supports. *

* The fields are returned largest to smallest, for example Hour, Minute, Second. * * @return the fields supported in an array that may be altered, largest to smallest */ public DateTimeField[] getFields() { DateTimeField[] result = new DateTimeField[size()]; for (int i = 0; i < result.length; i++) { result[i] = getField(i); } return result; } /** * Gets an array of the value of each of the fields that this partial supports. *

* The fields are returned largest to smallest, for example Hour, Minute, Second. * Each value corresponds to the same array index as getFields() * * @return the current values of each field in an array that may be altered, largest to smallest */ public int[] getValues() { int[] result = new int[size()]; for (int i = 0; i < result.length; i++) { result[i] = getValue(i); } return result; } //----------------------------------------------------------------------- /** * Get the value of one of the fields of a datetime. *

* The field specified must be one of those that is supported by the partial. * * @param type a DateTimeFieldType instance that is supported by this partial * @return the value of that field * @throws IllegalArgumentException if the field is null or not supported */ public int get(DateTimeFieldType type) { return getValue(indexOfSupported(type)); } /** * Checks whether the field specified is supported by this partial. * * @param type the type to check, may be null which returns false * @return true if the field is supported */ public boolean isSupported(DateTimeFieldType type) { return (indexOf(type) != -1); } /** * Gets the index of the specified field, or -1 if the field is unsupported. * * @param type the type to check, may be null which returns -1 * @return the index of the field, -1 if unsupported */ public int indexOf(DateTimeFieldType type) { for (int i = 0, isize = size(); i < isize; i++) { if (getFieldType(i) == type) { return i; } } return -1; } /** * Gets the index of the specified field, throwing an exception if the * field is unsupported. * * @param type the type to check, not null * @return the index of the field * @throws IllegalArgumentException if the field is null or not supported */ protected int indexOfSupported(DateTimeFieldType type) { int index = indexOf(type); if (index == -1) { throw new IllegalArgumentException("Field '" + type + "' is not supported"); } return index; } /** * Gets the index of the first fields to have the specified duration, * or -1 if the field is unsupported. * * @param type the type to check, may be null which returns -1 * @return the index of the field, -1 if unsupported */ protected int indexOf(DurationFieldType type) { for (int i = 0, isize = size(); i < isize; i++) { if (getFieldType(i).getDurationType() == type) { return i; } } return -1; } /** * Gets the index of the first fields to have the specified duration, * throwing an exception if the field is unsupported. * * @param type the type to check, not null * @return the index of the field * @throws IllegalArgumentException if the field is null or not supported */ protected int indexOfSupported(DurationFieldType type) { int index = indexOf(type); if (index == -1) { throw new IllegalArgumentException("Field '" + type + "' is not supported"); } return index; } //----------------------------------------------------------------------- /** * Resolves this partial against another complete instant to create a new * full instant. The combination is performed using the chronology of the * specified instant. *

* For example, if this partial represents a time, then the result of this * method will be the datetime from the specified base instant plus the * time from this partial. * * @param baseInstant the instant that provides the missing fields, null means now * @return the combined datetime */ public DateTime toDateTime(ReadableInstant baseInstant) { Chronology chrono = DateTimeUtils.getInstantChronology(baseInstant); long instantMillis = DateTimeUtils.getInstantMillis(baseInstant); long resolved = chrono.set(this, instantMillis); return new DateTime(resolved, chrono); } //----------------------------------------------------------------------- /** * Compares this ReadablePartial with another returning true if the chronology, * field types and values are equal. * * @param partial an object to check against * @return true if fields and values are equal */ public boolean equals(Object partial) { if (this == partial) { return true; } if (partial instanceof ReadablePartial == false) { return false; } ReadablePartial other = (ReadablePartial) partial; if (size() != other.size()) { return false; } for (int i = 0, isize = size(); i < isize; i++) { if (getValue(i) != other.getValue(i) || getFieldType(i) != other.getFieldType(i)) { return false; } } return FieldUtils.equals(getChronology(), other.getChronology()); } /** * Gets a hash code for the ReadablePartial that is compatible with the * equals method. * * @return a suitable hash code */ public int hashCode() { int total = 157; for (int i = 0, isize = size(); i < isize; i++) { total = 23 * total + getValue(i); total = 23 * total + getFieldType(i).hashCode(); } total += getChronology().hashCode(); return total; } //----------------------------------------------------------------------- /** * Compares this partial with another returning an integer * indicating the order. *

* The fields are compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. *

* The specified object must be a partial instance whose field types * match those of this partial. *

* NOTE: Prior to v2.0, the {@code Comparable} interface was only implemented * in this class and not in the {@code ReadablePartial} interface. * * @param other an object to check against * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the partial is the wrong class * or if it has field types that don't match * @throws NullPointerException if the partial is null * @since 1.1 */ public int compareTo(ReadablePartial other) { if (this == other) { return 0; } if (size() != other.size()) { throw new ClassCastException("ReadablePartial objects must have matching field types"); } for (int i = 0, isize = size(); i < isize; i++) { if (getFieldType(i) != other.getFieldType(i)) { throw new ClassCastException("ReadablePartial objects must have matching field types"); } } // fields are ordered largest first for (int i = 0, isize = size(); i < isize; i++) { if (getValue(i) > other.getValue(i)) { return 1; } if (getValue(i) < other.getValue(i)) { return -1; } } return 0; } /** * Is this partial later than the specified partial. *

* The fields are compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. *

* You may not pass null into this method. This is because you need * a time zone to accurately determine the current date. * * @param partial a partial to check against, must not be null * @return true if this date is after the date passed in * @throws IllegalArgumentException if the specified partial is null * @throws ClassCastException if the partial has field types that don't match * @since 1.1 */ public boolean isAfter(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("Partial cannot be null"); } return compareTo(partial) > 0; } /** * Is this partial earlier than the specified partial. *

* The fields are compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. *

* You may not pass null into this method. This is because you need * a time zone to accurately determine the current date. * * @param partial a partial to check against, must not be null * @return true if this date is before the date passed in * @throws IllegalArgumentException if the specified partial is null * @throws ClassCastException if the partial has field types that don't match * @since 1.1 */ public boolean isBefore(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("Partial cannot be null"); } return compareTo(partial) < 0; } /** * Is this partial the same as the specified partial. *

* The fields are compared in order, from largest to smallest. * If all fields are equal, the result is true. *

* You may not pass null into this method. This is because you need * a time zone to accurately determine the current date. * * @param partial a partial to check against, must not be null * @return true if this date is the same as the date passed in * @throws IllegalArgumentException if the specified partial is null * @throws ClassCastException if the partial has field types that don't match * @since 1.1 */ public boolean isEqual(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("Partial cannot be null"); } return compareTo(partial) == 0; } //----------------------------------------------------------------------- /** * Uses the specified formatter to convert this partial to a String. * * @param formatter the formatter to use, null means use toString(). * @return the formatted string * @since 1.1 */ public String toString(DateTimeFormatter formatter) { if (formatter == null) { return toString(); } return formatter.print(this); } } joda-time-2.3/src/main/java/org/joda/time/base/BaseLocal.java0000644000175000017500000000445212203434571023265 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; /** * BaseLocal is an abstract implementation of ReadablePartial that * use a local milliseconds internal representation. *

* This class should generally not be used directly by API users. * The {@link org.joda.time.ReadablePartial} interface should be used when different * kinds of partial objects are to be referenced. *

* BasePartial subclasses may be mutable and not thread-safe. * * @author Stephen Colebourne * @since 1.5 */ public abstract class BaseLocal extends AbstractPartial { /** Serialization version */ @SuppressWarnings("unused") private static final long serialVersionUID = 276453175381783L; //----------------------------------------------------------------------- /** * Constructs a partial with the current time, using ISOChronology in * the default zone to extract the fields. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). */ protected BaseLocal() { super(); } //----------------------------------------------------------------------- /** * Gets the local milliseconds from the Java epoch * of 1970-01-01T00:00:00 (not fixed to any specific time zone). *

* This method is useful in certain circustances for high performance * access to the datetime fields. * * @return the number of milliseconds since 1970-01-01T00:00:00 */ protected abstract long getLocalMillis(); } joda-time-2.3/src/main/java/org/joda/time/base/BaseInterval.java0000644000175000017500000002377411600100544024015 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.io.Serializable; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.MutableInterval; import org.joda.time.ReadWritableInterval; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; import org.joda.time.ReadableInterval; import org.joda.time.ReadablePeriod; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.IntervalConverter; import org.joda.time.field.FieldUtils; /** * BaseInterval is an abstract implementation of ReadableInterval that stores * data in two long millisecond fields. *

* This class should generally not be used directly by API users. * The {@link ReadableInterval} interface should be used when different * kinds of interval objects are to be referenced. *

* BaseInterval subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Sean Geoghegan * @author Stephen Colebourne * @since 1.0 */ public abstract class BaseInterval extends AbstractInterval implements ReadableInterval, Serializable { /** Serialization version */ private static final long serialVersionUID = 576586928732749278L; /** The chronology of the interval */ private volatile Chronology iChronology; /** The start of the interval */ private volatile long iStartMillis; /** The end of the interval */ private volatile long iEndMillis; /** * Constructs an interval from a start and end instant. * * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. * @param chrono the chronology to use, null is ISO default * @throws IllegalArgumentException if the end is before the start */ protected BaseInterval(long startInstant, long endInstant, Chronology chrono) { super(); iChronology = DateTimeUtils.getChronology(chrono); checkInterval(startInstant, endInstant); iStartMillis = startInstant; iEndMillis = endInstant; } /** * Constructs an interval from a start and end instant. * * @param start start of this interval, null means now * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start */ protected BaseInterval(ReadableInstant start, ReadableInstant end) { super(); if (start == null && end == null) { iStartMillis = iEndMillis = DateTimeUtils.currentTimeMillis(); iChronology = ISOChronology.getInstance(); } else { iChronology = DateTimeUtils.getInstantChronology(start); iStartMillis = DateTimeUtils.getInstantMillis(start); iEndMillis = DateTimeUtils.getInstantMillis(end); checkInterval(iStartMillis, iEndMillis); } } /** * Constructs an interval from a start instant and a duration. * * @param start start of this interval, null means now * @param duration the duration of this interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ protected BaseInterval(ReadableInstant start, ReadableDuration duration) { super(); iChronology = DateTimeUtils.getInstantChronology(start); iStartMillis = DateTimeUtils.getInstantMillis(start); long durationMillis = DateTimeUtils.getDurationMillis(duration); iEndMillis = FieldUtils.safeAdd(iStartMillis, durationMillis); checkInterval(iStartMillis, iEndMillis); } /** * Constructs an interval from a millisecond duration and an end instant. * * @param duration the duration of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ protected BaseInterval(ReadableDuration duration, ReadableInstant end) { super(); iChronology = DateTimeUtils.getInstantChronology(end); iEndMillis = DateTimeUtils.getInstantMillis(end); long durationMillis = DateTimeUtils.getDurationMillis(duration); iStartMillis = FieldUtils.safeAdd(iEndMillis, -durationMillis); checkInterval(iStartMillis, iEndMillis); } /** * Constructs an interval from a start instant and a time period. *

* When forming the interval, the chronology from the instant is used * if present, otherwise the chronology of the period is used. * * @param start start of this interval, null means now * @param period the period of this interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ protected BaseInterval(ReadableInstant start, ReadablePeriod period) { super(); Chronology chrono = DateTimeUtils.getInstantChronology(start); iChronology = chrono; iStartMillis = DateTimeUtils.getInstantMillis(start); if (period == null) { iEndMillis = iStartMillis; } else { iEndMillis = chrono.add(period, iStartMillis, 1); } checkInterval(iStartMillis, iEndMillis); } /** * Constructs an interval from a time period and an end instant. *

* When forming the interval, the chronology from the instant is used * if present, otherwise the chronology of the period is used. * * @param period the period of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ protected BaseInterval(ReadablePeriod period, ReadableInstant end) { super(); Chronology chrono = DateTimeUtils.getInstantChronology(end); iChronology = chrono; iEndMillis = DateTimeUtils.getInstantMillis(end); if (period == null) { iStartMillis = iEndMillis; } else { iStartMillis = chrono.add(period, iEndMillis, -1); } checkInterval(iStartMillis, iEndMillis); } /** * Constructs a time interval converting or copying from another object * that describes an interval. * * @param interval the time interval to copy * @param chrono the chronology to use, null means let converter decide * @throws IllegalArgumentException if the interval is invalid */ protected BaseInterval(Object interval, Chronology chrono) { super(); IntervalConverter converter = ConverterManager.getInstance().getIntervalConverter(interval); if (converter.isReadableInterval(interval, chrono)) { ReadableInterval input = (ReadableInterval) interval; iChronology = (chrono != null ? chrono : input.getChronology()); iStartMillis = input.getStartMillis(); iEndMillis = input.getEndMillis(); } else if (this instanceof ReadWritableInterval) { converter.setInto((ReadWritableInterval) this, interval, chrono); } else { MutableInterval mi = new MutableInterval(); converter.setInto(mi, interval, chrono); iChronology = mi.getChronology(); iStartMillis = mi.getStartMillis(); iEndMillis = mi.getEndMillis(); } checkInterval(iStartMillis, iEndMillis); } //----------------------------------------------------------------------- /** * Gets the chronology of this interval. * * @return the chronology */ public Chronology getChronology() { return iChronology; } /** * Gets the start of this time interval which is inclusive. * * @return the start of the time interval, * millisecond instant from 1970-01-01T00:00:00Z */ public long getStartMillis() { return iStartMillis; } /** * Gets the end of this time interval which is exclusive. * * @return the end of the time interval, * millisecond instant from 1970-01-01T00:00:00Z */ public long getEndMillis() { return iEndMillis; } //----------------------------------------------------------------------- /** * Sets this interval from two millisecond instants and a chronology. * * @param startInstant the start of the time interval * @param endInstant the start of the time interval * @param chrono the chronology, not null * @throws IllegalArgumentException if the end is before the start */ protected void setInterval(long startInstant, long endInstant, Chronology chrono) { checkInterval(startInstant, endInstant); iStartMillis = startInstant; iEndMillis = endInstant; iChronology = DateTimeUtils.getChronology(chrono); } } joda-time-2.3/src/main/java/org/joda/time/base/AbstractDuration.java0000644000175000017500000001642011763630667024725 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import org.joda.convert.ToString; import org.joda.time.Duration; import org.joda.time.Period; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; import org.joda.time.format.FormatUtils; /** * AbstractDuration provides the common behaviour for duration classes. *

* This class should generally not be used directly by API users. The * {@link ReadableDuration} interface should be used when different * kinds of durations are to be referenced. *

* AbstractDuration subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractDuration implements ReadableDuration { /** * Constructor. */ protected AbstractDuration() { super(); } //----------------------------------------------------------------------- /** * Get this duration as an immutable Duration object. * * @return a Duration created using the millisecond duration from this instance */ public Duration toDuration() { return new Duration(getMillis()); } //----------------------------------------------------------------------- /** * Converts this duration to a Period instance using the standard period type * and the ISO chronology. *

* Only precise fields in the period type will be used. Thus, only the hour, * minute, second and millisecond fields on the period will be used. * The year, month, week and day fields will not be populated. *

* If the duration is small, less than one day, then this method will perform * as you might expect and split the fields evenly. * If the duration is larger than one day then all the remaining duration will * be stored in the largest available field, hours in this case. *

* For example, a duration effectively equal to (365 + 60 + 5) days will be * converted to ((365 + 60 + 5) * 24) hours by this constructor. *

* For more control over the conversion process, you must pair the duration with * an instant, see {@link Period#Period(ReadableInstant,ReadableDuration)}. * * @return a Period created using the millisecond duration from this instance */ public Period toPeriod() { return new Period(getMillis()); } //----------------------------------------------------------------------- /** * Compares this duration with the specified duration based on length. * * @param other a duration to check against * @return negative value if this is less, 0 if equal, or positive value if greater * @throws NullPointerException if the object is null * @throws ClassCastException if the given object is not supported */ public int compareTo(ReadableDuration other) { long thisMillis = this.getMillis(); long otherMillis = other.getMillis(); // cannot do (thisMillis - otherMillis) as it can overflow if (thisMillis < otherMillis) { return -1; } if (thisMillis > otherMillis) { return 1; } return 0; } /** * Is the length of this duration equal to the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ public boolean isEqual(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) == 0; } /** * Is the length of this duration longer than the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ public boolean isLongerThan(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) > 0; } /** * Is the length of this duration shorter than the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ public boolean isShorterThan(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) < 0; } //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the millisecond length. All ReadableDuration instances are accepted. * * @param duration a readable duration to check against * @return true if the length of the duration is equal */ public boolean equals(Object duration) { if (this == duration) { return true; } if (duration instanceof ReadableDuration == false) { return false; } ReadableDuration other = (ReadableDuration) duration; return (getMillis() == other.getMillis()); } /** * Gets a hash code for the duration that is compatible with the * equals method. * * @return a hash code */ public int hashCode() { long len = getMillis(); return (int) (len ^ (len >>> 32)); } //----------------------------------------------------------------------- /** * Gets the value as a String in the ISO8601 duration format including * only seconds and milliseconds. *

* For example, "PT72.345S" represents 1 minute, 12 seconds and 345 milliseconds. *

* For more control over the output, see * {@link org.joda.time.format.PeriodFormatterBuilder PeriodFormatterBuilder}. * * @return the value as an ISO8601 string */ @ToString public String toString() { long millis = getMillis(); StringBuffer buf = new StringBuffer(); buf.append("PT"); boolean negative = (millis < 0); FormatUtils.appendUnpaddedInteger(buf, millis); while (buf.length() < (negative ? 7 : 6)) { buf.insert(negative ? 3 : 2, "0"); } if ((millis / 1000) * 1000 == millis) { buf.setLength(buf.length() - 3); } else { buf.insert(buf.length() - 3, "."); } buf.append('S'); return buf.toString(); } } joda-time-2.3/src/main/java/org/joda/time/base/AbstractInterval.java0000644000175000017500000004605312200501234024677 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import org.joda.time.DateTime; import org.joda.time.DateTimeUtils; import org.joda.time.Duration; import org.joda.time.Interval; import org.joda.time.MutableInterval; import org.joda.time.Period; import org.joda.time.PeriodType; import org.joda.time.ReadableInstant; import org.joda.time.ReadableInterval; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * AbstractInterval provides the common behaviour for time intervals. *

* This class should generally not be used directly by API users. The * {@link ReadableInterval} interface should be used when different * kinds of intervals are to be referenced. *

* AbstractInterval subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractInterval implements ReadableInterval { /** * Constructor. */ protected AbstractInterval() { super(); } //----------------------------------------------------------------------- /** * Validates an interval. * * @param start the start instant in milliseconds * @param end the end instant in milliseconds * @throws IllegalArgumentException if the interval is invalid */ protected void checkInterval(long start, long end) { if (end < start) { throw new IllegalArgumentException("The end instant must be greater or equal to the start"); } } //----------------------------------------------------------------------- /** * Gets the start of this time interval, which is inclusive, as a DateTime. * * @return the start of the time interval */ public DateTime getStart() { return new DateTime(getStartMillis(), getChronology()); } /** * Gets the end of this time interval, which is exclusive, as a DateTime. * * @return the end of the time interval */ public DateTime getEnd() { return new DateTime(getEndMillis(), getChronology()); } //----------------------------------------------------------------------- /** * Does this time interval contain the specified millisecond instant. *

* Non-zero duration intervals are inclusive of the start instant and * exclusive of the end. A zero duration interval cannot contain anything. * * @param millisInstant the instant to compare to, * millisecond instant from 1970-01-01T00:00:00Z * @return true if this time interval contains the millisecond */ public boolean contains(long millisInstant) { long thisStart = getStartMillis(); long thisEnd = getEndMillis(); return (millisInstant >= thisStart && millisInstant < thisEnd); } /** * Does this time interval contain the current instant. *

* Non-zero duration intervals are inclusive of the start instant and * exclusive of the end. A zero duration interval cannot contain anything. * * @return true if this time interval contains the current instant */ public boolean containsNow() { return contains(DateTimeUtils.currentTimeMillis()); } /** * Does this time interval contain the specified instant. *

* Non-zero duration intervals are inclusive of the start instant and * exclusive of the end. A zero duration interval cannot contain anything. *

* For example: *

     * [09:00 to 10:00) contains 08:59  = false (before start)
     * [09:00 to 10:00) contains 09:00  = true
     * [09:00 to 10:00) contains 09:59  = true
     * [09:00 to 10:00) contains 10:00  = false (equals end)
     * [09:00 to 10:00) contains 10:01  = false (after end)
     * 
     * [14:00 to 14:00) contains 14:00  = false (zero duration contains nothing)
     * 
* Passing in a null parameter will have the same effect as * calling {@link #containsNow()}. * * @param instant the instant, null means now * @return true if this time interval contains the instant */ public boolean contains(ReadableInstant instant) { if (instant == null) { return containsNow(); } return contains(instant.getMillis()); } /** * Does this time interval contain the specified time interval. *

* Non-zero duration intervals are inclusive of the start instant and * exclusive of the end. The other interval is contained if this interval * wholly contains, starts, finishes or equals it. * A zero duration interval cannot contain anything. *

* When two intervals are compared the result is one of three states: * (a) they abut, (b) there is a gap between them, (c) they overlap. * The contains method is not related to these states. * In particular, a zero duration interval is contained at the start of * a larger interval, but does not overlap (it abuts instead). *

* For example: *

     * [09:00 to 10:00) contains [09:00 to 10:00)  = true
     * [09:00 to 10:00) contains [09:00 to 09:30)  = true
     * [09:00 to 10:00) contains [09:30 to 10:00)  = true
     * [09:00 to 10:00) contains [09:15 to 09:45)  = true
     * [09:00 to 10:00) contains [09:00 to 09:00)  = true
     * 
     * [09:00 to 10:00) contains [08:59 to 10:00)  = false (otherStart before thisStart)
     * [09:00 to 10:00) contains [09:00 to 10:01)  = false (otherEnd after thisEnd)
     * [09:00 to 10:00) contains [10:00 to 10:00)  = false (otherStart equals thisEnd)
     * 
     * [14:00 to 14:00) contains [14:00 to 14:00)  = false (zero duration contains nothing)
     * 
* Passing in a null parameter will have the same effect as * calling {@link #containsNow()}. * * @param interval the time interval to compare to, null means a zero duration interval now * @return true if this time interval contains the time interval */ public boolean contains(ReadableInterval interval) { if (interval == null) { return containsNow(); } long otherStart = interval.getStartMillis(); long otherEnd = interval.getEndMillis(); long thisStart = getStartMillis(); long thisEnd = getEndMillis(); return (thisStart <= otherStart && otherStart < thisEnd && otherEnd <= thisEnd); } /** * Does this time interval overlap the specified time interval. *

* Intervals are inclusive of the start instant and exclusive of the end. * An interval overlaps another if it shares some common part of the * datetime continuum. *

* When two intervals are compared the result is one of three states: * (a) they abut, (b) there is a gap between them, (c) they overlap. * The abuts state takes precedence over the other two, thus a zero duration * interval at the start of a larger interval abuts and does not overlap. *

* For example: *

     * [09:00 to 10:00) overlaps [08:00 to 08:30)  = false (completely before)
     * [09:00 to 10:00) overlaps [08:00 to 09:00)  = false (abuts before)
     * [09:00 to 10:00) overlaps [08:00 to 09:30)  = true
     * [09:00 to 10:00) overlaps [08:00 to 10:00)  = true
     * [09:00 to 10:00) overlaps [08:00 to 11:00)  = true
     * 
     * [09:00 to 10:00) overlaps [09:00 to 09:00)  = false (abuts before)
     * [09:00 to 10:00) overlaps [09:00 to 09:30)  = true
     * [09:00 to 10:00) overlaps [09:00 to 10:00)  = true
     * [09:00 to 10:00) overlaps [09:00 to 11:00)  = true
     * 
     * [09:00 to 10:00) overlaps [09:30 to 09:30)  = true
     * [09:00 to 10:00) overlaps [09:30 to 10:00)  = true
     * [09:00 to 10:00) overlaps [09:30 to 11:00)  = true
     * 
     * [09:00 to 10:00) overlaps [10:00 to 10:00)  = false (abuts after)
     * [09:00 to 10:00) overlaps [10:00 to 11:00)  = false (abuts after)
     * 
     * [09:00 to 10:00) overlaps [10:30 to 11:00)  = false (completely after)
     * 
     * [14:00 to 14:00) overlaps [14:00 to 14:00)  = false (abuts before and after)
     * [14:00 to 14:00) overlaps [13:00 to 15:00)  = true
     * 
* * @param interval the time interval to compare to, null means a zero length interval now * @return true if the time intervals overlap */ public boolean overlaps(ReadableInterval interval) { long thisStart = getStartMillis(); long thisEnd = getEndMillis(); if (interval == null) { long now = DateTimeUtils.currentTimeMillis(); return (thisStart < now && now < thisEnd); } else { long otherStart = interval.getStartMillis(); long otherEnd = interval.getEndMillis(); return (thisStart < otherEnd && otherStart < thisEnd); } } //----------------------------------------------------------------------- /** * Is this interval equal to the specified interval ignoring the chronology. *

* This compares the underlying instants, ignoring the chronology. * * @param other a readable interval to check against * @return true if the intervals are equal comparing the start and end millis * @since 2.3 */ public boolean isEqual(ReadableInterval other) { return getStartMillis() == other.getStartMillis() && getEndMillis() == other.getEndMillis(); } /** * Is this time interval before the specified millisecond instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param millisInstant the instant to compare to, * millisecond instant from 1970-01-01T00:00:00Z * @return true if this time interval is before the instant */ public boolean isBefore(long millisInstant) { return (getEndMillis() <= millisInstant); } /** * Is this time interval before the current instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @return true if this time interval is before the current instant */ public boolean isBeforeNow() { return isBefore(DateTimeUtils.currentTimeMillis()); } /** * Is this time interval before the specified instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param instant the instant to compare to, null means now * @return true if this time interval is before the instant */ public boolean isBefore(ReadableInstant instant) { if (instant == null) { return isBeforeNow(); } return isBefore(instant.getMillis()); } /** * Is this time interval entirely before the specified instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param interval the interval to compare to, null means now * @return true if this time interval is before the interval specified */ public boolean isBefore(ReadableInterval interval) { if (interval == null) { return isBeforeNow(); } return isBefore(interval.getStartMillis()); } //----------------------------------------------------------------------- /** * Is this time interval after the specified millisecond instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param millisInstant the instant to compare to, * millisecond instant from 1970-01-01T00:00:00Z * @return true if this time interval is after the instant */ public boolean isAfter(long millisInstant) { return (getStartMillis() > millisInstant); } /** * Is this time interval after the current instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @return true if this time interval is after the current instant */ public boolean isAfterNow() { return isAfter(DateTimeUtils.currentTimeMillis()); } /** * Is this time interval after the specified instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param instant the instant to compare to, null means now * @return true if this time interval is after the instant */ public boolean isAfter(ReadableInstant instant) { if (instant == null) { return isAfterNow(); } return isAfter(instant.getMillis()); } /** * Is this time interval entirely after the specified interval. *

* Intervals are inclusive of the start instant and exclusive of the end. * Only the end time of the specified interval is used in the comparison. * * @param interval the interval to compare to, null means now * @return true if this time interval is after the interval specified */ public boolean isAfter(ReadableInterval interval) { long endMillis; if (interval == null) { endMillis = DateTimeUtils.currentTimeMillis(); } else { endMillis = interval.getEndMillis(); } return (getStartMillis() >= endMillis); } //----------------------------------------------------------------------- /** * Get this interval as an immutable Interval object. * * @return the interval as an Interval object */ public Interval toInterval() { return new Interval(getStartMillis(), getEndMillis(), getChronology()); } /** * Get this time interval as a MutableInterval. *

* This will always return a new MutableInterval with the same interval. * * @return the time interval as a MutableInterval object */ public MutableInterval toMutableInterval() { return new MutableInterval(getStartMillis(), getEndMillis(), getChronology()); } //----------------------------------------------------------------------- /** * Gets the duration of this time interval in milliseconds. *

* The duration is equal to the end millis minus the start millis. * * @return the duration of the time interval in milliseconds * @throws ArithmeticException if the duration exceeds the capacity of a long */ public long toDurationMillis() { return FieldUtils.safeAdd(getEndMillis(), -getStartMillis()); } /** * Gets the duration of this time interval. *

* The duration is equal to the end millis minus the start millis. * * @return the duration of the time interval * @throws ArithmeticException if the duration exceeds the capacity of a long */ public Duration toDuration() { long durMillis = toDurationMillis(); if (durMillis == 0) { return Duration.ZERO; } else { return new Duration(durMillis); } } //----------------------------------------------------------------------- /** * Converts the duration of the interval to a Period using the * All period type. *

* This method should be used to exract the field values describing the * difference between the start and end instants. * * @return a time period derived from the interval */ public Period toPeriod() { return new Period(getStartMillis(), getEndMillis(), getChronology()); } /** * Converts the duration of the interval to a Period using the * specified period type. *

* This method should be used to exract the field values describing the * difference between the start and end instants. * * @param type the requested type of the duration, null means AllType * @return a time period derived from the interval */ public Period toPeriod(PeriodType type) { return new Period(getStartMillis(), getEndMillis(), type, getChronology()); } //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on start and end millis plus the chronology. * All ReadableInterval instances are accepted. *

* To compare the duration of two time intervals, use {@link #toDuration()} * to get the durations and compare those. * * @param readableInterval a readable interval to check against * @return true if the intervals are equal comparing the start millis, * end millis and chronology */ public boolean equals(Object readableInterval) { if (this == readableInterval) { return true; } if (readableInterval instanceof ReadableInterval == false) { return false; } ReadableInterval other = (ReadableInterval) readableInterval; return getStartMillis() == other.getStartMillis() && getEndMillis() == other.getEndMillis() && FieldUtils.equals(getChronology(), other.getChronology()); } /** * Hashcode compatible with equals method. * * @return suitable hashcode */ public int hashCode() { long start = getStartMillis(); long end = getEndMillis(); int result = 97; result = 31 * result + ((int) (start ^ (start >>> 32))); result = 31 * result + ((int) (end ^ (end >>> 32))); result = 31 * result + getChronology().hashCode(); return result; } /** * Output a string in ISO8601 interval format. *

* From version 2.1, the string includes the time zone offset. * * @return re-parsable string (in the default zone) */ public String toString() { DateTimeFormatter printer = ISODateTimeFormat.dateTime(); printer = printer.withChronology(getChronology()); StringBuffer buf = new StringBuffer(48); printer.printTo(buf, getStartMillis()); buf.append('/'); printer.printTo(buf, getEndMillis()); return buf.toString(); } } joda-time-2.3/src/main/java/org/joda/time/base/AbstractInstant.java0000644000175000017500000003600011564251363024543 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.util.Date; import org.joda.convert.ToString; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.Instant; import org.joda.time.MutableDateTime; import org.joda.time.ReadableInstant; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * AbstractInstant provides the common behaviour for instant classes. *

* This class has no concept of a chronology, all methods work on the * millisecond instant. *

* This class should generally not be used directly by API users. The * {@link ReadableInstant} interface should be used when different * kinds of date/time objects are to be referenced. *

* Whenever you want to implement ReadableInstant you should * extend this class. *

* AbstractInstant itself is thread-safe and immutable, but subclasses may be * mutable and not thread-safe. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public abstract class AbstractInstant implements ReadableInstant { /** * Constructor. */ protected AbstractInstant() { super(); } //----------------------------------------------------------------------- /** * Gets the time zone of the instant from the chronology. * * @return the DateTimeZone that the instant is using, never null */ public DateTimeZone getZone() { return getChronology().getZone(); } /** * Get the value of one of the fields of a datetime using the chronology of the instant. *

* This method uses the chronology of the instant to obtain the value. * For example: *

     * DateTime dt = new DateTime();
     * int year = dt.get(DateTimeFieldType.year());
     * 
* * @param type a field type, usually obtained from DateTimeFieldType, not null * @return the value of that field * @throws IllegalArgumentException if the field type is null */ public int get(DateTimeFieldType type) { if (type == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } return type.getField(getChronology()).get(getMillis()); } /** * Checks if the field type specified is supported by this instant and chronology. * This can be used to avoid exceptions in {@link #get(DateTimeFieldType)}. * * @param type a field type, usually obtained from DateTimeFieldType * @return true if the field type is supported */ public boolean isSupported(DateTimeFieldType type) { if (type == null) { return false; } return type.getField(getChronology()).isSupported(); } /** * Get the value of one of the fields of a datetime. *

* This could be used to get a field using a different Chronology. * For example: *

     * Instant dt = new Instant();
     * int gjYear = dt.get(Chronology.getCoptic().year());
     * 
* * @param field the DateTimeField to use, not null * @return the value * @throws IllegalArgumentException if the field is null */ public int get(DateTimeField field) { if (field == null) { throw new IllegalArgumentException("The DateTimeField must not be null"); } return field.get(getMillis()); } //----------------------------------------------------------------------- /** * Get this object as an Instant. * * @return an Instant using the same millis */ public Instant toInstant() { return new Instant(getMillis()); } /** * Get this object as a DateTime in the same zone. * * @return a DateTime using the same millis */ public DateTime toDateTime() { return new DateTime(getMillis(), getZone()); } /** * Get this object as a DateTime using ISOChronology in the same zone. * * @return a DateTime using the same millis with ISOChronology */ public DateTime toDateTimeISO() { return new DateTime(getMillis(), ISOChronology.getInstance(getZone())); } /** * Get this object as a DateTime using the same chronology but a different zone. * * @param zone time zone to apply, or default if null * @return a DateTime using the same millis */ public DateTime toDateTime(DateTimeZone zone) { Chronology chrono = DateTimeUtils.getChronology(getChronology()); chrono = chrono.withZone(zone); return new DateTime(getMillis(), chrono); } /** * Get this object as a DateTime using the given chronology and its zone. * * @param chronology chronology to apply, or ISOChronology if null * @return a DateTime using the same millis */ public DateTime toDateTime(Chronology chronology) { return new DateTime(getMillis(), chronology); } // NOTE: Although the toMutableDateTime methods could check to see if this // is already a MutableDateTime and return this casted, it makes it too // easy to mistakenly modify ReadableDateTime input parameters. Always // returning a copy prevents this. /** * Get this object as a MutableDateTime in the same zone. * * @return a MutableDateTime using the same millis */ public MutableDateTime toMutableDateTime() { return new MutableDateTime(getMillis(), getZone()); } /** * Get this object as a MutableDateTime using ISOChronology in the same zone. * * @return a MutableDateTime using the same millis with ISOChronology */ public MutableDateTime toMutableDateTimeISO() { return new MutableDateTime(getMillis(), ISOChronology.getInstance(getZone())); } /** * Get this object as a MutableDateTime using the same chronology but a different zone. * * @param zone time zone to apply, or default if null * @return a MutableDateTime using the same millis */ public MutableDateTime toMutableDateTime(DateTimeZone zone) { Chronology chrono = DateTimeUtils.getChronology(getChronology()); chrono = chrono.withZone(zone); return new MutableDateTime(getMillis(), chrono); } /** * Get this object as a MutableDateTime using the given chronology and its zone. * * @param chronology chronology to apply, or ISOChronology if null * @return a MutableDateTime using the same millis */ public MutableDateTime toMutableDateTime(Chronology chronology) { return new MutableDateTime(getMillis(), chronology); } //----------------------------------------------------------------------- /** * Get the date time as a java.util.Date. *

* The Date object created has exactly the same millisecond * instant as this object. * * @return a Date initialised with this datetime */ public Date toDate() { return new Date(getMillis()); } //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the millisecond instant, chronology and time zone. *

* Two objects which represent the same instant in time, but are in * different time zones (based on time zone id), will be considered to * be different. Only two objects with the same {@link DateTimeZone}, * {@link Chronology} and instant are equal. *

* See {@link #isEqual(ReadableInstant)} for an equals method that * ignores the Chronology and time zone. *

* All ReadableInstant instances are accepted. * * @param readableInstant a readable instant to check against * @return true if millisecond and chronology are equal, false if * not or the instant is null or of an incorrect type */ public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); } /** * Gets a hash code for the instant as defined in ReadableInstant. * * @return a suitable hash code */ public int hashCode() { // must be to fulfil ReadableInstant contract return ((int) (getMillis() ^ (getMillis() >>> 32))) + (getChronology().hashCode()); } /** * Compares this object with the specified object for ascending * millisecond instant order. This ordering is inconsistent with * equals, as it ignores the Chronology. *

* All ReadableInstant instances are accepted. * * @param other a readable instant to check against * @return negative value if this is less, 0 if equal, or positive value if greater * @throws NullPointerException if the object is null * @throws ClassCastException if the object type is not supported */ public int compareTo(ReadableInstant other) { if (this == other) { return 0; } long otherMillis = other.getMillis(); long thisMillis = getMillis(); // cannot do (thisMillis - otherMillis) as can overflow if (thisMillis == otherMillis) { return 0; } if (thisMillis < otherMillis) { return -1; } else { return 1; } } //----------------------------------------------------------------------- /** * Is this instant after the millisecond instant passed in * comparing solely by millisecond. * * @param instant a millisecond instant to check against * @return true if this instant is after the instant passed in */ public boolean isAfter(long instant) { return (getMillis() > instant); } /** * Is this instant after the current instant * comparing solely by millisecond. * * @return true if this instant is after the current instant */ public boolean isAfterNow() { return isAfter(DateTimeUtils.currentTimeMillis()); } /** * Is this instant after the instant passed in * comparing solely by millisecond. * * @param instant an instant to check against, null means now * @return true if the instant is after the instant passed in */ public boolean isAfter(ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); return isAfter(instantMillis); } //----------------------------------------------------------------------- /** * Is this instant before the millisecond instant passed in * comparing solely by millisecond. * * @param instant a millisecond instant to check against * @return true if this instant is before the instant passed in */ public boolean isBefore(long instant) { return (getMillis() < instant); } /** * Is this instant before the current instant * comparing solely by millisecond. * * @return true if this instant is before the current instant */ public boolean isBeforeNow() { return isBefore(DateTimeUtils.currentTimeMillis()); } /** * Is this instant before the instant passed in * comparing solely by millisecond. * * @param instant an instant to check against, null means now * @return true if the instant is before the instant passed in */ public boolean isBefore(ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); return isBefore(instantMillis); } //----------------------------------------------------------------------- /** * Is this instant equal to the millisecond instant passed in * comparing solely by millisecond. * * @param instant a millisecond instant to check against * @return true if this instant is before the instant passed in */ public boolean isEqual(long instant) { return (getMillis() == instant); } /** * Is this instant equal to the current instant * comparing solely by millisecond. * * @return true if this instant is before the current instant */ public boolean isEqualNow() { return isEqual(DateTimeUtils.currentTimeMillis()); } /** * Is this instant equal to the instant passed in * comparing solely by millisecond. * * @param instant an instant to check against, null means now * @return true if the instant is equal to the instant passed in */ public boolean isEqual(ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); return isEqual(instantMillis); } //----------------------------------------------------------------------- /** * Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ). * * @return ISO8601 time formatted string. */ @ToString public String toString() { return ISODateTimeFormat.dateTime().print(this); } //----------------------------------------------------------------------- /** * Uses the specified formatter to convert this partial to a String. * * @param formatter the formatter to use, null means use toString(). * @return the formatted string * @since 1.1 */ public String toString(DateTimeFormatter formatter) { if (formatter == null) { return toString(); } return formatter.print(this); } } joda-time-2.3/src/main/java/org/joda/time/base/BaseDateTime.java0000644000175000017500000003054111600100621023707 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.io.Serializable; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.ReadableDateTime; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.InstantConverter; /** * BaseDateTime is an abstract implementation of ReadableDateTime that stores * data in long and Chronology fields. *

* This class should generally not be used directly by API users. * The {@link ReadableDateTime} interface should be used when different * kinds of date/time objects are to be referenced. *

* BaseDateTime subclasses may be mutable and not thread-safe. * * @author Stephen Colebourne * @author Kandarp Shah * @author Brian S O'Neill * @since 1.0 */ public abstract class BaseDateTime extends AbstractDateTime implements ReadableDateTime, Serializable { /** Serialization lock */ private static final long serialVersionUID = -6728882245981L; /** The millis from 1970-01-01T00:00:00Z */ private volatile long iMillis; /** The chronology to use */ private volatile Chronology iChronology; //----------------------------------------------------------------------- /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the default time zone. */ public BaseDateTime() { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance()); } /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param zone the time zone, null means default zone */ public BaseDateTime(DateTimeZone zone) { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the current system millisecond time * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param chronology the chronology, null means ISOChronology in default zone */ public BaseDateTime(Chronology chronology) { this(DateTimeUtils.currentTimeMillis(), chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the default time zone. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public BaseDateTime(long instant) { this(instant, ISOChronology.getInstance()); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public BaseDateTime(long instant, DateTimeZone zone) { this(instant, ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public BaseDateTime(long instant, Chronology chronology) { super(); iChronology = checkChronology(chronology); iMillis = checkInstant(instant, iChronology); } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. *

* If the object contains no chronology, ISOChronology is used. * If the specified time zone is null, the default zone is used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object * @param zone the time zone * @throws IllegalArgumentException if the instant is invalid */ public BaseDateTime(Object instant, DateTimeZone zone) { super(); InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant); Chronology chrono = checkChronology(converter.getChronology(instant, zone)); iChronology = chrono; iMillis = checkInstant(converter.getInstantMillis(instant, chrono), chrono); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. *

* If the chronology is null, ISO in the default time zone is used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object * @param chronology the chronology * @throws IllegalArgumentException if the instant is invalid */ public BaseDateTime(Object instant, Chronology chronology) { super(); InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant); iChronology = checkChronology(converter.getChronology(instant, chronology)); iMillis = checkInstant(converter.getInstantMillis(instant, chronology), iChronology); } //----------------------------------------------------------------------- /** * Constructs an instance from datetime field values * using ISOChronology in the default time zone. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second */ public BaseDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { this(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, ISOChronology.getInstance()); } /** * Constructs an instance from datetime field values * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param zone the time zone, null means default time zone */ public BaseDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, DateTimeZone zone) { this(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, ISOChronology.getInstance(zone)); } /** * Constructs an instance from datetime field values * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param chronology the chronology, null means ISOChronology in default zone */ public BaseDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(); iChronology = checkChronology(chronology); long instant = iChronology.getDateTimeMillis(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); iMillis = checkInstant(instant, iChronology); } //----------------------------------------------------------------------- /** * Checks the specified chronology before storing it, potentially altering it. * This method must not access any instance variables. *

* This implementation converts nulls to ISOChronology in the default zone. * * @param chronology the chronology to use, may be null * @return the chronology to store in this datetime, not null */ protected Chronology checkChronology(Chronology chronology) { return DateTimeUtils.getChronology(chronology); } /** * Checks the specified instant before storing it, potentially altering it. * This method must not access any instance variables. *

* This implementation simply returns the instant. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @param chronology the chronology to use, not null * @return the instant to store in this datetime */ protected long checkInstant(long instant, Chronology chronology) { return instant; } //----------------------------------------------------------------------- /** * Gets the milliseconds of the datetime instant from the Java epoch * of 1970-01-01T00:00:00Z. * * @return the number of milliseconds since 1970-01-01T00:00:00Z */ public long getMillis() { return iMillis; } /** * Gets the chronology of the datetime. * * @return the Chronology that the datetime is using */ public Chronology getChronology() { return iChronology; } //----------------------------------------------------------------------- /** * Sets the milliseconds of the datetime. *

* All changes to the millisecond field occurs via this method. * Override and block this method to make a subclass immutable. * * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the datetime to */ protected void setMillis(long instant) { iMillis = checkInstant(instant, iChronology); } /** * Sets the chronology of the datetime. *

* All changes to the chronology field occurs via this method. * Override and block this method to make a subclass immutable. * * @param chronology the chronology to set */ protected void setChronology(Chronology chronology) { iChronology = checkChronology(chronology); } } joda-time-2.3/src/main/java/org/joda/time/base/BasePeriod.java0000644000175000017500000006262311721223530023454 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import java.io.Serializable; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.Duration; import org.joda.time.DurationFieldType; import org.joda.time.MutablePeriod; import org.joda.time.PeriodType; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; import org.joda.time.ReadablePartial; import org.joda.time.ReadablePeriod; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.PeriodConverter; import org.joda.time.field.FieldUtils; /** * BasePeriod is an abstract implementation of ReadablePeriod that stores * data in a PeriodType and an int[]. *

* This class should generally not be used directly by API users. * The {@link ReadablePeriod} interface should be used when different * kinds of period objects are to be referenced. *

* BasePeriod subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class BasePeriod extends AbstractPeriod implements ReadablePeriod, Serializable { /** Serialization version */ private static final long serialVersionUID = -2110953284060001145L; /** Serialization version */ private static final ReadablePeriod DUMMY_PERIOD = new AbstractPeriod() { public int getValue(int index) { return 0; } public PeriodType getPeriodType() { return PeriodType.time(); } }; /** The type of period */ private final PeriodType iType; /** The values */ private final int[] iValues; //----------------------------------------------------------------------- /** * Creates a period from a set of field values. * * @param years amount of years in this period, which must be zero if unsupported * @param months amount of months in this period, which must be zero if unsupported * @param weeks amount of weeks in this period, which must be zero if unsupported * @param days amount of days in this period, which must be zero if unsupported * @param hours amount of hours in this period, which must be zero if unsupported * @param minutes amount of minutes in this period, which must be zero if unsupported * @param seconds amount of seconds in this period, which must be zero if unsupported * @param millis amount of milliseconds in this period, which must be zero if unsupported * @param type which set of fields this period supports * @throws IllegalArgumentException if period type is invalid * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected BasePeriod(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis, PeriodType type) { super(); type = checkPeriodType(type); iType = type; iValues = setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis); // internal method } /** * Creates a period from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param type which set of fields this period supports, null means standard * @param chrono the chronology to use, null means ISO default * @throws IllegalArgumentException if period type is invalid */ protected BasePeriod(long startInstant, long endInstant, PeriodType type, Chronology chrono) { super(); type = checkPeriodType(type); chrono = DateTimeUtils.getChronology(chrono); iType = type; iValues = chrono.get(this, startInstant, endInstant); } /** * Creates a period from the given interval endpoints. * * @param startInstant interval start, null means now * @param endInstant interval end, null means now * @param type which set of fields this period supports, null means standard * @throws IllegalArgumentException if period type is invalid */ protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) { super(); type = checkPeriodType(type); if (startInstant == null && endInstant == null) { iType = type; iValues = new int[size()]; } else { long startMillis = DateTimeUtils.getInstantMillis(startInstant); long endMillis = DateTimeUtils.getInstantMillis(endInstant); Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); } } /** * Creates a period from the given duration and end point. *

* The two partials must contain the same fields, thus you can * specify two LocalDate objects, or two LocalTime * objects, but not one of each. * As these are Partial objects, time zones have no effect on the result. *

* The two partials must also both be contiguous - see * {@link DateTimeUtils#isContiguous(ReadablePartial)} for a * definition. Both LocalDate and LocalTime are contiguous. * * @param start the start of the period, must not be null * @param end the end of the period, must not be null * @param type which set of fields this period supports, null means standard * @throws IllegalArgumentException if the partials are null or invalid * @since 1.1 */ protected BasePeriod(ReadablePartial start, ReadablePartial end, PeriodType type) { super(); if (start == null || end == null) { throw new IllegalArgumentException("ReadablePartial objects must not be null"); } if (start instanceof BaseLocal && end instanceof BaseLocal && start.getClass() == end.getClass()) { // for performance type = checkPeriodType(type); long startMillis = ((BaseLocal) start).getLocalMillis(); long endMillis = ((BaseLocal) end).getLocalMillis(); Chronology chrono = start.getChronology(); chrono = DateTimeUtils.getChronology(chrono); iType = type; iValues = chrono.get(this, startMillis, endMillis); } else { if (start.size() != end.size()) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } for (int i = 0, isize = start.size(); i < isize; i++) { if (start.getFieldType(i) != end.getFieldType(i)) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } } if (DateTimeUtils.isContiguous(start) == false) { throw new IllegalArgumentException("ReadablePartial objects must be contiguous"); } iType = checkPeriodType(type); Chronology chrono = DateTimeUtils.getChronology(start.getChronology()).withUTC(); iValues = chrono.get(this, chrono.set(start, 0L), chrono.set(end, 0L)); } } /** * Creates a period from the given start point and duration. * * @param startInstant the interval start, null means now * @param duration the duration of the interval, null means zero-length * @param type which set of fields this period supports, null means standard */ protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { super(); type = checkPeriodType(type); long startMillis = DateTimeUtils.getInstantMillis(startInstant); long durationMillis = DateTimeUtils.getDurationMillis(duration); long endMillis = FieldUtils.safeAdd(startMillis, durationMillis); Chronology chrono = DateTimeUtils.getInstantChronology(startInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); } /** * Creates a period from the given duration and end point. * * @param duration the duration of the interval, null means zero-length * @param endInstant the interval end, null means now * @param type which set of fields this period supports, null means standard */ protected BasePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) { super(); type = checkPeriodType(type); long durationMillis = DateTimeUtils.getDurationMillis(duration); long endMillis = DateTimeUtils.getInstantMillis(endInstant); long startMillis = FieldUtils.safeSubtract(endMillis, durationMillis); Chronology chrono = DateTimeUtils.getInstantChronology(endInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); } /** * Creates a period from the given millisecond duration with the standard period type * and ISO rules, ensuring that the calculation is performed with the time-only period type. *

* The calculation uses the hour, minute, second and millisecond fields. * * @param duration the duration, in milliseconds */ protected BasePeriod(long duration) { super(); // bug [3264409] // calculation uses period type from a period object (bad design) // thus we use a dummy period object with the time type iType = PeriodType.standard(); int[] values = ISOChronology.getInstanceUTC().get(DUMMY_PERIOD, duration); iValues = new int[8]; System.arraycopy(values, 0, iValues, 4, 4); } /** * Creates a period from the given millisecond duration, which is only really * suitable for durations less than one day. *

* Only fields that are precise will be used. * Thus the largest precise field may have a large value. * * @param duration the duration, in milliseconds * @param type which set of fields this period supports, null means standard * @param chrono the chronology to use, null means ISO default * @throws IllegalArgumentException if period type is invalid */ protected BasePeriod(long duration, PeriodType type, Chronology chrono) { super(); type = checkPeriodType(type); chrono = DateTimeUtils.getChronology(chrono); iType = type; iValues = chrono.get(this, duration); } /** * Creates a new period based on another using the {@link ConverterManager}. * * @param period the period to convert * @param type which set of fields this period supports, null means use type from object * @param chrono the chronology to use, null means ISO default * @throws IllegalArgumentException if period is invalid * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected BasePeriod(Object period, PeriodType type, Chronology chrono) { super(); PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period); type = (type == null ? converter.getPeriodType(period) : type); type = checkPeriodType(type); iType = type; if (this instanceof ReadWritablePeriod) { iValues = new int[size()]; chrono = DateTimeUtils.getChronology(chrono); converter.setInto((ReadWritablePeriod) this, period, chrono); } else { iValues = new MutablePeriod(period, type, chrono).getValues(); } } /** * Constructor used when we trust ourselves. * Do not expose publically. * * @param values the values to use, not null, not cloned * @param type which set of fields this period supports, not null */ protected BasePeriod(int[] values, PeriodType type) { super(); iType = type; iValues = values; } //----------------------------------------------------------------------- /** * Validates a period type, converting nulls to a default value and * checking the type is suitable for this instance. * * @param type the type to check, may be null * @return the validated type to use, not null * @throws IllegalArgumentException if the period type is invalid */ protected PeriodType checkPeriodType(PeriodType type) { return DateTimeUtils.getPeriodType(type); } //----------------------------------------------------------------------- /** * Gets the period type. * * @return the period type */ public PeriodType getPeriodType() { return iType; } /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value of the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public int getValue(int index) { return iValues[index]; } //----------------------------------------------------------------------- /** * Gets the total millisecond duration of this period relative to a start instant. *

* This method adds the period to the specified instant in order to * calculate the duration. *

* An instant must be supplied as the duration of a period varies. * For example, a period of 1 month could vary between the equivalent of * 28 and 31 days in milliseconds due to different length months. * Similarly, a day can vary at Daylight Savings cutover, typically between * 23 and 25 hours. * * @param startInstant the instant to add the period to, thus obtaining the duration * @return the total length of the period as a duration relative to the start instant * @throws ArithmeticException if the millis exceeds the capacity of the duration */ public Duration toDurationFrom(ReadableInstant startInstant) { long startMillis = DateTimeUtils.getInstantMillis(startInstant); Chronology chrono = DateTimeUtils.getInstantChronology(startInstant); long endMillis = chrono.add(this, startMillis, 1); return new Duration(startMillis, endMillis); } /** * Gets the total millisecond duration of this period relative to an * end instant. *

* This method subtracts the period from the specified instant in order * to calculate the duration. *

* An instant must be supplied as the duration of a period varies. * For example, a period of 1 month could vary between the equivalent of * 28 and 31 days in milliseconds due to different length months. * Similarly, a day can vary at Daylight Savings cutover, typically between * 23 and 25 hours. * * @param endInstant the instant to subtract the period from, thus obtaining the duration * @return the total length of the period as a duration relative to the end instant * @throws ArithmeticException if the millis exceeds the capacity of the duration */ public Duration toDurationTo(ReadableInstant endInstant) { long endMillis = DateTimeUtils.getInstantMillis(endInstant); Chronology chrono = DateTimeUtils.getInstantChronology(endInstant); long startMillis = chrono.add(this, endMillis, -1); return new Duration(startMillis, endMillis); } //----------------------------------------------------------------------- /** * Checks whether a field type is supported, and if so adds the new value * to the relevant index in the specified array. * * @param type the field type * @param values the array to update * @param newValue the new value to store if successful */ private void checkAndUpdate(DurationFieldType type, int[] values, int newValue) { int index = indexOf(type); if (index == -1) { if (newValue != 0) { throw new IllegalArgumentException( "Period does not support field '" + type.getName() + "'"); } } else { values[index] = newValue; } } //----------------------------------------------------------------------- /** * Sets all the fields of this period from another. * * @param period the period to copy from, not null * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected void setPeriod(ReadablePeriod period) { if (period == null) { setValues(new int[size()]); } else { setPeriodInternal(period); } } /** * Private method called from constructor. */ private void setPeriodInternal(ReadablePeriod period) { int[] newValues = new int[size()]; for (int i = 0, isize = period.size(); i < isize; i++) { DurationFieldType type = period.getFieldType(i); int value = period.getValue(i); checkAndUpdate(type, newValues, value); } setValues(newValues); } /** * Sets the eight standard the fields in one go. * * @param years amount of years in this period, which must be zero if unsupported * @param months amount of months in this period, which must be zero if unsupported * @param weeks amount of weeks in this period, which must be zero if unsupported * @param days amount of days in this period, which must be zero if unsupported * @param hours amount of hours in this period, which must be zero if unsupported * @param minutes amount of minutes in this period, which must be zero if unsupported * @param seconds amount of seconds in this period, which must be zero if unsupported * @param millis amount of milliseconds in this period, which must be zero if unsupported * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected void setPeriod(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { int[] newValues = setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis); setValues(newValues); } /** * Private method called from constructor. */ private int[] setPeriodInternal(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { int[] newValues = new int[size()]; checkAndUpdate(DurationFieldType.years(), newValues, years); checkAndUpdate(DurationFieldType.months(), newValues, months); checkAndUpdate(DurationFieldType.weeks(), newValues, weeks); checkAndUpdate(DurationFieldType.days(), newValues, days); checkAndUpdate(DurationFieldType.hours(), newValues, hours); checkAndUpdate(DurationFieldType.minutes(), newValues, minutes); checkAndUpdate(DurationFieldType.seconds(), newValues, seconds); checkAndUpdate(DurationFieldType.millis(), newValues, millis); return newValues; } //----------------------------------------------------------------------- /** * Sets the value of a field in this period. * * @param field the field to set * @param value the value to set * @throws IllegalArgumentException if field is is null or not supported. */ protected void setField(DurationFieldType field, int value) { setFieldInto(iValues, field, value); } /** * Sets the value of a field in this period. * * @param values the array of values to update * @param field the field to set * @param value the value to set * @throws IllegalArgumentException if field is null or not supported. */ protected void setFieldInto(int[] values, DurationFieldType field, int value) { int index = indexOf(field); if (index == -1) { if (value != 0 || field == null) { throw new IllegalArgumentException( "Period does not support field '" + field + "'"); } } else { values[index] = value; } } /** * Adds the value of a field in this period. * * @param field the field to set * @param value the value to set * @throws IllegalArgumentException if field is is null or not supported. */ protected void addField(DurationFieldType field, int value) { addFieldInto(iValues, field, value); } /** * Adds the value of a field in this period. * * @param values the array of values to update * @param field the field to set * @param value the value to set * @throws IllegalArgumentException if field is is null or not supported. */ protected void addFieldInto(int[] values, DurationFieldType field, int value) { int index = indexOf(field); if (index == -1) { if (value != 0 || field == null) { throw new IllegalArgumentException( "Period does not support field '" + field + "'"); } } else { values[index] = FieldUtils.safeAdd(values[index], value); } } /** * Merges the fields from another period. * * @param period the period to add from, not null * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected void mergePeriod(ReadablePeriod period) { if (period != null) { setValues(mergePeriodInto(getValues(), period)); } } /** * Merges the fields from another period. * * @param values the array of values to update * @param period the period to add from, not null * @return the updated values * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected int[] mergePeriodInto(int[] values, ReadablePeriod period) { for (int i = 0, isize = period.size(); i < isize; i++) { DurationFieldType type = period.getFieldType(i); int value = period.getValue(i); checkAndUpdate(type, values, value); } return values; } /** * Adds the fields from another period. * * @param period the period to add from, not null * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected void addPeriod(ReadablePeriod period) { if (period != null) { setValues(addPeriodInto(getValues(), period)); } } /** * Adds the fields from another period. * * @param values the array of values to update * @param period the period to add from, not null * @return the updated values * @throws IllegalArgumentException if an unsupported field's value is non-zero */ protected int[] addPeriodInto(int[] values, ReadablePeriod period) { for (int i = 0, isize = period.size(); i < isize; i++) { DurationFieldType type = period.getFieldType(i); int value = period.getValue(i); if (value != 0) { int index = indexOf(type); if (index == -1) { throw new IllegalArgumentException( "Period does not support field '" + type.getName() + "'"); } else { values[index] = FieldUtils.safeAdd(getValue(index), value); } } } return values; } //----------------------------------------------------------------------- /** * Sets the value of the field at the specified index. * * @param index the index * @param value the value to set * @throws IndexOutOfBoundsException if the index is invalid */ protected void setValue(int index, int value) { iValues[index] = value; } /** * Sets the values of all fields. *

* In version 2.0 and later, this method copies the array into the original. * This is because the instance variable has been changed to be final to satisfy the Java Memory Model. * This only impacts subclasses that are mutable. * * @param values the array of values */ protected void setValues(int[] values) { System.arraycopy(values, 0, iValues, 0, iValues.length); } } joda-time-2.3/src/main/java/org/joda/time/base/AbstractPeriod.java0000644000175000017500000002031112162055431024334 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.base; import org.joda.convert.ToString; import org.joda.time.DurationFieldType; import org.joda.time.MutablePeriod; import org.joda.time.Period; import org.joda.time.ReadablePeriod; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * AbstractPeriod provides the common behaviour for period classes. *

* This class should generally not be used directly by API users. The * {@link ReadablePeriod} interface should be used when different * kinds of periods are to be referenced. *

* AbstractPeriod subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractPeriod implements ReadablePeriod { /** * Constructor. */ protected AbstractPeriod() { super(); } //----------------------------------------------------------------------- /** * Gets the number of fields that this period supports. * * @return the number of fields supported * @since 2.0 (previously on BasePeriod) */ public int size() { return getPeriodType().size(); } /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid * @since 2.0 (previously on BasePeriod) */ public DurationFieldType getFieldType(int index) { return getPeriodType().getFieldType(index); } /** * Gets an array of the field types that this period supports. *

* The fields are returned largest to smallest, for example Hours, Minutes, Seconds. * * @return the fields supported in an array that may be altered, largest to smallest */ public DurationFieldType[] getFieldTypes() { DurationFieldType[] result = new DurationFieldType[size()]; for (int i = 0; i < result.length; i++) { result[i] = getFieldType(i); } return result; } /** * Gets an array of the value of each of the fields that this period supports. *

* The fields are returned largest to smallest, for example Hours, Minutes, Seconds. * Each value corresponds to the same array index as getFields() * * @return the current values of each field in an array that may be altered, largest to smallest */ public int[] getValues() { int[] result = new int[size()]; for (int i = 0; i < result.length; i++) { result[i] = getValue(i); } return result; } //----------------------------------------------------------------------- /** * Gets the value of one of the fields. *

* If the field type specified is not supported by the period then zero * is returned. * * @param type the field type to query, null returns zero * @return the value of that field, zero if field not supported */ public int get(DurationFieldType type) { int index = indexOf(type); if (index == -1) { return 0; } return getValue(index); } /** * Checks whether the field specified is supported by this period. * * @param type the type to check, may be null which returns false * @return true if the field is supported */ public boolean isSupported(DurationFieldType type) { return getPeriodType().isSupported(type); } /** * Gets the index of the field in this period. * * @param type the type to check, may be null which returns -1 * @return the index of -1 if not supported */ public int indexOf(DurationFieldType type) { return getPeriodType().indexOf(type); } //----------------------------------------------------------------------- /** * Get this period as an immutable Period object. * * @return a Period using the same field set and values */ public Period toPeriod() { return new Period(this); } /** * Get this object as a MutablePeriod. *

* This will always return a new MutablePeriod with the same fields. * * @return a MutablePeriod using the same field set and values */ public MutablePeriod toMutablePeriod() { return new MutablePeriod(this); } //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the value of each field. All ReadablePeriod instances are accepted. *

* Note that a period of 1 day is not equal to a period of 24 hours, * nor is 1 hour equal to 60 minutes. Only periods with the same amount * in each field are equal. *

* This is because periods represent an abstracted definition of a time * period (eg. a day may not actually be 24 hours, it might be 23 or 25 * at daylight savings boundary). *

* To compare the actual duration of two periods, convert both to * {@link org.joda.time.Duration Duration}s, an operation that emphasises * that the result may differ according to the date you choose. * * @param period a readable period to check against * @return true if all the field values are equal, false if * not or the period is null or of an incorrect type */ public boolean equals(Object period) { if (this == period) { return true; } if (period instanceof ReadablePeriod == false) { return false; } ReadablePeriod other = (ReadablePeriod) period; if (size() != other.size()) { return false; } for (int i = 0, isize = size(); i < isize; i++) { if (getValue(i) != other.getValue(i) || getFieldType(i) != other.getFieldType(i)) { return false; } } return true; } /** * Gets a hash code for the period as defined by ReadablePeriod. * * @return a hash code */ public int hashCode() { int total = 17; for (int i = 0, isize = size(); i < isize; i++) { total = 27 * total + getValue(i); total = 27 * total + getFieldType(i).hashCode(); } return total; } //----------------------------------------------------------------------- /** * Gets the value as a String in the ISO8601 duration format. *

* For example, "PT6H3M7S" represents 6 hours, 3 minutes, 7 seconds. *

* For more control over the output, see * {@link org.joda.time.format.PeriodFormatterBuilder PeriodFormatterBuilder}. * * @return the value as an ISO8601 string */ @ToString public String toString() { return ISOPeriodFormat.standard().print(this); } //----------------------------------------------------------------------- /** * Uses the specified formatter to convert this period to a String. * * @param formatter the formatter to use, null means use toString(). * @return the formatted string * @since 1.5 */ public String toString(PeriodFormatter formatter) { if (formatter == null) { return toString(); } return formatter.print(this); } } joda-time-2.3/src/main/java/org/joda/time/base/package.html0000644000175000017500000000246711564251363023067 0ustar ebourgebourg org.joda.time.chrono package

Implementation package providing abstract and base time classes.

Provides abstract implementations of the Readable* interfaces. The Abstract* classes hold no fields and have no final methods. They can be used by anyone wanting to implement the interface. The Base* classes extend the Abstract* classes to provide fields for the standard way to implement the class.

If you intend to implement a Readable* interface yourself, please consider extending either the Abstract* or Base* class in this package.

joda-time-2.3/src/main/java/org/joda/time/ReadWritablePeriod.java0000644000175000017500000002606611564251363024250 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines a duration of time that can be queried and modified using datetime fields. *

* The implementation of this interface will be mutable. * It may provide more advanced methods than those in the interface. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public interface ReadWritablePeriod extends ReadablePeriod { /** * Clears the period, setting all values back to zero. */ void clear(); /** * Sets the value of one of the fields by index. * * @param index the field index * @param value the new value for the field * @throws IndexOutOfBoundsException if the index is invalid */ void setValue(int index, int value); /** * Sets the value of one of the fields. *

* The field type specified must be one of those that is supported by the period. * * @param field a DurationFieldType instance that is supported by this period * @param value the new value for the field * @throws IllegalArgumentException if the field is null or not supported */ void set(DurationFieldType field, int value); /** * Sets all the fields in one go from another ReadablePeriod. * * @param period the period to set, null means zero length period * @throws IllegalArgumentException if an unsupported field's value is non-zero */ void setPeriod(ReadablePeriod period); /** * Sets all the fields in one go. * * @param years amount of years in this period, which must be zero if unsupported * @param months amount of months in this period, which must be zero if unsupported * @param weeks amount of weeks in this period, which must be zero if unsupported * @param days amount of days in this period, which must be zero if unsupported * @param hours amount of hours in this period, which must be zero if unsupported * @param minutes amount of minutes in this period, which must be zero if unsupported * @param seconds amount of seconds in this period, which must be zero if unsupported * @param millis amount of milliseconds in this period, which must be zero if unsupported * @throws IllegalArgumentException if an unsupported field's value is non-zero */ void setPeriod(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis); /** * Sets all the fields in one go from an interval dividing the * fields using the period type. * * @param interval the interval to set, null means zero length */ void setPeriod(ReadableInterval interval); //----------------------------------------------------------------------- /** * Adds to the value of one of the fields. *

* The field type specified must be one of those that is supported by the period. * * @param field a DurationFieldType instance that is supported by this period * @param value the value to add to the field * @throws IllegalArgumentException if the field is null or not supported */ void add(DurationFieldType field, int value); /** * Adds a period to this one by adding each field in turn. * * @param period the period to add, null means add nothing * @throws IllegalArgumentException if the period being added contains a field * not supported by this period * @throws ArithmeticException if the addition exceeds the capacity of the period */ void add(ReadablePeriod period); /** * Adds to each field of this period. * * @param years amount of years to add to this period, which must be zero if unsupported * @param months amount of months to add to this period, which must be zero if unsupported * @param weeks amount of weeks to add to this period, which must be zero if unsupported * @param days amount of days to add to this period, which must be zero if unsupported * @param hours amount of hours to add to this period, which must be zero if unsupported * @param minutes amount of minutes to add to this period, which must be zero if unsupported * @param seconds amount of seconds to add to this period, which must be zero if unsupported * @param millis amount of milliseconds to add to this period, which must be zero if unsupported * @throws IllegalArgumentException if the period being added contains a field * not supported by this period * @throws ArithmeticException if the addition exceeds the capacity of the period */ void add(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis); /** * Adds an interval to this one by dividing the interval into * fields and then adding each field in turn. * * @param interval the interval to add, null means add nothing * @throws ArithmeticException if the addition exceeds the capacity of the period */ void add(ReadableInterval interval); //----------------------------------------------------------------------- /** * Sets the number of years of the period. * * @param years the number of years * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setYears(int years); /** * Adds the specified years to the number of years in the period. * * @param years the number of years * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addYears(int years); //----------------------------------------------------------------------- /** * Sets the number of months of the period. * * @param months the number of months * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setMonths(int months); /** * Adds the specified months to the number of months in the period. * * @param months the number of months * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addMonths(int months); //----------------------------------------------------------------------- /** * Sets the number of weeks of the period. * * @param weeks the number of weeks * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setWeeks(int weeks); /** * Adds the specified weeks to the number of weeks in the period. * * @param weeks the number of weeks * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addWeeks(int weeks); //----------------------------------------------------------------------- /** * Sets the number of days of the period. * * @param days the number of days * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setDays(int days); /** * Adds the specified days to the number of days in the period. * * @param days the number of days * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addDays(int days); //----------------------------------------------------------------------- /** * Sets the number of hours of the period. * * @param hours the number of hours * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setHours(int hours); /** * Adds the specified hours to the number of hours in the period. * * @param hours the number of hours * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addHours(int hours); //----------------------------------------------------------------------- /** * Sets the number of minutes of the period. * * @param minutes the number of minutes * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setMinutes(int minutes); /** * Adds the specified minutes to the number of minutes in the period. * * @param minutes the number of minutes * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addMinutes(int minutes); //----------------------------------------------------------------------- /** * Sets the number of seconds of the period. * * @param seconds the number of seconds * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setSeconds(int seconds); /** * Adds the specified seconds to the number of seconds in the period. * * @param seconds the number of seconds * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addSeconds(int seconds); //----------------------------------------------------------------------- /** * Sets the number of millis of the period. * * @param millis the number of millis * @throws IllegalArgumentException if field is not supported and the value is non-zero */ void setMillis(int millis); /** * Adds the specified millis to the number of millis in the period. * * @param millis the number of millis * @throws IllegalArgumentException if field is not supported and the value is non-zero * @throws ArithmeticException if the addition exceeds the capacity of the period */ void addMillis(int millis); } joda-time-2.3/src/main/java/org/joda/time/DateMidnight.java0000644000175000017500000016324712200501234023063 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Locale; import org.joda.convert.FromString; import org.joda.time.base.BaseDateTime; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * DateMidnight defines a date where the time component is fixed at midnight. * The class uses a time zone, thus midnight is local unless a UTC time zone is used. *

* It is important to emphasise that this class represents the time of midnight on * any given day. * Note that midnight is defined as 00:00, which is at the very start of a day. *

* This class does not represent a day, but the millisecond instant at midnight. * If you need a class that represents the whole day, then an {@link Interval} or * a {@link LocalDate} may be more suitable. *

* This class uses a Chronology internally. The Chronology determines how the * millisecond instant value is converted into the date time fields. * The default Chronology is ISOChronology which is the agreed * international standard and compatable with the modern Gregorian calendar. * *

Each individual field can be queried in two ways: *

    *
  • getDayOfMonth() *
  • dayOfMonth().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value *
  • text value *
  • short text value *
  • maximum/minimum values *
  • add/subtract *
  • set *
  • rounding *
* *

* DateMidnight is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @since 1.0 * @deprecated The time of midnight does not exist in some time zones * where the daylight saving time forward shift skips the midnight hour. * Use {@link LocalDate} to represent a date without a time zone. * Or use {@link DateTime} to represent a full date and time, perhaps * using {@link DateTime#withTimeAtStartOfDay()} to get an instant at the * start of a day. */ @Deprecated public final class DateMidnight extends BaseDateTime implements ReadableDateTime, Serializable { /** Serialization lock */ private static final long serialVersionUID = 156371964018738L; //----------------------------------------------------------------------- /** * Obtains a {@code DateMidnight} set to the current system millisecond time * using ISOChronology in the default time zone. * The constructed object will have a local time of midnight. * * @return the current date, not null * @since 2.0 */ public static DateMidnight now() { return new DateMidnight(); } /** * Obtains a {@code DateMidnight} set to the current system millisecond time * using ISOChronology in the specified time zone. * The constructed object will have a local time of midnight. * * @param zone the time zone, not null * @return the current date, not null * @since 2.0 */ public static DateMidnight now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new DateMidnight(zone); } /** * Obtains a {@code DateMidnight} set to the current system millisecond time * using the specified chronology. * The constructed object will have a local time of midnight. * * @param chronology the chronology, not null * @return the current date, not null * @since 2.0 */ public static DateMidnight now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new DateMidnight(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code DateMidnight} from the specified string. *

* This uses {@link ISODateTimeFormat#dateTimeParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static DateMidnight parse(String str) { return parse(str, ISODateTimeFormat.dateTimeParser().withOffsetParsed()); } /** * Parses a {@code DateMidnight} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static DateMidnight parse(String str, DateTimeFormatter formatter) { return formatter.parseDateTime(str).toDateMidnight(); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the default time zone. * The constructed object will have a local time of midnight. * * @see #now() */ public DateMidnight() { super(); } /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the specified time zone. * The constructed object will have a local time of midnight. *

* If the specified time zone is null, the default zone is used. * * @param zone the time zone, null means default zone * @see #now(DateTimeZone) */ public DateMidnight(DateTimeZone zone) { super(zone); } /** * Constructs an instance set to the current system millisecond time * using the specified chronology. * The constructed object will have a local time of midnight. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param chronology the chronology, null means ISOChronology in default zone * @see #now(Chronology) */ public DateMidnight(Chronology chronology) { super(chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the default time zone. * The constructed object will have a local time of midnight. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public DateMidnight(long instant) { super(instant); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the specified time zone. * The constructed object will have a local time of midnight. *

* If the specified time zone is null, the default zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public DateMidnight(long instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using the specified chronology. * The constructed object will have a local time of midnight. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public DateMidnight(long instant, Chronology chronology) { super(instant, chronology); } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime. * The constructed object will have a local time of midnight. *

* If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used. Otherwise, ISO default is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()}. * * @param instant the datetime object, null means now * @throws IllegalArgumentException if the instant is invalid */ public DateMidnight(Object instant) { super(instant, (Chronology) null); } /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. * The constructed object will have a local time of midnight. *

* If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used, but with the time zone adjusted. * Otherwise, ISO is used in the specified time zone. * If the specified time zone is null, the default zone is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()}. * * @param instant the datetime object, null means now * @param zone the time zone, null means default time zone * @throws IllegalArgumentException if the instant is invalid */ public DateMidnight(Object instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. * The constructed object will have a local time of midnight. *

* If the chronology is null, ISO in the default time zone is used. * Any chronology implied by the object (such as GregorianCalendar does) * is ignored. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()}. * * @param instant the datetime object, null means now * @param chronology the chronology, null means ISOChronology in default zone * @throws IllegalArgumentException if the instant is invalid */ public DateMidnight(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology)); } //----------------------------------------------------------------------- /** * Constructs an instance from datetime field values * using ISOChronology in the default time zone. * The constructed object will have a local time of midnight. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 */ public DateMidnight(int year, int monthOfYear, int dayOfMonth) { super(year, monthOfYear, dayOfMonth, 0, 0, 0, 0); } /** * Constructs an instance from datetime field values * using ISOChronology in the specified time zone. * The constructed object will have a local time of midnight. *

* If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param zone the time zone, null means default time zone */ public DateMidnight(int year, int monthOfYear, int dayOfMonth, DateTimeZone zone) { super(year, monthOfYear, dayOfMonth, 0, 0, 0, 0, zone); } /** * Constructs an instance from datetime field values * using the specified chronology. * The constructed object will have a local time of midnight. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param year the year, valid values defined by the chronology * @param monthOfYear the month of the year, valid values defined by the chronology * @param dayOfMonth the day of the month, valid values defined by the chronology * @param chronology the chronology, null means ISOChronology in default zone */ public DateMidnight(int year, int monthOfYear, int dayOfMonth, Chronology chronology) { super(year, monthOfYear, dayOfMonth, 0, 0, 0, 0, chronology); } /** * Rounds the specified instant to midnight. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @param chronology the chronology to use, not null * @return the updated instant, rounded to midnight */ protected long checkInstant(long instant, Chronology chronology) { return chronology.dayOfMonth().roundFloor(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this date with a different millisecond instant. * The returned object will have a local time of midnight. *

* Only the millis will change, the chronology and time zone are kept. * The returned object will be either be a new instance or this. * * @param newMillis the new millis, from 1970-01-01T00:00:00Z * @return a copy of this instant with different millis */ public DateMidnight withMillis(long newMillis) { Chronology chrono = getChronology(); newMillis = checkInstant(newMillis, chrono); return (newMillis == getMillis() ? this : new DateMidnight(newMillis, chrono)); } /** * Returns a copy of this date with a different chronology, potentially * changing the day in unexpected ways. *

* This method creates a new DateMidnight using the midnight millisecond value * and the new chronology. If the same or similar chronology is specified, but * with a different time zone, the day may change. This occurs because the new * DateMidnight rounds down the millisecond value to get to midnight, and the * time zone change may result in a rounding down to a different day. *

* For example, changing time zone from London (+00:00) to Paris (+01:00) will * retain the same day, but changing from Paris to London will change the day. * (When its midnight in London its the same day in Paris, but when its midnight * in Paris its still the previous day in London) *

* To avoid these unusual effects, use {@link #withZoneRetainFields(DateTimeZone)} * to change time zones. * * @param newChronology the new chronology * @return a copy of this instant with a different chronology */ public DateMidnight withChronology(Chronology newChronology) { return (newChronology == getChronology() ? this : new DateMidnight(getMillis(), newChronology)); } /** * Returns a copy of this date with a different time zone, preserving the day * The returned object will have a local time of midnight in the new zone on * the same day as the original instant. * * @param newZone the new time zone, null means default * @return a copy of this instant with a different time zone */ public DateMidnight withZoneRetainFields(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); if (newZone == originalZone) { return this; } long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); return new DateMidnight(millis, getChronology().withZone(newZone)); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the partial set of fields replacing those * from this instance. *

* For example, if the partial is a LocalDate then the date fields * would be changed in the returned instance. * If the partial is null, then this is returned. * * @param partial the partial set of fields to apply to this datetime, null ignored * @return a copy of this datetime with a different set of fields * @throws IllegalArgumentException if any value is invalid */ public DateMidnight withFields(ReadablePartial partial) { if (partial == null) { return this; } return withMillis(getChronology().set(partial, getMillis())); } /** * Returns a copy of this date with the specified field set to a new value. *

* For example, if the field type is dayOfMonth then the day of month * field would be changed in the returned instance. * If the field type is null, then this is returned. *

* These three lines are equivalent: *

     * DateTime updated = dt.withField(DateTimeFieldType.dayOfMonth(), 6);
     * DateTime updated = dt.dayOfMonth().setCopy(6);
     * DateTime updated = dt.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this datetime with the field set * @throws IllegalArgumentException if the value is null or invalid */ public DateMidnight withField(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } long instant = fieldType.getField(getChronology()).set(getMillis(), value); return withMillis(instant); } /** * Returns a copy of this date with the value of the specified field increased. *

* If the addition is zero or the field is null, then this is returned. *

* These three lines are equivalent: *

     * DateMidnight added = dt.withFieldAdded(DateTimeFieldType.year(), 6);
     * DateMidnight added = dt.plusYears(6);
     * DateMidnight added = dt.year().addToCopy(6);
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this datetime with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight withFieldAdded(DurationFieldType fieldType, int amount) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (amount == 0) { return this; } long instant = fieldType.getField(getChronology()).add(getMillis(), amount); return withMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified duration added. *

* If the addition is zero, then this is returned. * * @param durationToAdd the duration to add to this one * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight withDurationAdded(long durationToAdd, int scalar) { if (durationToAdd == 0 || scalar == 0) { return this; } long instant = getChronology().add(getMillis(), durationToAdd, scalar); return withMillis(instant); } /** * Returns a copy of this date with the specified duration added. *

* If the addition is zero, then this is returned. * * @param durationToAdd the duration to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight withDurationAdded(ReadableDuration durationToAdd, int scalar) { if (durationToAdd == null || scalar == 0) { return this; } return withDurationAdded(durationToAdd.getMillis(), scalar); } /** * Returns a copy of this date with the specified period added. *

* If the addition is zero, then this is returned. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusYears(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the period added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getChronology().add(period, getMillis(), scalar); return withMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified duration added. *

* If the amount is zero, then this is returned. * * @param duration the duration, in millis, to add to this one * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight plus(long duration) { return withDurationAdded(duration, 1); } /** * Returns a copy of this date with the specified duration added. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to add to this one, null means zero * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight plus(ReadableDuration duration) { return withDurationAdded(duration, 1); } /** * Returns a copy of this date with the specified period added. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusYears(int)}. * * @param period the duration to add to this one, null means zero * @return a copy of this datetime with the period added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this date plus the specified number of years. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateMidnight added = dt.plusYears(6);
     * DateMidnight added = dt.plus(Period.years(6));
     * DateMidnight added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * 
* * @param years the amount of years to add, may be negative * @return the new datetime plus the increased years * @since 1.1 */ public DateMidnight plusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().add(getMillis(), years); return withMillis(instant); } /** * Returns a copy of this date plus the specified number of months. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateMidnight added = dt.plusMonths(6);
     * DateMidnight added = dt.plus(Period.months(6));
     * DateMidnight added = dt.withFieldAdded(DurationFieldType.months(), 6);
     * 
* * @param months the amount of months to add, may be negative * @return the new datetime plus the increased months * @since 1.1 */ public DateMidnight plusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().add(getMillis(), months); return withMillis(instant); } /** * Returns a copy of this date plus the specified number of weeks. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateMidnight added = dt.plusWeeks(6);
     * DateMidnight added = dt.plus(Period.weeks(6));
     * DateMidnight added = dt.withFieldAdded(DurationFieldType.weeks(), 6);
     * 
* * @param weeks the amount of weeks to add, may be negative * @return the new datetime plus the increased weeks * @since 1.1 */ public DateMidnight plusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().add(getMillis(), weeks); return withMillis(instant); } /** * Returns a copy of this date plus the specified number of days. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateMidnight added = dt.plusDays(6);
     * DateMidnight added = dt.plus(Period.days(6));
     * DateMidnight added = dt.withFieldAdded(DurationFieldType.days(), 6);
     * 
* * @param days the amount of days to add, may be negative * @return the new datetime plus the increased days * @since 1.1 */ public DateMidnight plusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().add(getMillis(), days); return withMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified duration taken away. *

* If the amount is zero or null, then this is returned. * * @param duration the duration, in millis, to reduce this instant by * @return a copy of this datetime with the duration taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight minus(long duration) { return withDurationAdded(duration, -1); } /** * Returns a copy of this date with the specified duration taken away. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to reduce this instant by * @return a copy of this datetime with the duration taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight minus(ReadableDuration duration) { return withDurationAdded(duration, -1); } /** * Returns a copy of this date with the specified period taken away. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusYears(int)}. * * @param period the period to reduce this instant by * @return a copy of this datetime with the period taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateMidnight minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this date minus the specified number of years. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusYears(6);
     * DateTime subtracted = dt.minus(Period.years(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.years(), -6);
     * 
* * @param years the amount of years to subtract, may be negative * @return the new datetime minus the increased years * @since 1.1 */ public DateMidnight minusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().subtract(getMillis(), years); return withMillis(instant); } /** * Returns a copy of this date minus the specified number of months. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateMidnight subtracted = dt.minusMonths(6);
     * DateMidnight subtracted = dt.minus(Period.months(6));
     * DateMidnight subtracted = dt.withFieldAdded(DurationFieldType.months(), -6);
     * 
* * @param months the amount of months to subtract, may be negative * @return the new datetime minus the increased months * @since 1.1 */ public DateMidnight minusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().subtract(getMillis(), months); return withMillis(instant); } /** * Returns a copy of this date minus the specified number of weeks. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateMidnight subtracted = dt.minusWeeks(6);
     * DateMidnight subtracted = dt.minus(Period.weeks(6));
     * DateMidnight subtracted = dt.withFieldAdded(DurationFieldType.weeks(), -6);
     * 
* * @param weeks the amount of weeks to subtract, may be negative * @return the new datetime minus the increased weeks * @since 1.1 */ public DateMidnight minusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().subtract(getMillis(), weeks); return withMillis(instant); } /** * Returns a copy of this date minus the specified number of days. *

* This datetime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * DateMidnight subtracted = dt.minusDays(6);
     * DateMidnight subtracted = dt.minus(Period.days(6));
     * DateMidnight subtracted = dt.withFieldAdded(DurationFieldType.days(), -6);
     * 
* * @param days the amount of days to subtract, may be negative * @return the new datetime minus the increased days * @since 1.1 */ public DateMidnight minusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().subtract(getMillis(), days); return withMillis(instant); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains many useful methods. * * @param type the field type to get the chronology for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType type) { if (type == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } DateTimeField field = type.getField(getChronology()); if (field.isSupported() == false) { throw new IllegalArgumentException("Field '" + type + "' is not supported"); } return new Property(this, field); } //----------------------------------------------------------------------- /** * Converts this object to a YearMonthDay using the * same date and chronology. * * @return a YearMonthDay using the same millis and chronology * @deprecated Use LocalDate instead of YearMonthDay */ @Deprecated public YearMonthDay toYearMonthDay() { return new YearMonthDay(getMillis(), getChronology()); } /** * Converts this object to a LocalDate with the * same date and chronology. * * @return a LocalDate with the same date and chronology * @since 1.3 */ public LocalDate toLocalDate() { return new LocalDate(getMillis(), getChronology()); } /** * Converts this object to an Interval encompassing * the whole of this day. *

* The interval starts at midnight 00:00 and ends at 00:00 the following day, * (which is not included in the interval, as intervals are half-open). * * @return an interval over the day */ public Interval toInterval() { Chronology chrono = getChronology(); long start = getMillis(); long end = DurationFieldType.days().getField(chrono).add(start, 1); return new Interval(start, end, chrono); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the era field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * era changed. * * @param era the era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withEra(int era) { return withMillis(getChronology().era().set(getMillis(), era)); } /** * Returns a copy of this date with the century of era field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * century of era changed. * * @param centuryOfEra the centurey of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withCenturyOfEra(int centuryOfEra) { return withMillis(getChronology().centuryOfEra().set(getMillis(), centuryOfEra)); } /** * Returns a copy of this date with the year of era field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of era changed. * * @param yearOfEra the year of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withYearOfEra(int yearOfEra) { return withMillis(getChronology().yearOfEra().set(getMillis(), yearOfEra)); } /** * Returns a copy of this date with the year of century field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of century changed. * * @param yearOfCentury the year of century to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withYearOfCentury(int yearOfCentury) { return withMillis(getChronology().yearOfCentury().set(getMillis(), yearOfCentury)); } /** * Returns a copy of this date with the year field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year changed. * * @param year the year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withYear(int year) { return withMillis(getChronology().year().set(getMillis(), year)); } /** * Returns a copy of this date with the weekyear field updated. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * weekyear changed. * * @param weekyear the weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withWeekyear(int weekyear) { return withMillis(getChronology().weekyear().set(getMillis(), weekyear)); } /** * Returns a copy of this date with the month of year field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withMonthOfYear(int monthOfYear) { return withMillis(getChronology().monthOfYear().set(getMillis(), monthOfYear)); } /** * Returns a copy of this date with the week of weekyear field updated. *

* This field is associated with the "weekyear" via {@link #withWeekyear(int)}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * week of weekyear changed. * * @param weekOfWeekyear the week of weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withWeekOfWeekyear(int weekOfWeekyear) { return withMillis(getChronology().weekOfWeekyear().set(getMillis(), weekOfWeekyear)); } /** * Returns a copy of this date with the day of year field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of year changed. * * @param dayOfYear the day of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withDayOfYear(int dayOfYear) { return withMillis(getChronology().dayOfYear().set(getMillis(), dayOfYear)); } /** * Returns a copy of this date with the day of month field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of month changed. * * @param dayOfMonth the day of month to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withDayOfMonth(int dayOfMonth) { return withMillis(getChronology().dayOfMonth().set(getMillis(), dayOfMonth)); } /** * Returns a copy of this date with the day of week field updated. *

* DateMidnight is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of week changed. * * @param dayOfWeek the day of week to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateMidnight withDayOfWeek(int dayOfWeek) { return withMillis(getChronology().dayOfWeek().set(getMillis(), dayOfWeek)); } // Date properties //----------------------------------------------------------------------- /** * Get the era property which provides access to advanced functionality. * * @return the era property */ public Property era() { return new Property(this, getChronology().era()); } /** * Get the century of era property which provides access to advanced functionality. * * @return the year of era property */ public Property centuryOfEra() { return new Property(this, getChronology().centuryOfEra()); } /** * Get the year of century property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfCentury() { return new Property(this, getChronology().yearOfCentury()); } /** * Get the year of era property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfEra() { return new Property(this, getChronology().yearOfEra()); } /** * Get the year property which provides access to advanced functionality. * * @return the year property */ public Property year() { return new Property(this, getChronology().year()); } /** * Get the year of a week based year property which provides access to advanced functionality. * * @return the year of a week based year property */ public Property weekyear() { return new Property(this, getChronology().weekyear()); } /** * Get the month of year property which provides access to advanced functionality. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, getChronology().monthOfYear()); } /** * Get the week of a week based year property which provides access to advanced functionality. * * @return the week of a week based year property */ public Property weekOfWeekyear() { return new Property(this, getChronology().weekOfWeekyear()); } /** * Get the day of year property which provides access to advanced functionality. * * @return the day of year property */ public Property dayOfYear() { return new Property(this, getChronology().dayOfYear()); } /** * Get the day of month property which provides access to advanced functionality. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, getChronology().dayOfMonth()); } /** * Get the day of week property which provides access to advanced functionality. * * @return the day of week property */ public Property dayOfWeek() { return new Property(this, getChronology().dayOfWeek()); } //----------------------------------------------------------------------- /** * DateMidnight.Property binds a DateMidnight to a DateTimeField allowing powerful * datetime functionality to be easily accessed. *

* The simplest use of this class is as an alternative get method, here used to * get the year '1972' (as an int) and the month 'December' (as a String). *

     * DateMidnight dt = new DateMidnight(1972, 12, 3);
     * int year = dt.year().get();
     * String monthStr = dt.monthOfYear().getAsText();
     * 
*

* Methods are also provided that allow date modification. These return new instances * of DateMidnight - they do not modify the original. The example below yields two * independent immutable date objects 20 years apart. *

     * DateMidnight dt = new DateMidnight(1972, 12, 3);
     * DateMidnight dt20 = dt.year().addToCopy(20);
     * 
* Serious modification of dates (ie. more than just changing one or two fields) * should use the {@link org.joda.time.MutableDateTime MutableDateTime} class. *

* DateMidnight.Property itself is thread-safe and immutable. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization lock */ private static final long serialVersionUID = 257629620L; /** The instant this property is working against */ private DateMidnight iInstant; /** The field this property is working against */ private DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(DateMidnight instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Writes the property in a safe serialization format. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(iInstant); oos.writeObject(iField.getType()); } /** * Reads the property from a safe serialization format. */ private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException { iInstant = (DateMidnight) oos.readObject(); DateTimeFieldType type = (DateTimeFieldType) oos.readObject(); iField = type.getField(iInstant.getChronology()); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the milliseconds of the datetime that this property is linked to. * * @return the milliseconds */ protected long getMillis() { return iInstant.getMillis(); } /** * Gets the chronology of the datetime that this property is linked to. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { return iInstant.getChronology(); } /** * Gets the datetime being used. * * @return the datetime */ public DateMidnight getDateMidnight() { return iInstant; } //----------------------------------------------------------------------- /** * Adds to this field in a copy of this DateMidnight. *

* The DateMidnight attached to this property is unchanged by this call. * This operation is faster than converting a DateMidnight to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to add to the field in the copy * @return a copy of the DateMidnight with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateMidnight addToCopy(int value) { return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); } /** * Adds to this field in a copy of this DateMidnight. *

* The DateMidnight attached to this property is unchanged by this call. * This operation is faster than converting a DateMidnight to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to add to the field in the copy * @return a copy of the DateMidnight with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateMidnight addToCopy(long value) { return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); } /** * Adds to this field, possibly wrapped, in a copy of this DateMidnight. * A wrapped operation only changes this field. * Thus 31st January addWrapField one day goes to the 1st January. *

* The DateMidnight attached to this property is unchanged by this call. * This operation is faster than converting a DateMidnight to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to add to the field in the copy * @return a copy of the DateMidnight with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateMidnight addWrapFieldToCopy(int value) { return iInstant.withMillis(iField.addWrapField(iInstant.getMillis(), value)); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the DateMidnight. *

* The DateMidnight attached to this property is unchanged by this call. * This operation is faster than converting a DateMidnight to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to set the field in the copy to * @return a copy of the DateMidnight with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateMidnight setCopy(int value) { return iInstant.withMillis(iField.set(iInstant.getMillis(), value)); } /** * Sets this field in a copy of the DateMidnight to a parsed text value. *

* The DateMidnight attached to this property is unchanged by this call. * This operation is faster than converting a DateMidnight to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the DateMidnight with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public DateMidnight setCopy(String text, Locale locale) { return iInstant.withMillis(iField.set(iInstant.getMillis(), text, locale)); } /** * Sets this field in a copy of the DateMidnight to a parsed text value. *

* The DateMidnight attached to this property is unchanged by this call. * This operation is faster than converting a DateMidnight to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param text the text value to set * @return a copy of the DateMidnight with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public DateMidnight setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new DateMidnight with this field set to the maximum value * for this field. *

* This operation is useful for obtaining a DateTime on the last day * of the month, as month lengths vary. *

         * DateMidnight lastDayOfMonth = dt.dayOfMonth().withMaximumValue();
         * 
*

* The DateMidnight attached to this property is unchanged by this call. * * @return a copy of the DateMidnight with this field set to its maximum * @since 1.2 */ public DateMidnight withMaximumValue() { return setCopy(getMaximumValue()); } /** * Returns a new DateMidnight with this field set to the minimum value * for this field. *

* The DateMidnight attached to this property is unchanged by this call. * * @return a copy of the DateMidnight with this field set to its minimum * @since 1.2 */ public DateMidnight withMinimumValue() { return setCopy(getMinimumValue()); } //----------------------------------------------------------------------- /** * Rounds to the lowest whole unit of this field on a copy of this DateMidnight. * * @return a copy of the DateMidnight with the field value changed */ public DateMidnight roundFloorCopy() { return iInstant.withMillis(iField.roundFloor(iInstant.getMillis())); } /** * Rounds to the highest whole unit of this field on a copy of this DateMidnight. * * @return a copy of the DateMidnight with the field value changed */ public DateMidnight roundCeilingCopy() { return iInstant.withMillis(iField.roundCeiling(iInstant.getMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this DateMidnight, * favoring the floor if halfway. * * @return a copy of the DateMidnight with the field value changed */ public DateMidnight roundHalfFloorCopy() { return iInstant.withMillis(iField.roundHalfFloor(iInstant.getMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this DateMidnight, * favoring the ceiling if halfway. * * @return a copy of the DateMidnight with the field value changed */ public DateMidnight roundHalfCeilingCopy() { return iInstant.withMillis(iField.roundHalfCeiling(iInstant.getMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this DateMidnight. * If halfway, the ceiling is favored over the floor only if it makes this field's value even. * * @return a copy of the DateMidnight with the field value changed */ public DateMidnight roundHalfEvenCopy() { return iInstant.withMillis(iField.roundHalfEven(iInstant.getMillis())); } } } joda-time-2.3/src/main/java/org/joda/time/Seconds.java0000644000175000017500000004515511564251363022136 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseSingleFieldPeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period representing a number of seconds. *

* Seconds is an immutable period that can only store seconds. * It does not store years, months or hours for example. As such it is a * type-safe way of representing a number of seconds in an application. *

* The number of seconds is set in the constructor, and may be queried using * getSeconds(). Basic mathematical operations are provided - * plus(), minus(), multipliedBy() and * dividedBy(). *

* Seconds is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.4 */ public final class Seconds extends BaseSingleFieldPeriod { /** Constant representing zero seconds. */ public static final Seconds ZERO = new Seconds(0); /** Constant representing one second. */ public static final Seconds ONE = new Seconds(1); /** Constant representing two seconds. */ public static final Seconds TWO = new Seconds(2); /** Constant representing three seconds. */ public static final Seconds THREE = new Seconds(3); /** Constant representing the maximum number of seconds that can be stored in this object. */ public static final Seconds MAX_VALUE = new Seconds(Integer.MAX_VALUE); /** Constant representing the minimum number of seconds that can be stored in this object. */ public static final Seconds MIN_VALUE = new Seconds(Integer.MIN_VALUE); /** The paser to use for this class. */ private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.seconds()); /** Serialization version. */ private static final long serialVersionUID = 87525275727380862L; //----------------------------------------------------------------------- /** * Obtains an instance of Seconds that may be cached. * Seconds is immutable, so instances can be cached and shared. * This factory method provides access to shared instances. * * @param seconds the number of seconds to obtain an instance for * @return the instance of Seconds */ public static Seconds seconds(int seconds) { switch (seconds) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Seconds(seconds); } } //----------------------------------------------------------------------- /** * Creates a Seconds representing the number of whole seconds * between the two specified datetimes. * * @param start the start instant, must not be null * @param end the end instant, must not be null * @return the period in seconds * @throws IllegalArgumentException if the instants are null or invalid */ public static Seconds secondsBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.seconds()); return Seconds.seconds(amount); } /** * Creates a Seconds representing the number of whole seconds * between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalTime objects. * * @param start the start partial date, must not be null * @param end the end partial date, must not be null * @return the period in seconds * @throws IllegalArgumentException if the partials are null or invalid */ public static Seconds secondsBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalTime && end instanceof LocalTime) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int seconds = chrono.seconds().getDifference( ((LocalTime) end).getLocalMillis(), ((LocalTime) start).getLocalMillis()); return Seconds.seconds(seconds); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Seconds.seconds(amount); } /** * Creates a Seconds representing the number of whole seconds * in the specified interval. * * @param interval the interval to extract seconds from, null returns zero * @return the period in seconds * @throws IllegalArgumentException if the partials are null or invalid */ public static Seconds secondsIn(ReadableInterval interval) { if (interval == null) { return Seconds.ZERO; } int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.seconds()); return Seconds.seconds(amount); } /** * Creates a new Seconds representing the number of complete * standard length seconds in the specified period. *

* This factory method converts all fields from the period to hours using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. *

    *
  • One week consists of 7 seconds. *
  • One day consists of 24 hours. *
  • One hour consists of 60 minutes. *
  • One minute consists of 60 seconds. *
  • One second consists of 1000 milliseconds. *
* Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of hours from, null returns zero * @return the period in seconds * @throws IllegalArgumentException if the period contains imprecise duration values */ public static Seconds standardSecondsIn(ReadablePeriod period) { int amount = BaseSingleFieldPeriod.standardPeriodIn(period, DateTimeConstants.MILLIS_PER_SECOND); return Seconds.seconds(amount); } /** * Creates a new Seconds by parsing a string in the ISO8601 format 'PTnS'. *

* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the * seconds component may be non-zero. If any other component is non-zero, an exception * will be thrown. * * @param periodStr the period string, null returns zero * @return the period in seconds * @throws IllegalArgumentException if the string format is invalid */ @FromString public static Seconds parseSeconds(String periodStr) { if (periodStr == null) { return Seconds.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Seconds.seconds(p.getSeconds()); } //----------------------------------------------------------------------- /** * Creates a new instance representing a number of seconds. * You should consider using the factory method {@link #seconds(int)} * instead of the constructor. * * @param seconds the number of seconds to represent */ private Seconds(int seconds) { super(seconds); } /** * Resolves singletons. * * @return the singleton instance */ private Object readResolve() { return Seconds.seconds(getValue()); } //----------------------------------------------------------------------- /** * Gets the duration field type, which is seconds. * * @return the period type */ public DurationFieldType getFieldType() { return DurationFieldType.seconds(); } /** * Gets the period type, which is seconds. * * @return the period type */ public PeriodType getPeriodType() { return PeriodType.seconds(); } //----------------------------------------------------------------------- /** * Converts this period in seconds to a period in weeks assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are 7 days * long, all days are 24 hours long, all hours are 60 minutes long and * all minutes are 60 seconds long. * This is not true when daylight savings time is considered, and may also * not be true for some unusual chronologies. However, it is included as it * is a useful operation for many applications and business rules. * * @return a period representing the number of whole weeks for this number of seconds */ public Weeks toStandardWeeks() { return Weeks.weeks(getValue() / DateTimeConstants.SECONDS_PER_WEEK); } /** * Converts this period in seconds to a period in days assuming a * 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all days are 24 hours * long, all hours are 60 minutes long and all minutes are 60 seconds long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of days for this number of seconds */ public Days toStandardDays() { return Days.days(getValue() / DateTimeConstants.SECONDS_PER_DAY); } /** * Converts this period in seconds to a period in hours assuming a * 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all hours are * 60 minutes long and all minutes are 60 seconds long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of hours for this number of seconds */ public Hours toStandardHours() { return Hours.hours(getValue() / DateTimeConstants.SECONDS_PER_HOUR); } /** * Converts this period in seconds to a period in minutes assuming a * 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all minutes are * 60 seconds long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of minutes for this number of seconds */ public Minutes toStandardMinutes() { return Minutes.minutes(getValue() / DateTimeConstants.SECONDS_PER_MINUTE); } //----------------------------------------------------------------------- /** * Converts this period in seconds to a duration in milliseconds assuming a * 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert from a period to a duration. * However to achieve this it makes the assumption that all seconds are 24 hours * long, all hours are 60 minutes and all minutes are 60 seconds. * This is not true when daylight savings time is considered, and may also * not be true for some unusual chronologies. However, it is included as it * is a useful operation for many applications and business rules. * * @return a duration equivalent to this number of seconds */ public Duration toStandardDuration() { long seconds = getValue(); // assign to a long return new Duration(seconds * DateTimeConstants.MILLIS_PER_SECOND); } //----------------------------------------------------------------------- /** * Gets the number of seconds that this period represents. * * @return the number of seconds in the period */ public int getSeconds() { return getValue(); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of seconds added. *

* This instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to add, may be negative * @return the new period plus the specified number of seconds * @throws ArithmeticException if the result overflows an int */ public Seconds plus(int seconds) { if (seconds == 0) { return this; } return Seconds.seconds(FieldUtils.safeAdd(getValue(), seconds)); } /** * Returns a new instance with the specified number of seconds added. *

* This instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to add, may be negative, null means zero * @return the new period plus the specified number of seconds * @throws ArithmeticException if the result overflows an int */ public Seconds plus(Seconds seconds) { if (seconds == null) { return this; } return plus(seconds.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of seconds taken away. *

* This instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to take away, may be negative * @return the new period minus the specified number of seconds * @throws ArithmeticException if the result overflows an int */ public Seconds minus(int seconds) { return plus(FieldUtils.safeNegate(seconds)); } /** * Returns a new instance with the specified number of seconds taken away. *

* This instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to take away, may be negative, null means zero * @return the new period minus the specified number of seconds * @throws ArithmeticException if the result overflows an int */ public Seconds minus(Seconds seconds) { if (seconds == null) { return this; } return minus(seconds.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the seconds multiplied by the specified scalar. *

* This instance is immutable and unaffected by this method call. * * @param scalar the amount to multiply by, may be negative * @return the new period multiplied by the specified scalar * @throws ArithmeticException if the result overflows an int */ public Seconds multipliedBy(int scalar) { return Seconds.seconds(FieldUtils.safeMultiply(getValue(), scalar)); } /** * Returns a new instance with the seconds divided by the specified divisor. * The calculation uses integer division, thus 3 divided by 2 is 1. *

* This instance is immutable and unaffected by this method call. * * @param divisor the amount to divide by, may be negative * @return the new period divided by the specified divisor * @throws ArithmeticException if the divisor is zero */ public Seconds dividedBy(int divisor) { if (divisor == 1) { return this; } return Seconds.seconds(getValue() / divisor); } //----------------------------------------------------------------------- /** * Returns a new instance with the seconds value negated. * * @return the new period with a negated value * @throws ArithmeticException if the result overflows an int */ public Seconds negated() { return Seconds.seconds(FieldUtils.safeNegate(getValue())); } //----------------------------------------------------------------------- /** * Is this seconds instance greater than the specified number of seconds. * * @param other the other period, null means zero * @return true if this seconds instance is greater than the specified one */ public boolean isGreaterThan(Seconds other) { if (other == null) { return getValue() > 0; } return getValue() > other.getValue(); } /** * Is this seconds instance less than the specified number of seconds. * * @param other the other period, null means zero * @return true if this seconds instance is less than the specified one */ public boolean isLessThan(Seconds other) { if (other == null) { return getValue() < 0; } return getValue() < other.getValue(); } //----------------------------------------------------------------------- /** * Gets this instance as a String in the ISO8601 duration format. *

* For example, "PT4S" represents 4 seconds. * * @return the value as an ISO8601 string */ @ToString public String toString() { return "PT" + String.valueOf(getValue()) + "S"; } } joda-time-2.3/src/main/java/org/joda/time/MonthDay.java0000644000175000017500000011301211616003375022243 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BasePartial; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractPartialFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import org.joda.time.format.ISODateTimeFormat; /** * MonthDay is an immutable partial supporting the monthOfYear and dayOfMonth fields. *

* NOTE: This class only supports the two fields listed above. * It is impossible to query any other fields, such as dayOfWeek or centuryOfEra. *

* Calculations on MonthDay are performed using a {@link Chronology}. * This chronology is set to be in the UTC time zone for all calculations. *

* One use case for this class is to store a birthday without the year (to avoid * storing the age of the person). * This class can be used as the gMonthDay type in XML Schema. *

* Each individual field can be queried in two ways: *

    *
  • getMonthOfYear() *
  • monthOfYear().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value - monthOfYear().get() *
  • text value - monthOfYear().getAsText() *
  • short text value - monthOfYear().getAsShortText() *
  • maximum/minimum values - monthOfYear().getMaximumValue() *
  • add/subtract - monthOfYear().addToCopy() *
  • set - monthOfYear().setCopy() *
*

* MonthDay is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Chris Pheby * @since 2.0 */ public final class MonthDay extends BasePartial implements ReadablePartial, Serializable { /** Serialization version */ private static final long serialVersionUID = 2954560699050434609L; /** The singleton set of field types */ private static final DateTimeFieldType[] FIELD_TYPES = new DateTimeFieldType[] { DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth(), }; /** The singleton set of field types */ private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder() .appendOptional(ISODateTimeFormat.localDateParser().getParser()) .appendOptional(DateTimeFormat.forPattern("--MM-dd").getParser()).toFormatter(); /** The index of the monthOfYear field in the field array */ public static final int MONTH_OF_YEAR = 0; /** The index of the day field in the field array */ public static final int DAY_OF_MONTH = 1; //----------------------------------------------------------------------- /** * Obtains a {@code MonthDay} set to the current system millisecond time * using ISOChronology in the default time zone. * The resulting object does not use the zone. * * @return the current month-day, not null * @since 2.0 */ public static MonthDay now() { return new MonthDay(); } /** * Obtains a {@code MonthDay} set to the current system millisecond time * using ISOChronology in the specified time zone. * The resulting object does not use the zone. * * @param zone the time zone, not null * @return the current month-day, not null * @since 2.0 */ public static MonthDay now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new MonthDay(zone); } /** * Obtains a {@code MonthDay} set to the current system millisecond time * using the specified chronology. * The resulting object does not use the zone. * * @param chronology the chronology, not null * @return the current month-day, not null * @since 2.0 */ public static MonthDay now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new MonthDay(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code MonthDay} from the specified string. *

* This uses {@link ISODateTimeFormat#localDateParser()} or the format {@code --MM-dd}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static MonthDay parse(String str) { return parse(str, PARSER); } /** * Parses a {@code MonthDay} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static MonthDay parse(String str, DateTimeFormatter formatter) { LocalDate date = formatter.parseLocalDate(str); return new MonthDay(date.getMonthOfYear(), date.getDayOfMonth()); } //----------------------------------------------------------------------- /** * Constructs a MonthDay from a java.util.Calendar * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Calendar and assigned to the MonthDay. *

* This factory method ignores the type of the calendar and always * creates a MonthDay with ISO chronology. It is expected that you * will only pass in instances of GregorianCalendar however * this is not validated. * * @param calendar the Calendar to extract fields from * @return the created MonthDay, never null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the monthOfYear or dayOfMonth is invalid for the ISO chronology */ public static MonthDay fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } return new MonthDay(calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)); } /** * Constructs a MonthDay from a java.util.Date * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Date and assigned to the MonthDay. *

* This factory method always creates a MonthDay with ISO chronology. * * @param date the Date to extract fields from * @return the created MonthDay, never null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the monthOfYear or dayOfMonth is invalid for the ISO chronology */ @SuppressWarnings("deprecation") public static MonthDay fromDateFields(Date date) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } return new MonthDay(date.getMonth() + 1, date.getDate()); } //----------------------------------------------------------------------- /** * Constructs a MonthDay with the current monthOfYear, using ISOChronology in * the default zone to extract the fields. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @see #now() */ public MonthDay() { super(); } /** * Constructs a MonthDay with the current month-day, using ISOChronology in * the specified zone to extract the fields. *

* The constructor uses the specified time zone to obtain the current month-day. * Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @param zone the zone to use, null means default zone * @see #now(DateTimeZone) */ public MonthDay(DateTimeZone zone) { super(ISOChronology.getInstance(zone)); } /** * Constructs a MonthDay with the current month-day, using the specified chronology * and zone to extract the fields. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * * @param chronology the chronology, null means ISOChronology in the default zone * @see #now(Chronology) */ public MonthDay(Chronology chronology) { super(chronology); } /** * Constructs a MonthDay extracting the partial fields from the specified * milliseconds using the ISOChronology in the default zone. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public MonthDay(long instant) { super(instant); } /** * Constructs a MonthDay extracting the partial fields from the specified * milliseconds using the chronology provided. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in the default zone */ public MonthDay(long instant, Chronology chronology) { super(instant, chronology); } /** * Constructs a MonthDay from an Object that represents some form of time. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateParser()}. *

* The chronology used will be derived from the object, defaulting to ISO. * * @param instant the date-time object, null means now * @throws IllegalArgumentException if the instant is invalid */ public MonthDay(Object instant) { super(instant, null, ISODateTimeFormat.localDateParser()); } /** * Constructs a MonthDay from an Object that represents some form of time, * using the specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateParser()}. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * The specified chronology overrides that of the object. * * @param instant the date-time object, null means now * @param chronology the chronology, null means ISO default * @throws IllegalArgumentException if the instant is invalid */ public MonthDay(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology), ISODateTimeFormat.localDateParser()); } /** * Constructs a MonthDay with specified year and month * using ISOChronology. *

* The constructor uses the no time zone initialising the fields as provided. * Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @param monthOfYear the month of the year * @param dayOfMonth the day of the month */ public MonthDay(int monthOfYear, int dayOfMonth) { this(monthOfYear, dayOfMonth, null); } /** * Constructs an instance set to the specified monthOfYear and dayOfMonth * using the specified chronology, whose zone is ignored. *

* If the chronology is null, ISOChronology is used. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param chronology the chronology, null means ISOChronology in the default zone */ public MonthDay(int monthOfYear, int dayOfMonth, Chronology chronology) { super(new int[] {monthOfYear, dayOfMonth}, chronology); } /** * Constructs a MonthDay with chronology from this instance and new values. * * @param partial the partial to base this new instance on * @param values the new set of values */ MonthDay(MonthDay partial, int[] values) { super(partial, values); } /** * Constructs a MonthDay with values from this instance and a new chronology. * * @param partial the partial to base this new instance on * @param chrono the new chronology */ MonthDay(MonthDay partial, Chronology chrono) { super(partial, chrono); } /** * Handle broken serialization from other tools. * @return the resolved object, not null */ private Object readResolve() { if (DateTimeZone.UTC.equals(getChronology().getZone()) == false) { return new MonthDay(this, getChronology().withUTC()); } return this; } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial, which is two. * The supported fields are MonthOfYear and DayOfMonth. * Note that only these fields may be queried. * * @return the field count, two */ public int size() { return 2; } /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field, never null */ protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case MONTH_OF_YEAR: return chrono.monthOfYear(); case DAY_OF_MONTH: return chrono.dayOfMonth(); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index, never null * @throws IndexOutOfBoundsException if the index is invalid */ public DateTimeFieldType getFieldType(int index) { return FIELD_TYPES[index]; } /** * Gets an array of the field type of each of the fields that this partial supports. *

* The fields are returned largest to smallest, Month, Day. * * @return the array of field types (cloned), largest to smallest, never null */ public DateTimeFieldType[] getFieldTypes() { return (DateTimeFieldType[]) FIELD_TYPES.clone(); } //----------------------------------------------------------------------- /** * Returns a copy of this month-day with the specified chronology. * This instance is immutable and unaffected by this method call. *

* This method retains the values of the fields, thus the result will * typically refer to a different instant. *

* The time zone of the specified chronology is ignored, as MonthDay * operates without a time zone. * * @param newChronology the new chronology, null means ISO * @return a copy of this month-day with a different chronology, never null * @throws IllegalArgumentException if the values are invalid for the new chronology */ public MonthDay withChronologyRetainFields(Chronology newChronology) { newChronology = DateTimeUtils.getChronology(newChronology); newChronology = newChronology.withUTC(); if (newChronology == getChronology()) { return this; } else { MonthDay newMonthDay = new MonthDay(this, newChronology); newChronology.validate(newMonthDay, getValues()); return newMonthDay; } } /** * Returns a copy of this month-day with the specified field set to a new value. *

* For example, if the field type is dayOfMonth then the day * would be changed in the returned instance. *

* These three lines are equivalent: *

     * MonthDay updated = md.withField(DateTimeFieldType.dayOfMonth(), 6);
     * MonthDay updated = md.dayOfMonth().setCopy(6);
     * MonthDay updated = md.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this instance with the field set, never null * @throws IllegalArgumentException if the value is null or invalid */ public MonthDay withField(DateTimeFieldType fieldType, int value) { int index = indexOfSupported(fieldType); if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new MonthDay(this, newValues); } /** * Returns a copy of this month-day with the value of the specified field increased. *

* If the addition is zero, then this is returned. *

* These three lines are equivalent: *

     * MonthDay added = md.withFieldAdded(DurationFieldType.days(), 6);
     * MonthDay added = md.plusDays(6);
     * MonthDay added = md.dayOfMonth().addToCopy(6);
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this instance with the field updated, never null * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new date-time exceeds the capacity */ public MonthDay withFieldAdded(DurationFieldType fieldType, int amount) { int index = indexOfSupported(fieldType); if (amount == 0) { return this; } int[] newValues = getValues(); newValues = getField(index).add(this, index, newValues, amount); return new MonthDay(this, newValues); } /** * Returns a copy of this month-day with the specified period added. *

* If the addition is zero, then this is returned. * Fields in the period that aren't present in the partial are ignored. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusMonths(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this instance with the period added, never null * @throws ArithmeticException if the new date-time exceeds the capacity */ public MonthDay withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } int[] newValues = getValues(); for (int i = 0; i < period.size(); i++) { DurationFieldType fieldType = period.getFieldType(i); int index = indexOf(fieldType); if (index >= 0) { newValues = getField(index).add(this, index, newValues, FieldUtils.safeMultiply(period.getValue(i), scalar)); } } return new MonthDay(this, newValues); } //----------------------------------------------------------------------- /** * Returns a copy of this month-day with the specified period added. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusMonths(int)}. * * @param period the duration to add to this one, null means zero * @return a copy of this instance with the period added, never null * @throws ArithmeticException if the new month-day exceeds the capacity */ public MonthDay plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this month-day plus the specified number of months. *

* This month-day instance is immutable and unaffected by this method call. * The month will wrap at the end of the year from December to January. * The day will be adjusted to the last valid value if necessary. *

* The following three lines are identical in effect: *

     * MonthDay added = md.plusMonths(6);
     * MonthDay added = md.plus(Period.months(6));
     * MonthDay added = md.withFieldAdded(DurationFieldType.months(), 6);
     * 
* * @param months the amount of months to add, may be negative * @return the new month-day plus the increased months, never null */ public MonthDay plusMonths(int months) { return withFieldAdded(DurationFieldType.months(), months); } /** * Returns a copy of this month-day plus the specified number of days. *

* This month-day instance is immutable and unaffected by this method call. * The month will wrap at the end of the year from December to January. *

* The following three lines are identical in effect: *

     * MonthDay added = md.plusDays(6);
     * MonthDay added = md.plus(Period.days(6));
     * MonthDay added = md.withFieldAdded(DurationFieldType.days(), 6);
     * 
* * @param days the amount of days to add, may be negative * @return the new month-day plus the increased days, never null */ public MonthDay plusDays(int days) { return withFieldAdded(DurationFieldType.days(), days); } //----------------------------------------------------------------------- /** * Returns a copy of this month-day with the specified period taken away. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusMonths(int)}. * * @param period the period to reduce this instant by * @return a copy of this instance with the period taken away, never null * @throws ArithmeticException if the new month-day exceeds the capacity */ public MonthDay minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this month-day minus the specified number of months. *

* This MonthDay instance is immutable and unaffected by this method call. * The month will wrap at the end of the year from January to December. * The day will be adjusted to the last valid value if necessary. *

* The following three lines are identical in effect: *

     * MonthDay subtracted = md.minusMonths(6);
     * MonthDay subtracted = md.minus(Period.months(6));
     * MonthDay subtracted = md.withFieldAdded(DurationFieldType.months(), -6);
     * 
* * @param months the amount of months to subtract, may be negative * @return the new month-day minus the increased months, never null */ public MonthDay minusMonths(int months) { return withFieldAdded(DurationFieldType.months(), FieldUtils.safeNegate(months)); } /** * Returns a copy of this month-day minus the specified number of months. *

* This month-day instance is immutable and unaffected by this method call. * The month will wrap at the end of the year from January to December. *

* The following three lines are identical in effect: *

     * MonthDay subtracted = md.minusDays(6);
     * MonthDay subtracted = md.minus(Period.days(6));
     * MonthDay subtracted = md.withFieldAdded(DurationFieldType.days(), -6);
     * 
* * @param days the amount of days to subtract, may be negative * @return the new month-day minus the increased days, never null */ public MonthDay minusDays(int days) { return withFieldAdded(DurationFieldType.days(), FieldUtils.safeNegate(days)); } //----------------------------------------------------------------------- /** * Converts this object to a LocalDate with the same month-day and chronology. * * @param year the year to use, valid for chronology * @return a LocalDate with the same month-day and chronology, never null */ public LocalDate toLocalDate(int year) { return new LocalDate(year, getMonthOfYear(), getDayOfMonth(), getChronology()); } //----------------------------------------------------------------------- /** * Get the month of year field value. * * @return the month of year */ public int getMonthOfYear() { return getValue(MONTH_OF_YEAR); } /** * Get the day of month field value. * * @return the day of month */ public int getDayOfMonth() { return getValue(DAY_OF_MONTH); } //----------------------------------------------------------------------- /** * Returns a copy of this month-day with the month of year field updated. *

* MonthDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set, never null * @throws IllegalArgumentException if the value is invalid */ public MonthDay withMonthOfYear(int monthOfYear) { int[] newValues = getValues(); newValues = getChronology().monthOfYear().set(this, MONTH_OF_YEAR, newValues, monthOfYear); return new MonthDay(this, newValues); } /** * Returns a copy of this month-day with the day of month field updated. *

* MonthDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of month changed. * * @param dayOfMonth the day of month to set * @return a copy of this object with the field set, never null * @throws IllegalArgumentException if the value is invalid */ public MonthDay withDayOfMonth(int dayOfMonth) { int[] newValues = getValues(); newValues = getChronology().dayOfMonth().set(this, DAY_OF_MONTH, newValues, dayOfMonth); return new MonthDay(this, newValues); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains * many useful methods. * * @param type the field type to get the property for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType type) { return new Property(this, indexOfSupported(type)); } //----------------------------------------------------------------------- /** * Get the month of year field property which provides access to advanced functionality. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, MONTH_OF_YEAR); } /** * Get the day of month field property which provides access to advanced functionality. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, DAY_OF_MONTH); } //----------------------------------------------------------------------- /** * Output the month-day in ISO8601 format (--MM-dd). * * @return ISO8601 time formatted string. */ @ToString public String toString() { List fields = new ArrayList(); fields.add(DateTimeFieldType.monthOfYear()); fields.add(DateTimeFieldType.dayOfMonth()); return ISODateTimeFormat.forFields(fields, true, true).print(this); } /** * Output the month-day using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the month-day using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) throws IllegalArgumentException { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } //----------------------------------------------------------------------- /** * The property class for MonthDay. *

* This class binds a YearMonth to a DateTimeField. * * @author Chris Pheby * @since 2.0 */ public static class Property extends AbstractPartialFieldProperty implements Serializable { /** Serialization version */ private static final long serialVersionUID = 5727734012190224363L; /** The partial */ private final MonthDay iBase; /** The field index */ private final int iFieldIndex; /** * Constructs a property. * * @param partial the partial instance * @param fieldIndex the index in the partial */ Property(MonthDay partial, int fieldIndex) { super(); iBase = partial; iFieldIndex = fieldIndex; } /** * Gets the field that this property uses. * * @return the field */ public DateTimeField getField() { return iBase.getField(iFieldIndex); } /** * Gets the partial that this property belongs to. * * @return the partial */ protected ReadablePartial getReadablePartial() { return iBase; } /** * Gets the partial that this property belongs to. * * @return the partial */ public MonthDay getMonthDay() { return iBase; } /** * Gets the value of this field. * * @return the field value */ public int get() { return iBase.getValue(iFieldIndex); } //----------------------------------------------------------------------- /** * Adds to the value of this field in a copy of this MonthDay. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it will affect larger fields. * Smaller fields are unaffected. *

* The MonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the MonthDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public MonthDay addToCopy(int valueToAdd) { int[] newValues = iBase.getValues(); newValues = getField().add(iBase, iFieldIndex, newValues, valueToAdd); return new MonthDay(iBase, newValues); } /** * Adds to the value of this field in a copy of this MonthDay wrapping * within this field if the maximum value is reached. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps within this field. * Other fields are unaffected. *

* For example, * --12-30 addWrapField one month returns --01-30. *

* The MonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the MonthDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public MonthDay addWrapFieldToCopy(int valueToAdd) { int[] newValues = iBase.getValues(); newValues = getField().addWrapField(iBase, iFieldIndex, newValues, valueToAdd); return new MonthDay(iBase, newValues); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the MonthDay. *

* The MonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param value the value to set the field in the copy to * @return a copy of the MonthDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public MonthDay setCopy(int value) { int[] newValues = iBase.getValues(); newValues = getField().set(iBase, iFieldIndex, newValues, value); return new MonthDay(iBase, newValues); } /** * Sets this field in a copy of the MonthDay to a parsed text value. *

* The MonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the MonthDay with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public MonthDay setCopy(String text, Locale locale) { int[] newValues = iBase.getValues(); newValues = getField().set(iBase, iFieldIndex, newValues, text, locale); return new MonthDay(iBase, newValues); } /** * Sets this field in a copy of the MonthDay to a parsed text value. *

* The MonthDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @return a copy of the MonthDay with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public MonthDay setCopy(String text) { return setCopy(text, null); } } } joda-time-2.3/src/main/java/org/joda/time/DurationFieldType.java0000644000175000017500000002552511667410753024136 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; /** * Identifies a duration field, such as years or minutes, in a chronology-neutral way. *

* A duration field type defines the type of the field, such as hours. * If does not directly enable any calculations, however it does provide a * {@link #getField(Chronology)} method that returns the actual calculation engine * for a particular chronology. *

* Instances of DurationFieldType are singletons. * They can be compared using ==. *

* If required, you can create your own field, for example a quarters. * You must create a subclass of DurationFieldType that defines the field type. * This class returns the actual calculation engine from {@link #getField(Chronology)}. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public abstract class DurationFieldType implements Serializable { /** Serialization version */ private static final long serialVersionUID = 8765135187319L; // Ordinals for standard field types. static final byte ERAS = 1, CENTURIES = 2, WEEKYEARS = 3, YEARS = 4, MONTHS = 5, WEEKS = 6, DAYS = 7, HALFDAYS = 8, HOURS = 9, MINUTES = 10, SECONDS = 11, MILLIS = 12; /** The eras field type. */ static final DurationFieldType ERAS_TYPE = new StandardDurationFieldType("eras", ERAS); /** The centuries field type. */ static final DurationFieldType CENTURIES_TYPE = new StandardDurationFieldType("centuries", CENTURIES); /** The weekyears field type. */ static final DurationFieldType WEEKYEARS_TYPE = new StandardDurationFieldType("weekyears", WEEKYEARS); /** The years field type. */ static final DurationFieldType YEARS_TYPE = new StandardDurationFieldType("years", YEARS); /** The months field type. */ static final DurationFieldType MONTHS_TYPE = new StandardDurationFieldType("months", MONTHS); /** The weeks field type. */ static final DurationFieldType WEEKS_TYPE = new StandardDurationFieldType("weeks", WEEKS); /** The days field type. */ static final DurationFieldType DAYS_TYPE = new StandardDurationFieldType("days", DAYS); /** The halfdays field type. */ static final DurationFieldType HALFDAYS_TYPE = new StandardDurationFieldType("halfdays", HALFDAYS); /** The hours field type. */ static final DurationFieldType HOURS_TYPE = new StandardDurationFieldType("hours", HOURS); /** The minutes field type. */ static final DurationFieldType MINUTES_TYPE = new StandardDurationFieldType("minutes", MINUTES); /** The seconds field type. */ static final DurationFieldType SECONDS_TYPE = new StandardDurationFieldType("seconds", SECONDS); /** The millis field type. */ static final DurationFieldType MILLIS_TYPE = new StandardDurationFieldType("millis", MILLIS); /** The name of the field type. */ private final String iName; //----------------------------------------------------------------------- /** * Constructor. * * @param name the name to use, which by convention, are plural. */ protected DurationFieldType(String name) { super(); iName = name; } //----------------------------------------------------------------------- /** * Get the millis field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType millis() { return MILLIS_TYPE; } /** * Get the seconds field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType seconds() { return SECONDS_TYPE; } /** * Get the minutes field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType minutes() { return MINUTES_TYPE; } /** * Get the hours field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType hours() { return HOURS_TYPE; } /** * Get the halfdays field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType halfdays() { return HALFDAYS_TYPE; } //----------------------------------------------------------------------- /** * Get the days field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType days() { return DAYS_TYPE; } /** * Get the weeks field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType weeks() { return WEEKS_TYPE; } /** * Get the weekyears field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType weekyears() { return WEEKYEARS_TYPE; } /** * Get the months field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType months() { return MONTHS_TYPE; } /** * Get the years field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType years() { return YEARS_TYPE; } /** * Get the centuries field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType centuries() { return CENTURIES_TYPE; } /** * Get the eras field type. * * @return the DateTimeFieldType constant */ public static DurationFieldType eras() { return ERAS_TYPE; } //----------------------------------------------------------------------- /** * Get the name of the field. * By convention, names are plural. * * @return field name */ public String getName() { return iName; } /** * Gets a suitable field for this type from the given Chronology. * * @param chronology the chronology to use, null means ISOChronology in default zone * @return a suitable field */ public abstract DurationField getField(Chronology chronology); /** * Checks whether this field supported in the given Chronology. * * @param chronology the chronology to use, null means ISOChronology in default zone * @return true if supported */ public boolean isSupported(Chronology chronology) { return getField(chronology).isSupported(); } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return getName(); } private static class StandardDurationFieldType extends DurationFieldType { /** Serialization version */ private static final long serialVersionUID = 31156755687123L; /** The ordinal of the standard field type, for switch statements */ private final byte iOrdinal; /** * Constructor. * * @param name the name to use */ StandardDurationFieldType(String name, byte ordinal) { super(name); iOrdinal = ordinal; } /** @inheritdoc */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof StandardDurationFieldType) { return iOrdinal == ((StandardDurationFieldType) obj).iOrdinal; } return false; } /** @inheritdoc */ @Override public int hashCode() { return (1 << iOrdinal); } public DurationField getField(Chronology chronology) { chronology = DateTimeUtils.getChronology(chronology); switch (iOrdinal) { case ERAS: return chronology.eras(); case CENTURIES: return chronology.centuries(); case WEEKYEARS: return chronology.weekyears(); case YEARS: return chronology.years(); case MONTHS: return chronology.months(); case WEEKS: return chronology.weeks(); case DAYS: return chronology.days(); case HALFDAYS: return chronology.halfdays(); case HOURS: return chronology.hours(); case MINUTES: return chronology.minutes(); case SECONDS: return chronology.seconds(); case MILLIS: return chronology.millis(); default: // Shouldn't happen. throw new InternalError(); } } /** * Ensure a singleton is returned. * * @return the singleton type */ private Object readResolve() { switch (iOrdinal) { case ERAS: return ERAS_TYPE; case CENTURIES: return CENTURIES_TYPE; case WEEKYEARS: return WEEKYEARS_TYPE; case YEARS: return YEARS_TYPE; case MONTHS: return MONTHS_TYPE; case WEEKS: return WEEKS_TYPE; case DAYS: return DAYS_TYPE; case HALFDAYS: return HALFDAYS_TYPE; case HOURS: return HOURS_TYPE; case MINUTES: return MINUTES_TYPE; case SECONDS: return SECONDS_TYPE; case MILLIS: return MILLIS_TYPE; default: // Shouldn't happen. return this; } } } } joda-time-2.3/src/main/java/org/joda/time/Weeks.java0000644000175000017500000004544111564251363021614 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseSingleFieldPeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period representing a number of weeks. *

* Weeks is an immutable period that can only store weeks. * It does not store years, months or hours for example. As such it is a * type-safe way of representing a number of weeks in an application. *

* The number of weeks is set in the constructor, and may be queried using * getWeeks(). Basic mathematical operations are provided - * plus(), minus(), multipliedBy() and * dividedBy(). *

* Weeks is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.4 */ public final class Weeks extends BaseSingleFieldPeriod { /** Constant representing zero weeks. */ public static final Weeks ZERO = new Weeks(0); /** Constant representing one week. */ public static final Weeks ONE = new Weeks(1); /** Constant representing two weeks. */ public static final Weeks TWO = new Weeks(2); /** Constant representing three weeks. */ public static final Weeks THREE = new Weeks(3); /** Constant representing the maximum number of weeks that can be stored in this object. */ public static final Weeks MAX_VALUE = new Weeks(Integer.MAX_VALUE); /** Constant representing the minimum number of weeks that can be stored in this object. */ public static final Weeks MIN_VALUE = new Weeks(Integer.MIN_VALUE); /** The paser to use for this class. */ private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.weeks()); /** Serialization version. */ private static final long serialVersionUID = 87525275727380866L; //----------------------------------------------------------------------- /** * Obtains an instance of Weeks that may be cached. * Weeks is immutable, so instances can be cached and shared. * This factory method provides access to shared instances. * * @param weeks the number of weeks to obtain an instance for * @return the instance of Weeks */ public static Weeks weeks(int weeks) { switch (weeks) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Weeks(weeks); } } //----------------------------------------------------------------------- /** * Creates a Weeks representing the number of whole weeks * between the two specified datetimes. * * @param start the start instant, must not be null * @param end the end instant, must not be null * @return the period in weeks * @throws IllegalArgumentException if the instants are null or invalid */ public static Weeks weeksBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.weeks()); return Weeks.weeks(amount); } /** * Creates a Weeks representing the number of whole weeks * between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalDate objects. * * @param start the start partial date, must not be null * @param end the end partial date, must not be null * @return the period in weeks * @throws IllegalArgumentException if the partials are null or invalid */ public static Weeks weeksBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalDate && end instanceof LocalDate) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int weeks = chrono.weeks().getDifference( ((LocalDate) end).getLocalMillis(), ((LocalDate) start).getLocalMillis()); return Weeks.weeks(weeks); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Weeks.weeks(amount); } /** * Creates a Weeks representing the number of whole weeks * in the specified interval. * * @param interval the interval to extract weeks from, null returns zero * @return the period in weeks * @throws IllegalArgumentException if the partials are null or invalid */ public static Weeks weeksIn(ReadableInterval interval) { if (interval == null) { return Weeks.ZERO; } int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.weeks()); return Weeks.weeks(amount); } /** * Creates a new Weeks representing the number of complete * standard length weeks in the specified period. *

* This factory method converts all fields from the period to hours using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. *

    *
  • One week consists of 7 days. *
  • One day consists of 24 hours. *
  • One hour consists of 60 minutes. *
  • One minute consists of 60 weeks. *
  • One second consists of 1000 milliseconds. *
* Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of hours from, null returns zero * @return the period in weeks * @throws IllegalArgumentException if the period contains imprecise duration values */ public static Weeks standardWeeksIn(ReadablePeriod period) { int amount = BaseSingleFieldPeriod.standardPeriodIn(period, DateTimeConstants.MILLIS_PER_WEEK); return Weeks.weeks(amount); } /** * Creates a new Weeks by parsing a string in the ISO8601 format 'PnW'. *

* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the * weeks component may be non-zero. If any other component is non-zero, an exception * will be thrown. * * @param periodStr the period string, null returns zero * @return the period in weeks * @throws IllegalArgumentException if the string format is invalid */ @FromString public static Weeks parseWeeks(String periodStr) { if (periodStr == null) { return Weeks.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Weeks.weeks(p.getWeeks()); } //----------------------------------------------------------------------- /** * Creates a new instance representing a number of weeks. * You should consider using the factory method {@link #weeks(int)} * instead of the constructor. * * @param weeks the number of weeks to represent */ private Weeks(int weeks) { super(weeks); } /** * Resolves singletons. * * @return the singleton instance */ private Object readResolve() { return Weeks.weeks(getValue()); } //----------------------------------------------------------------------- /** * Gets the duration field type, which is weeks. * * @return the period type */ public DurationFieldType getFieldType() { return DurationFieldType.weeks(); } /** * Gets the period type, which is weeks. * * @return the period type */ public PeriodType getPeriodType() { return PeriodType.weeks(); } //----------------------------------------------------------------------- /** * Converts this period in weeks to a period in days assuming a * 7 day week. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are * 7 days long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of days for this number of weeks * @throws ArithmeticException if the number of days is too large to be represented */ public Days toStandardDays() { return Days.days(FieldUtils.safeMultiply(getValue(), DateTimeConstants.DAYS_PER_WEEK)); } /** * Converts this period in weeks to a period in hours assuming a * 7 day week and 24 hour day. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are * 7 days long and all days are 24 hours long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of hours for this number of weeks * @throws ArithmeticException if the number of hours is too large to be represented */ public Hours toStandardHours() { return Hours.hours(FieldUtils.safeMultiply(getValue(), DateTimeConstants.HOURS_PER_WEEK)); } /** * Converts this period in weeks to a period in minutes assuming a * 7 day week, 24 hour day and 60 minute hour. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are * 7 days long, all days are 24 hours long and all hours are 60 minutes long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of minutes for this number of weeks * @throws ArithmeticException if the number of minutes is too large to be represented */ public Minutes toStandardMinutes() { return Minutes.minutes(FieldUtils.safeMultiply(getValue(), DateTimeConstants.MINUTES_PER_WEEK)); } /** * Converts this period in weeks to a period in seconds assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are * 7 days long, all days are 24 hours long, all hours are 60 minutes long * and all minutes are 60 seconds long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of seconds for this number of weeks * @throws ArithmeticException if the number of seconds is too large to be represented */ public Seconds toStandardSeconds() { return Seconds.seconds(FieldUtils.safeMultiply(getValue(), DateTimeConstants.SECONDS_PER_WEEK)); } //----------------------------------------------------------------------- /** * Converts this period in weeks to a duration in milliweeks assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert from a period to a duration. * However to achieve this it makes the assumption that all weeks are * 7 days long, all days are 24 hours long, all hours are 60 minutes long * and all minutes are 60 seconds long. * This is not true when daylight savings time is considered, and may also * not be true for some unusual chronologies. However, it is included as it * is a useful operation for many applications and business rules. * * @return a duration equivalent to this number of weeks */ public Duration toStandardDuration() { long weeks = getValue(); // assign to a long return new Duration(weeks * DateTimeConstants.MILLIS_PER_WEEK); } //----------------------------------------------------------------------- /** * Gets the number of weeks that this period represents. * * @return the number of weeks in the period */ public int getWeeks() { return getValue(); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of weeks added. *

* This instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to add, may be negative * @return the new period plus the specified number of weeks * @throws ArithmeticException if the result overflows an int */ public Weeks plus(int weeks) { if (weeks == 0) { return this; } return Weeks.weeks(FieldUtils.safeAdd(getValue(), weeks)); } /** * Returns a new instance with the specified number of weeks added. *

* This instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to add, may be negative, null means zero * @return the new period plus the specified number of weeks * @throws ArithmeticException if the result overflows an int */ public Weeks plus(Weeks weeks) { if (weeks == null) { return this; } return plus(weeks.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of weeks taken away. *

* This instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to take away, may be negative * @return the new period minus the specified number of weeks * @throws ArithmeticException if the result overflows an int */ public Weeks minus(int weeks) { return plus(FieldUtils.safeNegate(weeks)); } /** * Returns a new instance with the specified number of weeks taken away. *

* This instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to take away, may be negative, null means zero * @return the new period minus the specified number of weeks * @throws ArithmeticException if the result overflows an int */ public Weeks minus(Weeks weeks) { if (weeks == null) { return this; } return minus(weeks.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the weeks multiplied by the specified scalar. *

* This instance is immutable and unaffected by this method call. * * @param scalar the amount to multiply by, may be negative * @return the new period multiplied by the specified scalar * @throws ArithmeticException if the result overflows an int */ public Weeks multipliedBy(int scalar) { return Weeks.weeks(FieldUtils.safeMultiply(getValue(), scalar)); } /** * Returns a new instance with the weeks divided by the specified divisor. * The calculation uses integer division, thus 3 divided by 2 is 1. *

* This instance is immutable and unaffected by this method call. * * @param divisor the amount to divide by, may be negative * @return the new period divided by the specified divisor * @throws ArithmeticException if the divisor is zero */ public Weeks dividedBy(int divisor) { if (divisor == 1) { return this; } return Weeks.weeks(getValue() / divisor); } //----------------------------------------------------------------------- /** * Returns a new instance with the weeks value negated. * * @return the new period with a negated value * @throws ArithmeticException if the result overflows an int */ public Weeks negated() { return Weeks.weeks(FieldUtils.safeNegate(getValue())); } //----------------------------------------------------------------------- /** * Is this weeks instance greater than the specified number of weeks. * * @param other the other period, null means zero * @return true if this weeks instance is greater than the specified one */ public boolean isGreaterThan(Weeks other) { if (other == null) { return getValue() > 0; } return getValue() > other.getValue(); } /** * Is this weeks instance less than the specified number of weeks. * * @param other the other period, null means zero * @return true if this weeks instance is less than the specified one */ public boolean isLessThan(Weeks other) { if (other == null) { return getValue() < 0; } return getValue() < other.getValue(); } //----------------------------------------------------------------------- /** * Gets this instance as a String in the ISO8601 duration format. *

* For example, "P4W" represents 4 weeks. * * @return the value as an ISO8601 string */ @ToString public String toString() { return "P" + String.valueOf(getValue()) + "W"; } } joda-time-2.3/src/main/java/org/joda/time/TimeOfDay.java0000644000175000017500000013741111616003375022352 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.joda.time.base.BasePartial; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractPartialFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISODateTimeFormat; /** * TimeOfDay is an immutable partial supporting the hour, minute, second * and millisecond fields. *

* NOTE: This class only supports the four fields listed above. Thus, you * cannot query the millisOfDay or secondOfDay fields for example. * The new LocalTime class removes this restriction. *

* Calculations on TimeOfDay are performed using a {@link Chronology}. * This chronology is set to be in the UTC time zone for all calculations. *

* Each individual field can be queried in two ways: *

    *
  • getHourOfDay() *
  • hourOfDay().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value - hourOfDay().get() *
  • text value - hourOfDay().getAsText() *
  • short text value - hourOfDay().getAsShortText() *
  • maximum/minimum values - hourOfDay().getMaximumValue() *
  • add/subtract - hourOfDay().addToCopy() *
  • set - hourOfDay().setCopy() *
*

* TimeOfDay is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 * @deprecated Use LocalTime which has a much better internal implementation and * has been available since 1.3 */ @Deprecated public final class TimeOfDay extends BasePartial implements ReadablePartial, Serializable { // NOTE: No toDateTime(YearMonthDay) as semantics are confusing when // different chronologies /** Serialization version */ private static final long serialVersionUID = 3633353405803318660L; /** The singleton set of field types */ private static final DateTimeFieldType[] FIELD_TYPES = new DateTimeFieldType[] { DateTimeFieldType.hourOfDay(), DateTimeFieldType.minuteOfHour(), DateTimeFieldType.secondOfMinute(), DateTimeFieldType.millisOfSecond(), }; /** Constant for midnight. */ public static final TimeOfDay MIDNIGHT = new TimeOfDay(0, 0, 0, 0); /** The index of the hourOfDay field in the field array */ public static final int HOUR_OF_DAY = 0; /** The index of the minuteOfHour field in the field array */ public static final int MINUTE_OF_HOUR = 1; /** The index of the secondOfMinute field in the field array */ public static final int SECOND_OF_MINUTE = 2; /** The index of the millisOfSecond field in the field array */ public static final int MILLIS_OF_SECOND = 3; //----------------------------------------------------------------------- /** * Constructs a TimeOfDay from a java.util.Calendar * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Calendar and assigned to the TimeOfDay. * This is useful to ensure that the field values are the same in the * created TimeOfDay no matter what the time zone is. For example, if * the Calendar states that the time is 04:29, then the created TimeOfDay * will always have the time 04:29 irrespective of time zone issues. *

* This factory method ignores the type of the calendar and always * creates a TimeOfDay with ISO chronology. * * @param calendar the Calendar to extract fields from * @return the created TimeOfDay * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the time is invalid for the ISO chronology * @since 1.2 */ public static TimeOfDay fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } return new TimeOfDay( calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), calendar.get(Calendar.MILLISECOND) ); } /** * Constructs a TimeOfDay from a java.util.Date * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Date and assigned to the TimeOfDay. * This is useful to ensure that the field values are the same in the * created TimeOfDay no matter what the time zone is. For example, if * the Calendar states that the time is 04:29, then the created TimeOfDay * will always have the time 04:29 irrespective of time zone issues. *

* This factory method always creates a TimeOfDay with ISO chronology. * * @param date the Date to extract fields from * @return the created TimeOfDay * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology * @since 1.2 */ public static TimeOfDay fromDateFields(Date date) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } return new TimeOfDay( date.getHours(), date.getMinutes(), date.getSeconds(), (((int) (date.getTime() % 1000)) + 1000) % 1000 ); } //----------------------------------------------------------------------- /** * Constructs a TimeOfDay from the specified millis of day using the * ISO chronology. *

* The millisOfDay value may exceed the number of millis in one day, * but additional days will be ignored. * This method uses the UTC time zone internally. * * @param millisOfDay the number of milliseconds into a day to convert */ public static TimeOfDay fromMillisOfDay(long millisOfDay) { return fromMillisOfDay(millisOfDay, null); } /** * Constructs a TimeOfDay from the specified millis of day using the * specified chronology. *

* The millisOfDay value may exceed the number of millis in one day, * but additional days will be ignored. * This method uses the UTC time zone internally. * * @param millisOfDay the number of milliseconds into a day to convert * @param chrono the chronology, null means ISO chronology */ public static TimeOfDay fromMillisOfDay(long millisOfDay, Chronology chrono) { chrono = DateTimeUtils.getChronology(chrono); chrono = chrono.withUTC(); return new TimeOfDay(millisOfDay, chrono); } // Constructors //----------------------------------------------------------------------- /** * Constructs a TimeOfDay with the current time, using ISOChronology in * the default zone to extract the fields. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). */ public TimeOfDay() { super(); } /** * Constructs a TimeOfDay with the current time, using ISOChronology in * the specified zone to extract the fields. *

* The constructor uses the specified time zone to obtain the current time. * Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param zone the zone to use, null means default zone * @since 1.1 */ public TimeOfDay(DateTimeZone zone) { super(ISOChronology.getInstance(zone)); } /** * Constructs a TimeOfDay with the current time, using the specified chronology * and zone to extract the fields. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param chronology the chronology, null means ISOChronology in the default zone */ public TimeOfDay(Chronology chronology) { super(chronology); } /** * Constructs a TimeOfDay extracting the partial fields from the specified * milliseconds using the ISOChronology in the default zone. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public TimeOfDay(long instant) { super(instant); } /** * Constructs a TimeOfDay extracting the partial fields from the specified * milliseconds using the chronology provided. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in the default zone */ public TimeOfDay(long instant, Chronology chronology) { super(instant, chronology); } /** * Constructs a TimeOfDay from an Object that represents a time. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#timeParser()}. *

* The chronology used will be derived from the object, defaulting to ISO. *

* NOTE: Prior to v1.3 the string format was described by * {@link ISODateTimeFormat#dateTimeParser()}. Dates are now rejected. * * @param instant the datetime object, null means now * @throws IllegalArgumentException if the instant is invalid */ public TimeOfDay(Object instant) { super(instant, null, ISODateTimeFormat.timeParser()); } /** * Constructs a TimeOfDay from an Object that represents a time, using the * specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#timeParser()}. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * The specified chronology overrides that of the object. *

* NOTE: Prior to v1.3 the string format was described by * {@link ISODateTimeFormat#dateTimeParser()}. Dates are now rejected. * * @param instant the datetime object, null means now * @param chronology the chronology, null means ISO default * @throws IllegalArgumentException if the instant is invalid */ public TimeOfDay(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology), ISODateTimeFormat.timeParser()); } /** * Constructs a TimeOfDay with specified hour and minute and zero seconds and milliseconds * using ISOChronology in the default zone. *

* The constructor uses the no time zone initialising the fields as provided. * Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour */ public TimeOfDay(int hourOfDay, int minuteOfHour) { this(hourOfDay, minuteOfHour, 0, 0, null); } /** * Constructs a TimeOfDay with specified hour and minute and zero seconds and milliseconds. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param chronology the chronology, null means ISOChronology in the default zone */ public TimeOfDay(int hourOfDay, int minuteOfHour, Chronology chronology) { this(hourOfDay, minuteOfHour, 0, 0, chronology); } /** * Constructs a TimeOfDay with specified time field values and zero milliseconds * using ISOChronology in the default zone. *

* The constructor uses the no time zone initialising the fields as provided. * Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute */ public TimeOfDay(int hourOfDay, int minuteOfHour, int secondOfMinute) { this(hourOfDay, minuteOfHour, secondOfMinute, 0, null); } /** * Constructs a TimeOfDay with specified time field values and zero milliseconds. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param chronology the chronology, null means ISOChronology in the default zone */ public TimeOfDay(int hourOfDay, int minuteOfHour, int secondOfMinute, Chronology chronology) { this(hourOfDay, minuteOfHour, secondOfMinute, 0, chronology); } /** * Constructs a TimeOfDay with specified time field values using * ISOChronology in the default zone. *

* The constructor uses the no time zone initialising the fields as provided. * Once the constructor is complete, all further calculations * are performed without reference to a timezone (by switching to UTC). * * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second */ public TimeOfDay(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { this(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, null); } /** * Constructs a TimeOfDay with specified time field values and chronology. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a timezone (by switching to UTC). * * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param chronology the chronology, null means ISOChronology in the default zone */ public TimeOfDay(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(new int[] {hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond}, chronology); } /** * Constructs a TimeOfDay with chronology from this instance and new values. * * @param partial the partial to base this new instance on * @param values the new set of values */ TimeOfDay(TimeOfDay partial, int[] values) { super(partial, values); } /** * Constructs a TimeOfDay with values from this instance and a new chronology. * * @param partial the partial to base this new instance on * @param chrono the new chronology */ TimeOfDay(TimeOfDay partial, Chronology chrono) { super(partial, chrono); } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial. * * @return the field count */ public int size() { return 4; } /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field */ protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case HOUR_OF_DAY: return chrono.hourOfDay(); case MINUTE_OF_HOUR: return chrono.minuteOfHour(); case SECOND_OF_MINUTE: return chrono.secondOfMinute(); case MILLIS_OF_SECOND: return chrono.millisOfSecond(); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public DateTimeFieldType getFieldType(int index) { return FIELD_TYPES[index]; } /** * Gets an array of the field type of each of the fields that this partial supports. *

* The fields are returned largest to smallest, Hour, Minute, Second, Millis. * * @return the array of field types (cloned), largest to smallest */ public DateTimeFieldType[] getFieldTypes() { return (DateTimeFieldType[]) FIELD_TYPES.clone(); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the specified chronology. * This instance is immutable and unaffected by this method call. *

* This method retains the values of the fields, thus the result will * typically refer to a different instant. *

* The time zone of the specified chronology is ignored, as TimeOfDay * operates without a time zone. * * @param newChronology the new chronology, null means ISO * @return a copy of this datetime with a different chronology * @throws IllegalArgumentException if the values are invalid for the new chronology */ public TimeOfDay withChronologyRetainFields(Chronology newChronology) { newChronology = DateTimeUtils.getChronology(newChronology); newChronology = newChronology.withUTC(); if (newChronology == getChronology()) { return this; } else { TimeOfDay newTimeOfDay = new TimeOfDay(this, newChronology); newChronology.validate(newTimeOfDay, getValues()); return newTimeOfDay; } } /** * Returns a copy of this time with the specified field set to a new value. *

* For example, if the field type is minuteOfHour then the day * would be changed in the returned instance. *

* These three lines are equivalent: *

     * TimeOfDay updated = tod.withField(DateTimeFieldType.minuteOfHour(), 6);
     * TimeOfDay updated = tod.minuteOfHour().setCopy(6);
     * TimeOfDay updated = tod.property(DateTimeFieldType.minuteOfHour()).setCopy(6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this instance with the field set * @throws IllegalArgumentException if the value is null or invalid */ public TimeOfDay withField(DateTimeFieldType fieldType, int value) { int index = indexOfSupported(fieldType); if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new TimeOfDay(this, newValues); } /** * Returns a copy of this time with the value of the specified field increased, * wrapping to what would be a new day if required. *

* If the addition is zero, then this is returned. *

* These three lines are equivalent: *

     * TimeOfDay added = tod.withFieldAdded(DurationFieldType.minutes(), 6);
     * TimeOfDay added = tod.plusMinutes(6);
     * TimeOfDay added = tod.minuteOfHour().addToCopy(6);
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this instance with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new datetime exceeds the capacity */ public TimeOfDay withFieldAdded(DurationFieldType fieldType, int amount) { int index = indexOfSupported(fieldType); if (amount == 0) { return this; } int[] newValues = getValues(); newValues = getField(index).addWrapPartial(this, index, newValues, amount); return new TimeOfDay(this, newValues); } /** * Returns a copy of this time with the specified period added, * wrapping to what would be a new day if required. *

* If the addition is zero, then this is returned. * Fields in the period that aren't present in the partial are ignored. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusHours(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this instance with the period added * @throws ArithmeticException if the new datetime exceeds the capacity */ public TimeOfDay withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } int[] newValues = getValues(); for (int i = 0; i < period.size(); i++) { DurationFieldType fieldType = period.getFieldType(i); int index = indexOf(fieldType); if (index >= 0) { newValues = getField(index).addWrapPartial(this, index, newValues, FieldUtils.safeMultiply(period.getValue(i), scalar)); } } return new TimeOfDay(this, newValues); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the specified period added, * wrapping to what would be a new day if required. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusHours(int)}. * * @param period the duration to add to this one, null means zero * @return a copy of this instance with the period added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public TimeOfDay plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this time plus the specified number of hours. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay added = dt.plusHours(6);
     * TimeOfDay added = dt.plus(Period.hours(6));
     * TimeOfDay added = dt.withFieldAdded(DurationFieldType.hours(), 6);
     * 
* * @param hours the amount of hours to add, may be negative * @return the new time plus the increased hours * @since 1.1 */ public TimeOfDay plusHours(int hours) { return withFieldAdded(DurationFieldType.hours(), hours); } /** * Returns a copy of this time plus the specified number of minutes. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay added = dt.plusMinutes(6);
     * TimeOfDay added = dt.plus(Period.minutes(6));
     * TimeOfDay added = dt.withFieldAdded(DurationFieldType.minutes(), 6);
     * 
* * @param minutes the amount of minutes to add, may be negative * @return the new time plus the increased minutes * @since 1.1 */ public TimeOfDay plusMinutes(int minutes) { return withFieldAdded(DurationFieldType.minutes(), minutes); } /** * Returns a copy of this time plus the specified number of seconds. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay added = dt.plusSeconds(6);
     * TimeOfDay added = dt.plus(Period.seconds(6));
     * TimeOfDay added = dt.withFieldAdded(DurationFieldType.seconds(), 6);
     * 
* * @param seconds the amount of seconds to add, may be negative * @return the new time plus the increased seconds * @since 1.1 */ public TimeOfDay plusSeconds(int seconds) { return withFieldAdded(DurationFieldType.seconds(), seconds); } /** * Returns a copy of this time plus the specified number of millis. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay added = dt.plusMillis(6);
     * TimeOfDay added = dt.plus(Period.millis(6));
     * TimeOfDay added = dt.withFieldAdded(DurationFieldType.millis(), 6);
     * 
* * @param millis the amount of millis to add, may be negative * @return the new time plus the increased millis * @since 1.1 */ public TimeOfDay plusMillis(int millis) { return withFieldAdded(DurationFieldType.millis(), millis); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the specified period taken away, * wrapping to what would be a new day if required. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusHours(int)}. * * @param period the period to reduce this instant by * @return a copy of this instance with the period taken away * @throws ArithmeticException if the new time exceeds capacity */ public TimeOfDay minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this time minus the specified number of hours. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay subtracted = dt.minusHours(6);
     * TimeOfDay subtracted = dt.minus(Period.hours(6));
     * TimeOfDay subtracted = dt.withFieldAdded(DurationFieldType.hours(), -6);
     * 
* * @param hours the amount of hours to subtract, may be negative * @return the new time minus the increased hours * @since 1.1 */ public TimeOfDay minusHours(int hours) { return withFieldAdded(DurationFieldType.hours(), FieldUtils.safeNegate(hours)); } /** * Returns a copy of this time minus the specified number of minutes. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay subtracted = dt.minusMinutes(6);
     * TimeOfDay subtracted = dt.minus(Period.minutes(6));
     * TimeOfDay subtracted = dt.withFieldAdded(DurationFieldType.minutes(), -6);
     * 
* * @param minutes the amount of minutes to subtract, may be negative * @return the new time minus the increased minutes * @since 1.1 */ public TimeOfDay minusMinutes(int minutes) { return withFieldAdded(DurationFieldType.minutes(), FieldUtils.safeNegate(minutes)); } /** * Returns a copy of this time minus the specified number of seconds. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay subtracted = dt.minusSeconds(6);
     * TimeOfDay subtracted = dt.minus(Period.seconds(6));
     * TimeOfDay subtracted = dt.withFieldAdded(DurationFieldType.seconds(), -6);
     * 
* * @param seconds the amount of seconds to subtract, may be negative * @return the new time minus the increased seconds * @since 1.1 */ public TimeOfDay minusSeconds(int seconds) { return withFieldAdded(DurationFieldType.seconds(), FieldUtils.safeNegate(seconds)); } /** * Returns a copy of this time minus the specified number of millis. *

* This time instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * TimeOfDay subtracted = dt.minusMillis(6);
     * TimeOfDay subtracted = dt.minus(Period.millis(6));
     * TimeOfDay subtracted = dt.withFieldAdded(DurationFieldType.millis(), -6);
     * 
* * @param millis the amount of millis to subtract, may be negative * @return the new time minus the increased millis * @since 1.1 */ public TimeOfDay minusMillis(int millis) { return withFieldAdded(DurationFieldType.millis(), FieldUtils.safeNegate(millis)); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains * many useful methods. * * @param type the field type to get the property for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType type) { return new Property(this, indexOfSupported(type)); } //----------------------------------------------------------------------- /** * Converts this object to a LocalTime with the same time and chronology. * * @return a LocalTime with the same time and chronology * @since 1.3 */ public LocalTime toLocalTime() { return new LocalTime(getHourOfDay(), getMinuteOfHour(), getSecondOfMinute(), getMillisOfSecond(), getChronology()); } //----------------------------------------------------------------------- /** * Converts this partial to a full datetime using the default time zone * setting the time fields from this instance and the date fields from * the current time. * * @return this date as a datetime with the time as the current time */ public DateTime toDateTimeToday() { return toDateTimeToday(null); } /** * Converts this partial to a full datetime using the specified time zone * setting the time fields from this instance and the date fields from * the current time. *

* This method uses the chronology from this instance plus the time zone * specified. * * @param zone the zone to use, null means default * @return this date as a datetime with the time as the current time */ public DateTime toDateTimeToday(DateTimeZone zone) { Chronology chrono = getChronology().withZone(zone); long instantMillis = DateTimeUtils.currentTimeMillis(); long resolved = chrono.set(this, instantMillis); return new DateTime(resolved, chrono); } //----------------------------------------------------------------------- /** * Get the hour of day (0-23) field value. * * @return the hour of day */ public int getHourOfDay() { return getValue(HOUR_OF_DAY); } /** * Get the minute of hour field value. * * @return the minute of hour */ public int getMinuteOfHour() { return getValue(MINUTE_OF_HOUR); } /** * Get the second of minute field value. * * @return the second of minute */ public int getSecondOfMinute() { return getValue(SECOND_OF_MINUTE); } /** * Get the millis of second field value. * * @return the millis of second */ public int getMillisOfSecond() { return getValue(MILLIS_OF_SECOND); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the hour of day field updated. *

* TimeOfDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * hour of day changed. * * @param hour the hour of day to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public TimeOfDay withHourOfDay(int hour) { int[] newValues = getValues(); newValues = getChronology().hourOfDay().set(this, HOUR_OF_DAY, newValues, hour); return new TimeOfDay(this, newValues); } /** * Returns a copy of this time with the minute of hour field updated. *

* TimeOfDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * minute of hour changed. * * @param minute the minute of hour to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public TimeOfDay withMinuteOfHour(int minute) { int[] newValues = getValues(); newValues = getChronology().minuteOfHour().set(this, MINUTE_OF_HOUR, newValues, minute); return new TimeOfDay(this, newValues); } /** * Returns a copy of this time with the second of minute field updated. *

* TimeOfDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * second of minute changed. * * @param second the second of minute to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public TimeOfDay withSecondOfMinute(int second) { int[] newValues = getValues(); newValues = getChronology().secondOfMinute().set(this, SECOND_OF_MINUTE, newValues, second); return new TimeOfDay(this, newValues); } /** * Returns a copy of this time with the millis of second field updated. *

* TimeOfDay is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * millis of second changed. * * @param millis the millis of second to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public TimeOfDay withMillisOfSecond(int millis) { int[] newValues = getValues(); newValues = getChronology().millisOfSecond().set(this, MILLIS_OF_SECOND, newValues, millis); return new TimeOfDay(this, newValues); } //----------------------------------------------------------------------- /** * Get the hour of day field property which provides access to advanced functionality. * * @return the hour of day property */ public Property hourOfDay() { return new Property(this, HOUR_OF_DAY); } /** * Get the minute of hour field property which provides access to advanced functionality. * * @return the minute of hour property */ public Property minuteOfHour() { return new Property(this, MINUTE_OF_HOUR); } /** * Get the second of minute field property which provides access to advanced functionality. * * @return the second of minute property */ public Property secondOfMinute() { return new Property(this, SECOND_OF_MINUTE); } /** * Get the millis of second property which provides access to advanced functionality. * * @return the millis of second property */ public Property millisOfSecond() { return new Property(this, MILLIS_OF_SECOND); } //----------------------------------------------------------------------- /** * Output the time in the ISO8601 format THH:mm:ss.SSS. * * @return ISO8601 formatted string */ public String toString() { return ISODateTimeFormat.tTime().print(this); } //----------------------------------------------------------------------- /** * The property class for TimeOfDay. *

* This class binds a TimeOfDay to a DateTimeField. * * @author Stephen Colebourne * @since 1.0 * @deprecated Use LocalTime which has a much better internal implementation */ @Deprecated public static class Property extends AbstractPartialFieldProperty implements Serializable { /** Serialization version */ private static final long serialVersionUID = 5598459141741063833L; /** The partial */ private final TimeOfDay iTimeOfDay; /** The field index */ private final int iFieldIndex; /** * Constructs a property. * * @param partial the partial instance * @param fieldIndex the index in the partial */ Property(TimeOfDay partial, int fieldIndex) { super(); iTimeOfDay = partial; iFieldIndex = fieldIndex; } /** * Gets the field that this property uses. * * @return the field */ public DateTimeField getField() { return iTimeOfDay.getField(iFieldIndex); } /** * Gets the partial that this property belongs to. * * @return the partial */ protected ReadablePartial getReadablePartial() { return iTimeOfDay; } /** * Gets the partial that this property belongs to. * * @return the partial */ public TimeOfDay getTimeOfDay() { return iTimeOfDay; } /** * Gets the value of this field. * * @return the field value */ public int get() { return iTimeOfDay.getValue(iFieldIndex); } //----------------------------------------------------------------------- /** * Adds to the value of this field in a copy of this TimeOfDay, * wrapping to what would be the next day if necessary. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it will affect larger fields. * Smaller fields are unaffected. *

* If the result would be too large, beyond 23:59:59:999, then the * calculation wraps to 00:00:00.000. For the alternate strict behaviour * with no wrapping see {@link #addNoWrapToCopy(int)}. *

* The TimeOfDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the TimeOfDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public TimeOfDay addToCopy(int valueToAdd) { int[] newValues = iTimeOfDay.getValues(); newValues = getField().addWrapPartial(iTimeOfDay, iFieldIndex, newValues, valueToAdd); return new TimeOfDay(iTimeOfDay, newValues); } /** * Adds to the value of this field in a copy of this TimeOfDay, * throwing an Exception if the bounds are exceeded. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it will affect larger fields. * Smaller fields are unaffected. *

* If the result would be too large (beyond 23:59:59:999) or too * small (less than 00:00:00.000) then an Execption is thrown. * For the alternate behaviour which wraps to the next 'day', * see {@link #addToCopy(int)}. *

* The TimeOfDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the TimeOfDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public TimeOfDay addNoWrapToCopy(int valueToAdd) { int[] newValues = iTimeOfDay.getValues(); newValues = getField().add(iTimeOfDay, iFieldIndex, newValues, valueToAdd); return new TimeOfDay(iTimeOfDay, newValues); } /** * Adds to the value of this field in a copy of this TimeOfDay wrapping * within this field if the maximum value is reached. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps within this field. * Other fields are unaffected. *

* For example, * 12:59:37 addWrapField one minute returns 12:00:37. *

* The TimeOfDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the TimeOfDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public TimeOfDay addWrapFieldToCopy(int valueToAdd) { int[] newValues = iTimeOfDay.getValues(); newValues = getField().addWrapField(iTimeOfDay, iFieldIndex, newValues, valueToAdd); return new TimeOfDay(iTimeOfDay, newValues); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the TimeOfDay. *

* The TimeOfDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param value the value to set the field in the copy to * @return a copy of the TimeOfDay with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public TimeOfDay setCopy(int value) { int[] newValues = iTimeOfDay.getValues(); newValues = getField().set(iTimeOfDay, iFieldIndex, newValues, value); return new TimeOfDay(iTimeOfDay, newValues); } /** * Sets this field in a copy of the TimeOfDay to a parsed text value. *

* The TimeOfDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the TimeOfDay with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public TimeOfDay setCopy(String text, Locale locale) { int[] newValues = iTimeOfDay.getValues(); newValues = getField().set(iTimeOfDay, iFieldIndex, newValues, text, locale); return new TimeOfDay(iTimeOfDay, newValues); } /** * Sets this field in a copy of the TimeOfDay to a parsed text value. *

* The TimeOfDay attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @return a copy of the TimeOfDay with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public TimeOfDay setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new TimeOfDay with this field set to the maximum value * for this field. *

* The TimeOfDay attached to this property is unchanged by this call. * * @return a copy of the TimeOfDay with this field set to its maximum * @since 1.2 */ public TimeOfDay withMaximumValue() { return setCopy(getMaximumValue()); } /** * Returns a new TimeOfDay with this field set to the minimum value * for this field. *

* The TimeOfDay attached to this property is unchanged by this call. * * @return a copy of the TimeOfDay with this field set to its minimum * @since 1.2 */ public TimeOfDay withMinimumValue() { return setCopy(getMinimumValue()); } } } joda-time-2.3/src/main/java/org/joda/time/ReadableDuration.java0000644000175000017500000001400011564251363023726 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines an exact duration of time in milliseconds. *

* The implementation of this interface may be mutable or immutable. This * interface only gives access to retrieve data, never to change it. *

* Methods that are passed a duration as a parameter will treat null * as a zero length duration. *

* The {@code compareTo} method is no longer defined in this class in version 2.0. * Instead, the definition is simply inherited from the {@code Comparable} interface. * This approach is necessary to preserve binary compatibility. * The definition of the comparison is ascending order by millisecond duration. * Implementors are recommended to extend {@code AbstractInstant} instead of this interface. * * @see ReadableInterval * @see ReadablePeriod * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public interface ReadableDuration extends Comparable { /** * Gets the total length of this duration in milliseconds. * * @return the total length of the time duration in milliseconds. */ long getMillis(); //----------------------------------------------------------------------- /** * Get this duration as an immutable Duration object. *

* This will either typecast this instance, or create a new Duration. * * @return a Duration created using the millisecond duration from this instance */ Duration toDuration(); //----------------------------------------------------------------------- /** * Converts this duration to a Period instance using the standard period type * and the ISO chronology. *

* Only precise fields in the period type will be used. Thus, only the hour, * minute, second and millisecond fields on the period will be used. * The year, month, week and day fields will not be populated. *

* If the duration is small, less than one day, then this method will perform * as you might expect and split the fields evenly. * If the duration is larger than one day then all the remaining duration will * be stored in the largest available field, hours in this case. *

* For example, a duration effectively equal to (365 + 60 + 5) days will be * converted to ((365 + 60 + 5) * 24) hours by this constructor. *

* For more control over the conversion process, you must pair the duration with * an instant, see {@link Period#Period(ReadableInstant,ReadableDuration)}. * * @return a Period created using the millisecond duration from this instance */ Period toPeriod(); //----------------------------------------------------------------------- // Method is no longer defined here as that would break generic backwards compatibility // /** // * Compares this duration with the specified duration based on length. // * // * @param obj a duration to check against // * @return negative value if this is less, 0 if equal, or positive value if greater // * @throws NullPointerException if the object is null // * @throws ClassCastException if the given object is not supported // */ // int compareTo(ReadableDuration obj); /** * Is the length of this duration equal to the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ boolean isEqual(ReadableDuration duration); /** * Is the length of this duration longer than the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ boolean isLongerThan(ReadableDuration duration); /** * Is the length of this duration shorter than the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ boolean isShorterThan(ReadableDuration duration); //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the millisecond length. All ReadableDuration instances are accepted. * * @param readableDuration a readable duration to check against * @return true if the length of the duration is equal */ boolean equals(Object readableDuration); /** * Gets a hash code for the duration that is compatable with the * equals method. * The following formula must be used: *

     *  long len = getMillis();
     *  return (int) (len ^ (len >>> 32));
     * 
* * @return a hash code */ int hashCode(); //----------------------------------------------------------------------- /** * Gets the value as a String in the ISO8601 duration format using hours, * minutes and seconds (including fractional milliseconds). *

* For example, "PT6H3M7S" represents 6 hours, 3 minutes, 7 seconds. * * @return the value as an ISO8601 string */ String toString(); } joda-time-2.3/src/main/java/org/joda/time/LocalTime.java0000644000175000017500000017360312111376463022407 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseLocal; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.PartialConverter; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * LocalTime is an immutable time class representing a time * without a time zone. *

* LocalTime implements the {@link ReadablePartial} interface. * To do this, the interface methods focus on the key fields - * HourOfDay, MinuteOfHour, SecondOfMinute and MillisOfSecond. * However, all time fields may in fact be queried. *

* Calculations on LocalTime are performed using a {@link Chronology}. * This chronology will be set internally to be in the UTC time zone * for all calculations. * *

Each individual field can be queried in two ways: *

    *
  • getHourOfDay() *
  • hourOfDay().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value *
  • text value *
  • short text value *
  • maximum/minimum values *
  • add/subtract *
  • set *
  • rounding *
* *

* LocalTime is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @since 1.3 */ public final class LocalTime extends BaseLocal implements ReadablePartial, Serializable { /** Serialization lock */ private static final long serialVersionUID = -12873158713873L; /** Constant for midnight. */ public static final LocalTime MIDNIGHT = new LocalTime(0, 0, 0, 0); /** The index of the hourOfDay field in the field array */ private static final int HOUR_OF_DAY = 0; /** The index of the minuteOfHour field in the field array */ private static final int MINUTE_OF_HOUR = 1; /** The index of the secondOfMinute field in the field array */ private static final int SECOND_OF_MINUTE = 2; /** The index of the millisOfSecond field in the field array */ private static final int MILLIS_OF_SECOND = 3; /** Set of known duration types. */ private static final Set TIME_DURATION_TYPES = new HashSet(); static { TIME_DURATION_TYPES.add(DurationFieldType.millis()); TIME_DURATION_TYPES.add(DurationFieldType.seconds()); TIME_DURATION_TYPES.add(DurationFieldType.minutes()); TIME_DURATION_TYPES.add(DurationFieldType.hours()); } /** The local millis from 1970-01-01T00:00:00 */ private final long iLocalMillis; /** The chronology to use, in UTC */ private final Chronology iChronology; //----------------------------------------------------------------------- /** * Obtains a {@code LocalTime} set to the current system millisecond time * using ISOChronology in the default time zone. * The resulting object does not use the zone. * * @return the current time, not null * @since 2.0 */ public static LocalTime now() { return new LocalTime(); } /** * Obtains a {@code LocalTime} set to the current system millisecond time * using ISOChronology in the specified time zone. * The resulting object does not use the zone. * * @param zone the time zone, not null * @return the current time, not null * @since 2.0 */ public static LocalTime now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new LocalTime(zone); } /** * Obtains a {@code LocalTime} set to the current system millisecond time * using the specified chronology. * The resulting object does not use the zone. * * @param chronology the chronology, not null * @return the current time, not null * @since 2.0 */ public static LocalTime now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new LocalTime(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code LocalTime} from the specified string. *

* This uses {@link ISODateTimeFormat#localTimeParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static LocalTime parse(String str) { return parse(str, ISODateTimeFormat.localTimeParser()); } /** * Parses a {@code LocalTime} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static LocalTime parse(String str, DateTimeFormatter formatter) { return formatter.parseLocalTime(str); } //----------------------------------------------------------------------- /** * Constructs a LocalTime from the specified millis of day using the * ISO chronology. *

* The millisOfDay value may exceed the number of millis in one day, * but additional days will be ignored. * This method uses the UTC time zone internally. * * @param millisOfDay the number of milliseconds into a day to convert */ public static LocalTime fromMillisOfDay(long millisOfDay) { return fromMillisOfDay(millisOfDay, null); } /** * Constructs a LocalTime from the specified millis of day using the * specified chronology. *

* The millisOfDay value may exceed the number of millis in one day, * but additional days will be ignored. * This method uses the UTC time zone internally. * * @param millisOfDay the number of milliseconds into a day to convert * @param chrono the chronology, null means ISO chronology */ public static LocalTime fromMillisOfDay(long millisOfDay, Chronology chrono) { chrono = DateTimeUtils.getChronology(chrono).withUTC(); return new LocalTime(millisOfDay, chrono); } //----------------------------------------------------------------------- /** * Constructs a LocalTime from a java.util.Calendar * using exactly the same field values. *

* Each field is queried from the Calendar and assigned to the LocalTime. * This is useful if you have been using the Calendar as a local time, * ignoring the zone. *

* One advantage of this method is that this method is unaffected if the * version of the time zone data differs between the JDK and Joda-Time. * That is because the local field values are transferred, calculated using * the JDK time zone data and without using the Joda-Time time zone data. *

* This factory method ignores the type of the calendar and always * creates a LocalTime with ISO chronology. It is expected that you * will only pass in instances of GregorianCalendar however * this is not validated. * * @param calendar the Calendar to extract fields from * @return the created LocalTime * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology */ public static LocalTime fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } return new LocalTime( calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), calendar.get(Calendar.MILLISECOND) ); } /** * Constructs a LocalTime from a java.util.Date * using exactly the same field values. *

* Each field is queried from the Date and assigned to the LocalTime. * This is useful if you have been using the Date as a local time, * ignoring the zone. *

* One advantage of this method is that this method is unaffected if the * version of the time zone data differs between the JDK and Joda-Time. * That is because the local field values are transferred, calculated using * the JDK time zone data and without using the Joda-Time time zone data. *

* This factory method always creates a LocalTime with ISO chronology. * * @param date the Date to extract fields from * @return the created LocalTime * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology */ @SuppressWarnings("deprecation") public static LocalTime fromDateFields(Date date) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } return new LocalTime( date.getHours(), date.getMinutes(), date.getSeconds(), (((int) (date.getTime() % 1000)) + 1000) % 1000 ); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current local time evaluated using * ISO chronology in the default zone. *

* Once the constructor is completed, the zone is no longer used. * * @see #now() */ public LocalTime() { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance()); } /** * Constructs an instance set to the current local time evaluated using * ISO chronology in the specified zone. *

* If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param zone the time zone, null means default zone * @see #now(DateTimeZone) */ public LocalTime(DateTimeZone zone) { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the current local time evaluated using * specified chronology and zone. *

* If the chronology is null, ISO chronology in the default time zone is used. * Once the constructor is completed, the zone is no longer used. * * @param chronology the chronology, null means ISOChronology in default zone * @see #now(Chronology) */ public LocalTime(Chronology chronology) { this(DateTimeUtils.currentTimeMillis(), chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the local time defined by the specified * instant evaluated using ISO chronology in the default zone. *

* Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public LocalTime(long instant) { this(instant, ISOChronology.getInstance()); } /** * Constructs an instance set to the local time defined by the specified * instant evaluated using ISO chronology in the specified zone. *

* If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public LocalTime(long instant, DateTimeZone zone) { this(instant, ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the local time defined by the specified * instant evaluated using the specified chronology. *

* If the chronology is null, ISO chronology in the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public LocalTime(long instant, Chronology chronology) { chronology = DateTimeUtils.getChronology(chronology); long localMillis = chronology.getZone().getMillisKeepLocal(DateTimeZone.UTC, instant); chronology = chronology.withUTC(); iLocalMillis = chronology.millisOfDay().get(localMillis); iChronology = chronology; } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime. *

* If the object contains no chronology, ISOChronology is used. * If the object contains no time zone, the default zone is used. * Once the constructor is completed, the zone is no longer used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localTimeParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @throws IllegalArgumentException if the instant is invalid */ public LocalTime(Object instant) { this(instant, (Chronology) null); } /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. *

* If the object contains no chronology, ISOChronology is used. * If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localTimeParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @param zone the time zone * @throws IllegalArgumentException if the instant is invalid */ public LocalTime(Object instant, DateTimeZone zone) { PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); Chronology chronology = converter.getChronology(instant, zone); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); int[] values = converter.getPartialValues(this, instant, chronology, ISODateTimeFormat.localTimeParser()); iLocalMillis = iChronology.getDateTimeMillis(0L, values[0], values[1], values[2], values[3]); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. *

* If the chronology is null, ISO in the default time zone is used. * Once the constructor is completed, the zone is no longer used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localTimeParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @param chronology the chronology * @throws IllegalArgumentException if the instant is invalid */ public LocalTime(Object instant, Chronology chronology) { PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); chronology = converter.getChronology(instant, chronology); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); int[] values = converter.getPartialValues(this, instant, chronology, ISODateTimeFormat.localTimeParser()); iLocalMillis = iChronology.getDateTimeMillis(0L, values[0], values[1], values[2], values[3]); } //----------------------------------------------------------------------- /** * Constructs an instance set to the specified time * using ISOChronology. * * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 */ public LocalTime( int hourOfDay, int minuteOfHour) { this(hourOfDay, minuteOfHour, 0, 0, ISOChronology.getInstanceUTC()); } /** * Constructs an instance set to the specified time * using ISOChronology. * * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 */ public LocalTime( int hourOfDay, int minuteOfHour, int secondOfMinute) { this(hourOfDay, minuteOfHour, secondOfMinute, 0, ISOChronology.getInstanceUTC()); } /** * Constructs an instance set to the specified time * using ISOChronology. * * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 * @param millisOfSecond the millisecond of the second, from 0 to 999 */ public LocalTime( int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { this(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, ISOChronology.getInstanceUTC()); } /** * Constructs an instance set to the specified time * using the specified chronology, whose zone is ignored. *

* If the chronology is null, ISOChronology is used. * * @param hourOfDay the hour of the day, valid values defined by the chronology * @param minuteOfHour the minute of the hour, valid values defined by the chronology * @param secondOfMinute the second of the minute, valid values defined by the chronology * @param millisOfSecond the millisecond of the second, valid values defined by the chronology * @param chronology the chronology, null means ISOChronology in default zone */ public LocalTime( int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(); chronology = DateTimeUtils.getChronology(chronology).withUTC(); long instant = chronology.getDateTimeMillis( 0L, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); iChronology = chronology; iLocalMillis = instant; } /** * Handle broken serialization from other tools. * @return the resolved object, not null */ private Object readResolve() { if (iChronology == null) { return new LocalTime(iLocalMillis, ISOChronology.getInstanceUTC()); } if (DateTimeZone.UTC.equals(iChronology.getZone()) == false) { return new LocalTime(iLocalMillis, iChronology.withUTC()); } return this; } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial, which is four. * The supported fields are HourOfDay, MinuteOfHour, SecondOfMinute * and MillisOfSecond. * * @return the field count, four */ public int size() { return 4; } /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field */ protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case HOUR_OF_DAY: return chrono.hourOfDay(); case MINUTE_OF_HOUR: return chrono.minuteOfHour(); case SECOND_OF_MINUTE: return chrono.secondOfMinute(); case MILLIS_OF_SECOND: return chrono.millisOfSecond(); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } /** * Gets the value of the field at the specifed index. *

* This method is required to support the ReadablePartial * interface. The supported fields are HourOfDay, MinuteOfHour, * SecondOfMinute and MillisOfSecond. * * @param index the index, zero to three * @return the value * @throws IndexOutOfBoundsException if the index is invalid */ public int getValue(int index) { switch (index) { case HOUR_OF_DAY: return getChronology().hourOfDay().get(getLocalMillis()); case MINUTE_OF_HOUR: return getChronology().minuteOfHour().get(getLocalMillis()); case SECOND_OF_MINUTE: return getChronology().secondOfMinute().get(getLocalMillis()); case MILLIS_OF_SECOND: return getChronology().millisOfSecond().get(getLocalMillis()); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } //----------------------------------------------------------------------- /** * Get the value of one of the fields of time. *

* This method gets the value of the specified field. * For example: *

     * DateTime dt = new DateTime();
     * int hourOfDay = dt.get(DateTimeFieldType.hourOfDay());
     * 
* * @param fieldType a field type, usually obtained from DateTimeFieldType, not null * @return the value of that field * @throws IllegalArgumentException if the field type is null */ public int get(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } return fieldType.getField(getChronology()).get(getLocalMillis()); } /** * Checks if the field type specified is supported by this * local time and chronology. * This can be used to avoid exceptions in {@link #get(DateTimeFieldType)}. * * @param type a field type, usually obtained from DateTimeFieldType * @return true if the field type is supported */ public boolean isSupported(DateTimeFieldType type) { if (type == null) { return false; } if (isSupported(type.getDurationType()) == false) { return false; } DurationFieldType range = type.getRangeDurationType(); return (isSupported(range) || range == DurationFieldType.days()); } /** * Checks if the duration type specified is supported by this * local time and chronology. * * @param type a duration type, usually obtained from DurationFieldType * @return true if the field type is supported */ public boolean isSupported(DurationFieldType type) { if (type == null) { return false; } DurationField field = type.getField(getChronology()); if (TIME_DURATION_TYPES.contains(type) || field.getUnitMillis() < getChronology().days().getUnitMillis()) { return field.isSupported(); } return false; } //----------------------------------------------------------------------- /** * Gets the local milliseconds from the Java epoch * of 1970-01-01T00:00:00 (not fixed to any specific time zone). * * @return the number of milliseconds since 1970-01-01T00:00:00 * @since 1.5 (previously private) */ protected long getLocalMillis() { return iLocalMillis; } /** * Gets the chronology of the time. * * @return the Chronology that the time is using */ public Chronology getChronology() { return iChronology; } //----------------------------------------------------------------------- /** * Compares this ReadablePartial with another returning true if the chronology, * field types and values are equal. * * @param partial an object to check against * @return true if fields and values are equal */ public boolean equals(Object partial) { // override to perform faster if (this == partial) { return true; } if (partial instanceof LocalTime) { LocalTime other = (LocalTime) partial; if (iChronology.equals(other.iChronology)) { return iLocalMillis == other.iLocalMillis; } } return super.equals(partial); } /** * Compares this partial with another returning an integer * indicating the order. *

* The fields are compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. *

* The specified object must be a partial instance whose field types * match those of this partial. * * @param partial an object to check against * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the partial is the wrong class * or if it has field types that don't match * @throws NullPointerException if the partial is null */ public int compareTo(ReadablePartial partial) { // override to perform faster if (this == partial) { return 0; } if (partial instanceof LocalTime) { LocalTime other = (LocalTime) partial; if (iChronology.equals(other.iChronology)) { return (iLocalMillis < other.iLocalMillis ? -1 : (iLocalMillis == other.iLocalMillis ? 0 : 1)); } } return super.compareTo(partial); } //----------------------------------------------------------------------- /** * Returns a copy of this time with different local millis. *

* The returned object will be a new instance of the same type. * Only the millis will change, the chronology is kept. * The returned object will be either be a new instance or this. * * @param newMillis the new millis, from 1970-01-01T00:00:00 * @return a copy of this time with different millis */ LocalTime withLocalMillis(long newMillis) { return (newMillis == getLocalMillis() ? this : new LocalTime(newMillis, getChronology())); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the partial set of fields replacing * those from this instance. *

* For example, if the partial contains an hour and minute then those two * fields will be changed in the returned instance. * Unsupported fields are ignored. * If the partial is null, then this is returned. * * @param partial the partial set of fields to apply to this time, null ignored * @return a copy of this time with a different set of fields * @throws IllegalArgumentException if any value is invalid */ public LocalTime withFields(ReadablePartial partial) { if (partial == null) { return this; } return withLocalMillis(getChronology().set(partial, getLocalMillis())); } /** * Returns a copy of this time with the specified field set * to a new value. *

* For example, if the field type is hourOfDay then the hour of day * field would be changed in the returned instance. * If the field type is null, then this is returned. *

* These lines are equivalent: *

     * LocalTime updated = dt.withHourOfDay(6);
     * LocalTime updated = dt.withField(DateTimeFieldType.hourOfDay(), 6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this time with the field set * @throws IllegalArgumentException if the value is null or invalid */ public LocalTime withField(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } long instant = fieldType.getField(getChronology()).set(getLocalMillis(), value); return withLocalMillis(instant); } /** * Returns a copy of this time with the value of the specified * field increased. *

* If the addition is zero or the field is null, then this * is returned. *

* If the addition causes the maximum value of the field to be exceeded, * then the value will wrap. Thus 23:59 plus two minutes yields 00:01. *

* These lines are equivalent: *

     * LocalTime added = dt.plusHours(6);
     * LocalTime added = dt.withFieldAdded(DurationFieldType.hours(), 6);
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this time with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalTime withFieldAdded(DurationFieldType fieldType, int amount) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } if (amount == 0) { return this; } long instant = fieldType.getField(getChronology()).add(getLocalMillis(), amount); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the specified period added. *

* If the addition is zero, then this is returned. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusHours(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this time with the period added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalTime withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getChronology().add(period, getLocalMillis(), scalar); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the specified period added. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusHours(int)}. * * @param period the period to add to this one, null means zero * @return a copy of this time with the period added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalTime plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this time plus the specified number of hours. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime added = dt.plusHours(6);
     * LocalTime added = dt.plus(Period.hours(6));
     * LocalTime added = dt.withFieldAdded(DurationFieldType.hours(), 6);
     * 
* * @param hours the amount of hours to add, may be negative * @return the new LocalTime plus the increased hours */ public LocalTime plusHours(int hours) { if (hours == 0) { return this; } long instant = getChronology().hours().add(getLocalMillis(), hours); return withLocalMillis(instant); } /** * Returns a copy of this time plus the specified number of minutes. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime added = dt.plusMinutes(6);
     * LocalTime added = dt.plus(Period.minutes(6));
     * LocalTime added = dt.withFieldAdded(DurationFieldType.minutes(), 6);
     * 
* * @param minutes the amount of minutes to add, may be negative * @return the new LocalTime plus the increased minutes */ public LocalTime plusMinutes(int minutes) { if (minutes == 0) { return this; } long instant = getChronology().minutes().add(getLocalMillis(), minutes); return withLocalMillis(instant); } /** * Returns a copy of this time plus the specified number of seconds. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime added = dt.plusSeconds(6);
     * LocalTime added = dt.plus(Period.seconds(6));
     * LocalTime added = dt.withFieldAdded(DurationFieldType.seconds(), 6);
     * 
* * @param seconds the amount of seconds to add, may be negative * @return the new LocalTime plus the increased seconds */ public LocalTime plusSeconds(int seconds) { if (seconds == 0) { return this; } long instant = getChronology().seconds().add(getLocalMillis(), seconds); return withLocalMillis(instant); } /** * Returns a copy of this time plus the specified number of millis. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime added = dt.plusMillis(6);
     * LocalTime added = dt.plus(Period.millis(6));
     * LocalTime added = dt.withFieldAdded(DurationFieldType.millis(), 6);
     * 
* * @param millis the amount of millis to add, may be negative * @return the new LocalTime plus the increased millis */ public LocalTime plusMillis(int millis) { if (millis == 0) { return this; } long instant = getChronology().millis().add(getLocalMillis(), millis); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the specified period taken away. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusHours(int)}. * * @param period the period to reduce this instant by * @return a copy of this time with the period taken away * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalTime minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this time minus the specified number of hours. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime subtracted = dt.minusHours(6);
     * LocalTime subtracted = dt.minus(Period.hours(6));
     * LocalTime subtracted = dt.withFieldAdded(DurationFieldType.hours(), -6);
     * 
* * @param hours the amount of hours to subtract, may be negative * @return the new LocalTime minus the increased hours */ public LocalTime minusHours(int hours) { if (hours == 0) { return this; } long instant = getChronology().hours().subtract(getLocalMillis(), hours); return withLocalMillis(instant); } /** * Returns a copy of this time minus the specified number of minutes. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime subtracted = dt.minusMinutes(6);
     * LocalTime subtracted = dt.minus(Period.minutes(6));
     * LocalTime subtracted = dt.withFieldAdded(DurationFieldType.minutes(), -6);
     * 
* * @param minutes the amount of minutes to subtract, may be negative * @return the new LocalTime minus the increased minutes */ public LocalTime minusMinutes(int minutes) { if (minutes == 0) { return this; } long instant = getChronology().minutes().subtract(getLocalMillis(), minutes); return withLocalMillis(instant); } /** * Returns a copy of this time minus the specified number of seconds. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime subtracted = dt.minusSeconds(6);
     * LocalTime subtracted = dt.minus(Period.seconds(6));
     * LocalTime subtracted = dt.withFieldAdded(DurationFieldType.seconds(), -6);
     * 
* * @param seconds the amount of seconds to subtract, may be negative * @return the new LocalTime minus the increased seconds */ public LocalTime minusSeconds(int seconds) { if (seconds == 0) { return this; } long instant = getChronology().seconds().subtract(getLocalMillis(), seconds); return withLocalMillis(instant); } /** * Returns a copy of this time minus the specified number of millis. *

* This LocalTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalTime subtracted = dt.minusMillis(6);
     * LocalTime subtracted = dt.minus(Period.millis(6));
     * LocalTime subtracted = dt.withFieldAdded(DurationFieldType.millis(), -6);
     * 
* * @param millis the amount of millis to subtract, may be negative * @return the new LocalTime minus the increased millis */ public LocalTime minusMillis(int millis) { if (millis == 0) { return this; } long instant = getChronology().millis().subtract(getLocalMillis(), millis); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains * many useful methods. * * @param fieldType the field type to get the chronology for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } return new Property(this, fieldType.getField(getChronology())); } //----------------------------------------------------------------------- /** * Get the hour of day field value. * * @return the hour of day */ public int getHourOfDay() { return getChronology().hourOfDay().get(getLocalMillis()); } /** * Get the minute of hour field value. * * @return the minute of hour */ public int getMinuteOfHour() { return getChronology().minuteOfHour().get(getLocalMillis()); } /** * Get the second of minute field value. * * @return the second of minute */ public int getSecondOfMinute() { return getChronology().secondOfMinute().get(getLocalMillis()); } /** * Get the millis of second field value. * * @return the millis of second */ public int getMillisOfSecond() { return getChronology().millisOfSecond().get(getLocalMillis()); } /** * Get the millis of day field value. * * @return the millis of day */ public int getMillisOfDay() { return getChronology().millisOfDay().get(getLocalMillis()); } //----------------------------------------------------------------------- /** * Returns a copy of this time with the hour of day field updated. *

* LocalTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * hour of day changed. * * @param hour the hour of day to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalTime withHourOfDay(int hour) { return withLocalMillis(getChronology().hourOfDay().set(getLocalMillis(), hour)); } /** * Returns a copy of this time with the minute of hour field updated. *

* LocalTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * minute of hour changed. * * @param minute the minute of hour to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalTime withMinuteOfHour(int minute) { return withLocalMillis(getChronology().minuteOfHour().set(getLocalMillis(), minute)); } /** * Returns a copy of this time with the second of minute field updated. *

* LocalTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * second of minute changed. * * @param second the second of minute to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalTime withSecondOfMinute(int second) { return withLocalMillis(getChronology().secondOfMinute().set(getLocalMillis(), second)); } /** * Returns a copy of this time with the millis of second field updated. *

* LocalTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * millis of second changed. * * @param millis the millis of second to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalTime withMillisOfSecond(int millis) { return withLocalMillis(getChronology().millisOfSecond().set(getLocalMillis(), millis)); } /** * Returns a copy of this time with the millis of day field updated. *

* LocalTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * millis of day changed. * * @param millis the millis of day to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalTime withMillisOfDay(int millis) { return withLocalMillis(getChronology().millisOfDay().set(getLocalMillis(), millis)); } //----------------------------------------------------------------------- /** * Get the hour of day field property which provides access to advanced functionality. * * @return the hour of day property */ public Property hourOfDay() { return new Property(this, getChronology().hourOfDay()); } /** * Get the minute of hour field property which provides access to advanced functionality. * * @return the minute of hour property */ public Property minuteOfHour() { return new Property(this, getChronology().minuteOfHour()); } /** * Get the second of minute field property which provides access to advanced functionality. * * @return the second of minute property */ public Property secondOfMinute() { return new Property(this, getChronology().secondOfMinute()); } /** * Get the millis of second property which provides access to advanced functionality. * * @return the millis of second property */ public Property millisOfSecond() { return new Property(this, getChronology().millisOfSecond()); } /** * Get the millis of day property which provides access to advanced functionality. * * @return the millis of day property */ public Property millisOfDay() { return new Property(this, getChronology().millisOfDay()); } //----------------------------------------------------------------------- /** * Converts this LocalTime to a full datetime using the default time zone * setting the time fields from this instance and the date fields from * the current date. * * @return this time as a datetime using todays date */ public DateTime toDateTimeToday() { return toDateTimeToday(null); } /** * Converts this LocalTime to a full datetime using the specified time zone * setting the time fields from this instance and the date fields from * the current time. *

* This method uses the chronology from this instance plus the time zone * specified. * * @param zone the zone to use, null means default * @return this time as a datetime using todays date */ public DateTime toDateTimeToday(DateTimeZone zone) { Chronology chrono = getChronology().withZone(zone); long instantMillis = DateTimeUtils.currentTimeMillis(); long resolved = chrono.set(this, instantMillis); return new DateTime(resolved, chrono); } //----------------------------------------------------------------------- /** * Output the time in ISO8601 format (HH:mm:ss.SSS). * * @return ISO8601 time formatted string. */ @ToString public String toString() { return ISODateTimeFormat.time().print(this); } /** * Output the time using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the time using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) throws IllegalArgumentException { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } //----------------------------------------------------------------------- /** * LocalTime.Property binds a LocalTime to a DateTimeField allowing * powerful datetime functionality to be easily accessed. *

* The simplest use of this class is as an alternative get method, here used to * get the minute '30'. *

     * LocalTime dt = new LocalTime(12, 30);
     * int year = dt.minuteOfHour().get();
     * 
*

* Methods are also provided that allow time modification. These return * new instances of LocalTime - they do not modify the original. The example * below yields two independent immutable date objects 2 hours apart. *

     * LocalTime dt1230 = new LocalTime(12, 30);
     * LocalTime dt1430 = dt1230.hourOfDay().setCopy(14);
     * 
*

* LocalTime.Property itself is thread-safe and immutable, as well as the * LocalTime being operated on. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.3 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization version */ private static final long serialVersionUID = -325842547277223L; /** The instant this property is working against */ private transient LocalTime iInstant; /** The field this property is working against */ private transient DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(LocalTime instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Writes the property in a safe serialization format. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(iInstant); oos.writeObject(iField.getType()); } /** * Reads the property from a safe serialization format. */ private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException { iInstant = (LocalTime) oos.readObject(); DateTimeFieldType type = (DateTimeFieldType) oos.readObject(); iField = type.getField(iInstant.getChronology()); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the milliseconds of the time that this property is linked to. * * @return the milliseconds */ protected long getMillis() { return iInstant.getLocalMillis(); } /** * Gets the chronology of the datetime that this property is linked to. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { return iInstant.getChronology(); } /** * Gets the LocalTime object linked to this property. * * @return the linked LocalTime */ public LocalTime getLocalTime() { return iInstant; } //----------------------------------------------------------------------- /** * Adds to this field in a copy of this LocalTime. *

* The LocalTime attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalTime with the field value changed */ public LocalTime addCopy(int value) { return iInstant.withLocalMillis(iField.add(iInstant.getLocalMillis(), value)); } /** * Adds to this field in a copy of this LocalTime. * If the addition exceeds the maximum value (eg. 23:59) it will * wrap to the minimum value (eg. 00:00). *

* The LocalTime attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalTime with the field value changed */ public LocalTime addCopy(long value) { return iInstant.withLocalMillis(iField.add(iInstant.getLocalMillis(), value)); } /** * Adds to this field in a copy of this LocalTime. * If the addition exceeds the maximum value (eg. 23:59) then * an exception will be thrown. * Contrast this behaviour to {@link #addCopy(int)}. *

* The LocalTime attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalTime with the field value changed * @throws IllegalArgumentException if the result is invalid */ public LocalTime addNoWrapToCopy(int value) { long millis = iField.add(iInstant.getLocalMillis(), value); long rounded = iInstant.getChronology().millisOfDay().get(millis); if (rounded != millis) { throw new IllegalArgumentException("The addition exceeded the boundaries of LocalTime"); } return iInstant.withLocalMillis(millis); } /** * Adds to this field, possibly wrapped, in a copy of this LocalTime. * A field wrapped operation only changes this field. * Thus 10:59 plusWrapField one minute goes to 10:00. *

* The LocalTime attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalTime addWrapFieldToCopy(int value) { return iInstant.withLocalMillis(iField.addWrapField(iInstant.getLocalMillis(), value)); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the LocalTime. *

* The LocalTime attached to this property is unchanged by this call. * * @param value the value to set the field in the copy to * @return a copy of the LocalTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalTime setCopy(int value) { return iInstant.withLocalMillis(iField.set(iInstant.getLocalMillis(), value)); } /** * Sets this field in a copy of the LocalTime to a parsed text value. *

* The LocalTime attached to this property is unchanged by this call. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the LocalTime with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public LocalTime setCopy(String text, Locale locale) { return iInstant.withLocalMillis(iField.set(iInstant.getLocalMillis(), text, locale)); } /** * Sets this field in a copy of the LocalTime to a parsed text value. *

* The LocalTime attached to this property is unchanged by this call. * * @param text the text value to set * @return a copy of the LocalTime with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public LocalTime setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new LocalTime with this field set to the maximum value * for this field. *

* The LocalTime attached to this property is unchanged by this call. * * @return a copy of the LocalTime with this field set to its maximum */ public LocalTime withMaximumValue() { return setCopy(getMaximumValue()); } /** * Returns a new LocalTime with this field set to the minimum value * for this field. *

* The LocalTime attached to this property is unchanged by this call. * * @return a copy of the LocalTime with this field set to its minimum */ public LocalTime withMinimumValue() { return setCopy(getMinimumValue()); } //----------------------------------------------------------------------- /** * Rounds to the lowest whole unit of this field on a copy of this * LocalTime. *

* For example, rounding floor on the hourOfDay field of a LocalTime * where the time is 10:30 would result in new LocalTime with the * time of 10:00. * * @return a copy of the LocalTime with the field value changed */ public LocalTime roundFloorCopy() { return iInstant.withLocalMillis(iField.roundFloor(iInstant.getLocalMillis())); } /** * Rounds to the highest whole unit of this field on a copy of this * LocalTime. *

* For example, rounding floor on the hourOfDay field of a LocalTime * where the time is 10:30 would result in new LocalTime with the * time of 11:00. * * @return a copy of the LocalTime with the field value changed */ public LocalTime roundCeilingCopy() { return iInstant.withLocalMillis(iField.roundCeiling(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalTime, favoring the floor if halfway. * * @return a copy of the LocalTime with the field value changed */ public LocalTime roundHalfFloorCopy() { return iInstant.withLocalMillis(iField.roundHalfFloor(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalTime, favoring the ceiling if halfway. * * @return a copy of the LocalTime with the field value changed */ public LocalTime roundHalfCeilingCopy() { return iInstant.withLocalMillis(iField.roundHalfCeiling(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalTime. If halfway, the ceiling is favored over the floor * only if it makes this field's value even. * * @return a copy of the LocalTime with the field value changed */ public LocalTime roundHalfEvenCopy() { return iInstant.withLocalMillis(iField.roundHalfEven(iInstant.getLocalMillis())); } } } joda-time-2.3/src/main/java/org/joda/time/LocalDateTime.java0000644000175000017500000026756512200504400023177 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseLocal; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.PartialConverter; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * LocalDateTime is an unmodifiable datetime class representing a * datetime without a time zone. *

* LocalDateTime implements the {@link ReadablePartial} interface. * To do this, certain methods focus on key fields Year, MonthOfYear, * DayOfYear and MillisOfDay. * However, all fields may in fact be queried. *

* Internally, LocalDateTime uses a single millisecond-based value to * represent the local datetime. This value is only used internally and * is not exposed to applications. *

* Calculations on LocalDateTime are performed using a {@link Chronology}. * This chronology will be set internally to be in the UTC time zone * for all calculations. * *

Each individual field can be queried in two ways: *

    *
  • getHourOfDay() *
  • hourOfDay().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value *
  • text value *
  • short text value *
  • maximum/minimum values *
  • add/subtract *
  • set *
  • rounding *
* *

* LocalDateTime is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @since 1.3 */ public final class LocalDateTime extends BaseLocal implements ReadablePartial, Serializable { /** Serialization lock */ private static final long serialVersionUID = -268716875315837168L; /** The index of the year field in the field array */ private static final int YEAR = 0; /** The index of the monthOfYear field in the field array */ private static final int MONTH_OF_YEAR = 1; /** The index of the dayOfMonth field in the field array */ private static final int DAY_OF_MONTH = 2; /** The index of the millis field in the field array */ private static final int MILLIS_OF_DAY = 3; /** The local millis from 1970-01-01T00:00:00 */ private final long iLocalMillis; /** The chronology to use in UTC */ private final Chronology iChronology; //----------------------------------------------------------------------- /** * Obtains a {@code LocalDateTime} set to the current system millisecond time * using ISOChronology in the default time zone. * The resulting object does not use the zone. * * @return the current date, not null * @since 2.0 */ public static LocalDateTime now() { return new LocalDateTime(); } /** * Obtains a {@code LocalDateTime} set to the current system millisecond time * using ISOChronology in the specified time zone. * The resulting object does not use the zone. * * @param zone the time zone, not null * @return the current date, not null * @since 2.0 */ public static LocalDateTime now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new LocalDateTime(zone); } /** * Obtains a {@code LocalDateTime} set to the current system millisecond time * using the specified chronology. * The resulting object does not use the zone. * * @param chronology the chronology, not null * @return the current date, not null * @since 2.0 */ public static LocalDateTime now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new LocalDateTime(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code LocalDateTime} from the specified string. *

* This uses {@link ISODateTimeFormat#localDateOptionalTimeParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static LocalDateTime parse(String str) { return parse(str, ISODateTimeFormat.localDateOptionalTimeParser()); } /** * Parses a {@code LocalDateTime} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static LocalDateTime parse(String str, DateTimeFormatter formatter) { return formatter.parseLocalDateTime(str); } //----------------------------------------------------------------------- /** * Constructs a LocalDateTime from a java.util.Calendar * using exactly the same field values. *

* Each field is queried from the Calendar and assigned to the LocalDateTime. * This is useful if you have been using the Calendar as a local date, * ignoring the zone. *

* One advantage of this method is that this method is unaffected if the * version of the time zone data differs between the JDK and Joda-Time. * That is because the local field values are transferred, calculated using * the JDK time zone data and without using the Joda-Time time zone data. *

* This factory method ignores the type of the calendar and always * creates a LocalDateTime with ISO chronology. It is expected that you * will only pass in instances of GregorianCalendar however * this is not validated. * * @param calendar the Calendar to extract fields from, not null * @return the created local date-time, not null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology */ public static LocalDateTime fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } int era = calendar.get(Calendar.ERA); int yearOfEra = calendar.get(Calendar.YEAR); return new LocalDateTime( (era == GregorianCalendar.AD ? yearOfEra : 1 - yearOfEra), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), calendar.get(Calendar.MILLISECOND) ); } /** * Constructs a LocalDateTime from a java.util.Date * using exactly the same field values. *

* Each field is queried from the Date and assigned to the LocalDateTime. * This is useful if you have been using the Date as a local date, * ignoring the zone. *

* One advantage of this method is that this method is unaffected if the * version of the time zone data differs between the JDK and Joda-Time. * That is because the local field values are transferred, calculated using * the JDK time zone data and without using the Joda-Time time zone data. *

* This factory method always creates a LocalDateTime with ISO chronology. * * @param date the Date to extract fields from, not null * @return the created local date-time, not null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology */ @SuppressWarnings("deprecation") public static LocalDateTime fromDateFields(Date date) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } if (date.getTime() < 0) { // handle years in era BC GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); return fromCalendarFields(cal); } return new LocalDateTime( date.getYear() + 1900, date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), (((int) (date.getTime() % 1000)) + 1000) % 1000 ); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current local time evaluated using * ISO chronology in the default zone. *

* Once the constructor is completed, the zone is no longer used. * * @see #now() */ public LocalDateTime() { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance()); } /** * Constructs an instance set to the current local time evaluated using * ISO chronology in the specified zone. *

* If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param zone the time zone, null means default zone * @see #now(DateTimeZone) */ public LocalDateTime(DateTimeZone zone) { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the current local time evaluated using * specified chronology. *

* If the chronology is null, ISO chronology in the default time zone is used. * Once the constructor is completed, the zone is no longer used. * * @param chronology the chronology, null means ISOChronology in default zone * @see #now(Chronology) */ public LocalDateTime(Chronology chronology) { this(DateTimeUtils.currentTimeMillis(), chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the local time defined by the specified * instant evaluated using ISO chronology in the default zone. *

* Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public LocalDateTime(long instant) { this(instant, ISOChronology.getInstance()); } /** * Constructs an instance set to the local time defined by the specified * instant evaluated using ISO chronology in the specified zone. *

* If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public LocalDateTime(long instant, DateTimeZone zone) { this(instant, ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the local time defined by the specified * instant evaluated using the specified chronology. *

* If the chronology is null, ISO chronology in the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public LocalDateTime(long instant, Chronology chronology) { chronology = DateTimeUtils.getChronology(chronology); long localMillis = chronology.getZone().getMillisKeepLocal(DateTimeZone.UTC, instant); iLocalMillis = localMillis; iChronology = chronology.withUTC(); } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime. *

* If the object contains no chronology, ISOChronology is used. * If the object contains no time zone, the default zone is used. * Once the constructor is completed, the zone is no longer used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateOptionalTimeParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @throws IllegalArgumentException if the instant is invalid */ public LocalDateTime(Object instant) { this(instant, (Chronology) null); } /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. *

* If the object contains no chronology, ISOChronology is used. * If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateOptionalTimeParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @param zone the time zone * @throws IllegalArgumentException if the instant is invalid */ public LocalDateTime(Object instant, DateTimeZone zone) { PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); Chronology chronology = converter.getChronology(instant, zone); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); int[] values = converter.getPartialValues(this, instant, chronology, ISODateTimeFormat.localDateOptionalTimeParser()); iLocalMillis = iChronology.getDateTimeMillis(values[0], values[1], values[2], values[3]); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. *

* If the chronology is null, ISO in the default time zone is used. * Once the constructor is completed, the zone is no longer used. * If the instant contains a chronology, it will be ignored. * For example, passing a {@code LocalDate} and a different chronology * will return a date with the year/month/day from the date applied * unaltered to the specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateOptionalTimeParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @param chronology the chronology * @throws IllegalArgumentException if the instant is invalid */ public LocalDateTime(Object instant, Chronology chronology) { PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); chronology = converter.getChronology(instant, chronology); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); int[] values = converter.getPartialValues(this, instant, chronology, ISODateTimeFormat.localDateOptionalTimeParser()); iLocalMillis = iChronology.getDateTimeMillis(values[0], values[1], values[2], values[3]); } //----------------------------------------------------------------------- /** * Constructs an instance set to the specified date and time * using ISOChronology. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 */ public LocalDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour) { this(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, 0, 0, ISOChronology.getInstanceUTC()); } /** * Constructs an instance set to the specified date and time * using ISOChronology. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 */ public LocalDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute) { this(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, 0, ISOChronology.getInstanceUTC()); } /** * Constructs an instance set to the specified date and time * using ISOChronology. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 * @param millisOfSecond the millisecond of the second, from 0 to 999 */ public LocalDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { this(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, ISOChronology.getInstanceUTC()); } /** * Constructs an instance set to the specified date and time * using the specified chronology, whose zone is ignored. *

* If the chronology is null, ISOChronology is used. * * @param year the year, valid values defined by the chronology * @param monthOfYear the month of the year, valid values defined by the chronology * @param dayOfMonth the day of the month, valid values defined by the chronology * @param hourOfDay the hour of the day, valid values defined by the chronology * @param minuteOfHour the minute of the hour, valid values defined by the chronology * @param secondOfMinute the second of the minute, valid values defined by the chronology * @param millisOfSecond the millisecond of the second, valid values defined by the chronology * @param chronology the chronology, null means ISOChronology in default zone */ public LocalDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(); chronology = DateTimeUtils.getChronology(chronology).withUTC(); long instant = chronology.getDateTimeMillis(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); iChronology = chronology; iLocalMillis = instant; } /** * Handle broken serialization from other tools. * @return the resolved object, not null */ private Object readResolve() { if (iChronology == null) { return new LocalDateTime(iLocalMillis, ISOChronology.getInstanceUTC()); } if (DateTimeZone.UTC.equals(iChronology.getZone()) == false) { return new LocalDateTime(iLocalMillis, iChronology.withUTC()); } return this; } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial, which is four. * The supported fields are Year, MonthOfDay, DayOfMonth and MillisOfDay. * * @return the field count, four */ public int size() { return 4; } /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field */ protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case YEAR: return chrono.year(); case MONTH_OF_YEAR: return chrono.monthOfYear(); case DAY_OF_MONTH: return chrono.dayOfMonth(); case MILLIS_OF_DAY: return chrono.millisOfDay(); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } /** * Gets the value of the field at the specifed index. *

* This method is required to support the ReadablePartial * interface. The supported fields are Year, MonthOfDay, DayOfMonth and MillisOfDay. * * @param index the index, zero to two * @return the value * @throws IndexOutOfBoundsException if the index is invalid */ public int getValue(int index) { switch (index) { case YEAR: return getChronology().year().get(getLocalMillis()); case MONTH_OF_YEAR: return getChronology().monthOfYear().get(getLocalMillis()); case DAY_OF_MONTH: return getChronology().dayOfMonth().get(getLocalMillis()); case MILLIS_OF_DAY: return getChronology().millisOfDay().get(getLocalMillis()); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } //----------------------------------------------------------------------- /** * Get the value of one of the fields of a datetime. *

* This method gets the value of the specified field. * For example: *

     * DateTime dt = new DateTime();
     * int year = dt.get(DateTimeFieldType.year());
     * 
* * @param type a field type, usually obtained from DateTimeFieldType, not null * @return the value of that field * @throws IllegalArgumentException if the field type is null */ public int get(DateTimeFieldType type) { if (type == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } return type.getField(getChronology()).get(getLocalMillis()); } /** * Checks if the field type specified is supported by this * local datetime and chronology. * This can be used to avoid exceptions in {@link #get(DateTimeFieldType)}. * * @param type a field type, usually obtained from DateTimeFieldType * @return true if the field type is supported */ public boolean isSupported(DateTimeFieldType type) { if (type == null) { return false; } return type.getField(getChronology()).isSupported(); } /** * Checks if the duration type specified is supported by this * local datetime and chronology. * * @param type a duration type, usually obtained from DurationFieldType * @return true if the field type is supported */ public boolean isSupported(DurationFieldType type) { if (type == null) { return false; } return type.getField(getChronology()).isSupported(); } //----------------------------------------------------------------------- /** * Gets the milliseconds of the datetime instant from the Java epoch * of 1970-01-01T00:00:00 (not fixed to any specific time zone). * * @return the number of milliseconds since 1970-01-01T00:00:00 * @since 1.5 (previously private) */ protected long getLocalMillis() { return iLocalMillis; } /** * Gets the chronology of the datetime. * * @return the Chronology that the datetime is using */ public Chronology getChronology() { return iChronology; } //----------------------------------------------------------------------- /** * Compares this ReadablePartial with another returning true if the chronology, * field types and values are equal. * * @param partial an object to check against * @return true if fields and values are equal */ public boolean equals(Object partial) { // override to perform faster if (this == partial) { return true; } if (partial instanceof LocalDateTime) { LocalDateTime other = (LocalDateTime) partial; if (iChronology.equals(other.iChronology)) { return iLocalMillis == other.iLocalMillis; } } return super.equals(partial); } /** * Compares this partial with another returning an integer * indicating the order. *

* The fields are compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. *

* The specified object must be a partial instance whose field types * match those of this partial. * * @param partial an object to check against * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the partial is the wrong class * or if it has field types that don't match * @throws NullPointerException if the partial is null */ public int compareTo(ReadablePartial partial) { // override to perform faster if (this == partial) { return 0; } if (partial instanceof LocalDateTime) { LocalDateTime other = (LocalDateTime) partial; if (iChronology.equals(other.iChronology)) { return (iLocalMillis < other.iLocalMillis ? -1 : (iLocalMillis == other.iLocalMillis ? 0 : 1)); } } return super.compareTo(partial); } //----------------------------------------------------------------------- /** * Converts this object to a DateTime using the default zone. *

* This method will throw an exception if the datetime that would be * created does not exist when the time zone is taken into account. * * @return this */ public DateTime toDateTime() { return toDateTime((DateTimeZone) null); } /** * Converts this object to a DateTime using the specified zone. *

* This method will throw an exception if the datetime that would be * created does not exist when the time zone is taken into account. * * @param zone time zone to apply, or default if null * @return a DateTime using the same millis */ public DateTime toDateTime(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); Chronology chrono = iChronology.withZone(zone); return new DateTime( getYear(), getMonthOfYear(), getDayOfMonth(), getHourOfDay(), getMinuteOfHour(), getSecondOfMinute(), getMillisOfSecond(), chrono); } //----------------------------------------------------------------------- /** * Converts this object to a LocalDate with the same date and chronology. * * @return a LocalDate with the same date and chronology */ public LocalDate toLocalDate() { return new LocalDate(getLocalMillis(), getChronology()); } /** * Converts this object to a LocalTime with the same time and chronology. * * @return a LocalTime with the same time and chronology */ public LocalTime toLocalTime() { return new LocalTime(getLocalMillis(), getChronology()); } //----------------------------------------------------------------------- /** * Get the date time as a java.util.Date. *

* The Date object created has exactly the same fields as this * date-time, except when the time would be invalid due to a daylight savings * gap. In that case, the time will be set to the earliest valid time after the gap. *

* In the case of a daylight savings overlap, the earlier instant is selected. *

* Converting to a JDK Date is full of complications as the JDK Date constructor * doesn't behave as you might expect around DST transitions. This method works * by taking a first guess and then adjusting. This also handles the situation * where the JDK time zone data differs from the Joda-Time time zone data. * * @return a Date initialised with this date-time, never null * @since 2.0 */ @SuppressWarnings("deprecation") public Date toDate() { int dom = getDayOfMonth(); Date date = new Date(getYear() - 1900, getMonthOfYear() - 1, dom, getHourOfDay(), getMinuteOfHour(), getSecondOfMinute()); date.setTime(date.getTime() + getMillisOfSecond()); return correctDstTransition(date, TimeZone.getDefault()); } /** * Get the date time as a java.util.Date using the specified time zone. *

* The Date object created has exactly the same fields as this * date-time, except when the time would be invalid due to a daylight savings * gap. In that case, the time will be set to the earliest valid time after the gap. *

* In the case of a daylight savings overlap, the earlier instant is selected. *

* Converting to a JDK Date is full of complications as the JDK Date constructor * doesn't behave as you might expect around DST transitions. This method works * by taking a first guess and then adjusting. This also handles the situation * where the JDK time zone data differs from the Joda-Time time zone data. *

* Unlike {@link #toDate()}, this implementation does not rely on Java's synchronized * time zone initialization logic, and should demonstrate better concurrent performance * characteristics. * * @return a Date initialised with this date-time, never null * @since 2.3 */ public Date toDate(final TimeZone timeZone) { final Calendar calendar = Calendar.getInstance(timeZone); calendar.clear(); calendar.set(getYear(), getMonthOfYear() - 1, getDayOfMonth(), getHourOfDay(), getMinuteOfHour(), getSecondOfMinute()); Date date = calendar.getTime(); date.setTime(date.getTime() + getMillisOfSecond()); return correctDstTransition(date, timeZone); } /** * Correct date in case of DST overlap. *

* The Date object created has exactly the same fields as this * date-time, except when the time would be invalid due to a daylight savings * gap. In that case, the time will be set to the earliest valid time after the gap. *

* In the case of a daylight savings overlap, the earlier instant is selected. *

* Converting to a JDK Date is full of complications as the JDK Date constructor * doesn't behave as you might expect around DST transitions. This method works * by taking a first guess and then adjusting. This also handles the situation * where the JDK time zone data differs from the Joda-Time time zone data. * @see #toDate() */ private Date correctDstTransition(Date date, final TimeZone timeZone) { Calendar calendar = Calendar.getInstance(timeZone); calendar.setTime(date); LocalDateTime check = LocalDateTime.fromCalendarFields(calendar); if (check.isBefore(this)) { // DST gap // move forward in units of one minute until equal/after while (check.isBefore(this)) { calendar.setTimeInMillis(calendar.getTimeInMillis() + 60000); check = LocalDateTime.fromCalendarFields(calendar); } // move back in units of one second until date wrong while (check.isBefore(this) == false) { calendar.setTimeInMillis(calendar.getTimeInMillis() - 1000); check = LocalDateTime.fromCalendarFields(calendar); } calendar.setTimeInMillis(calendar.getTimeInMillis() + 1000); } else if (check.equals(this)) { // check for DST overlap final Calendar earlier = Calendar.getInstance(timeZone); earlier.setTimeInMillis(calendar.getTimeInMillis() - timeZone.getDSTSavings()); check = LocalDateTime.fromCalendarFields(earlier); if (check.equals(this)) { calendar = earlier; } } return calendar.getTime(); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with different local millis. *

* The returned object will be a new instance of the same type. * Only the millis will change, the chronology is kept. * The returned object will be either be a new instance or this. * * @param newMillis the new millis, from 1970-01-01T00:00:00 * @return a copy of this datetime with different millis */ LocalDateTime withLocalMillis(long newMillis) { return (newMillis == getLocalMillis() ? this : new LocalDateTime(newMillis, getChronology())); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified date, * retaining the time fields. *

* If the date is already the date passed in, then this is returned. *

* To set a single field use the properties, for example: *

     * DateTime set = dt.monthOfYear().setCopy(6);
     * 
* * @param year the new year value * @param monthOfYear the new monthOfYear value * @param dayOfMonth the new dayOfMonth value * @return a copy of this datetime with a different date * @throws IllegalArgumentException if any value if invalid */ public LocalDateTime withDate(int year, int monthOfYear, int dayOfMonth) { Chronology chrono = getChronology(); long instant = getLocalMillis(); instant = chrono.year().set(instant, year); instant = chrono.monthOfYear().set(instant, monthOfYear); instant = chrono.dayOfMonth().set(instant, dayOfMonth); return withLocalMillis(instant); } /** * Returns a copy of this datetime with the specified time, * retaining the date fields. *

* If the time is already the time passed in, then this is returned. *

* To set a single field use the properties, for example: *

     * LocalDateTime set = dt.hourOfDay().setCopy(6);
     * 
* * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @return a copy of this datetime with a different time * @throws IllegalArgumentException if any value if invalid */ public LocalDateTime withTime(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { Chronology chrono = getChronology(); long instant = getLocalMillis(); instant = chrono.hourOfDay().set(instant, hourOfDay); instant = chrono.minuteOfHour().set(instant, minuteOfHour); instant = chrono.secondOfMinute().set(instant, secondOfMinute); instant = chrono.millisOfSecond().set(instant, millisOfSecond); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the partial set of fields * replacing those from this instance. *

* For example, if the partial is a TimeOfDay then the time fields * would be changed in the returned instance. * If the partial is null, then this is returned. * * @param partial the partial set of fields to apply to this datetime, null ignored * @return a copy of this datetime with a different set of fields * @throws IllegalArgumentException if any value is invalid */ public LocalDateTime withFields(ReadablePartial partial) { if (partial == null) { return this; } return withLocalMillis(getChronology().set(partial, getLocalMillis())); } /** * Returns a copy of this datetime with the specified field set to a new value. *

* For example, if the field type is hourOfDay then the hour of day * field would be changed in the returned instance. * If the field type is null, then this is returned. *

* These three lines are equivalent: *

     * LocalDateTime updated = dt.withField(DateTimeFieldType.dayOfMonth(), 6);
     * LocalDateTime updated = dt.dayOfMonth().setCopy(6);
     * LocalDateTime updated = dt.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this datetime with the field set * @throws IllegalArgumentException if the value is null or invalid */ public LocalDateTime withField(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } long instant = fieldType.getField(getChronology()).set(getLocalMillis(), value); return withLocalMillis(instant); } /** * Returns a copy of this datetime with the value of the specified * field increased. *

* If the addition is zero or the field is null, then this is returned. *

* These three lines are equivalent: *

     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * LocalDateTime added = dt.plusYears(6);
     * LocalDateTime added = dt.plus(Period.years(6));
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this datetime with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDateTime withFieldAdded(DurationFieldType fieldType, int amount) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (amount == 0) { return this; } long instant = fieldType.getField(getChronology()).add(getLocalMillis(), amount); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified duration added. *

* If the addition is zero, then this is returned. * * @param durationToAdd the duration to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the duration added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDateTime withDurationAdded(ReadableDuration durationToAdd, int scalar) { if (durationToAdd == null || scalar == 0) { return this; } long instant = getChronology().add(getLocalMillis(), durationToAdd.getMillis(), scalar); return withLocalMillis(instant); } /** * Returns a copy of this datetime with the specified period added. *

* If the addition is zero, then this is returned. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusYears(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the period added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDateTime withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getChronology().add(period, getLocalMillis(), scalar); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified duration added. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to add to this one, null means zero * @return a copy of this datetime with the duration added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDateTime plus(ReadableDuration duration) { return withDurationAdded(duration, 1); } /** * Returns a copy of this datetime with the specified period added. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusYears(int)}. * * @param period the period to add to this one, null means zero * @return a copy of this datetime with the period added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDateTime plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime plus the specified number of years. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusYears(6);
     * LocalDateTime added = dt.plus(Period.years(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * 
* * @param years the amount of years to add, may be negative * @return the new LocalDateTime plus the increased years */ public LocalDateTime plusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().add(getLocalMillis(), years); return withLocalMillis(instant); } /** * Returns a copy of this datetime plus the specified number of months. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusMonths(6);
     * LocalDateTime added = dt.plus(Period.months(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.months(), 6);
     * 
* * @param months the amount of months to add, may be negative * @return the new LocalDateTime plus the increased months */ public LocalDateTime plusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().add(getLocalMillis(), months); return withLocalMillis(instant); } /** * Returns a copy of this datetime plus the specified number of weeks. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusWeeks(6);
     * LocalDateTime added = dt.plus(Period.weeks(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.weeks(), 6);
     * 
* * @param weeks the amount of weeks to add, may be negative * @return the new LocalDateTime plus the increased weeks */ public LocalDateTime plusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().add(getLocalMillis(), weeks); return withLocalMillis(instant); } /** * Returns a copy of this datetime plus the specified number of days. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusDays(6);
     * LocalDateTime added = dt.plus(Period.days(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.days(), 6);
     * 
* * @param days the amount of days to add, may be negative * @return the new LocalDateTime plus the increased days */ public LocalDateTime plusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().add(getLocalMillis(), days); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime plus the specified number of hours. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusHours(6);
     * LocalDateTime added = dt.plus(Period.hours(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.hours(), 6);
     * 
* * @param hours the amount of hours to add, may be negative * @return the new LocalDateTime plus the increased hours */ public LocalDateTime plusHours(int hours) { if (hours == 0) { return this; } long instant = getChronology().hours().add(getLocalMillis(), hours); return withLocalMillis(instant); } /** * Returns a copy of this datetime plus the specified number of minutes. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusMinutes(6);
     * LocalDateTime added = dt.plus(Period.minutes(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.minutes(), 6);
     * 
* * @param minutes the amount of minutes to add, may be negative * @return the new LocalDateTime plus the increased minutes */ public LocalDateTime plusMinutes(int minutes) { if (minutes == 0) { return this; } long instant = getChronology().minutes().add(getLocalMillis(), minutes); return withLocalMillis(instant); } /** * Returns a copy of this datetime plus the specified number of seconds. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusSeconds(6);
     * LocalDateTime added = dt.plus(Period.seconds(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.seconds(), 6);
     * 
* * @param seconds the amount of seconds to add, may be negative * @return the new LocalDateTime plus the increased seconds */ public LocalDateTime plusSeconds(int seconds) { if (seconds == 0) { return this; } long instant = getChronology().seconds().add(getLocalMillis(), seconds); return withLocalMillis(instant); } /** * Returns a copy of this datetime plus the specified number of millis. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime added = dt.plusMillis(6);
     * LocalDateTime added = dt.plus(Period.millis(6));
     * LocalDateTime added = dt.withFieldAdded(DurationFieldType.millis(), 6);
     * 
* * @param millis the amount of millis to add, may be negative * @return the new LocalDateTime plus the increased millis */ public LocalDateTime plusMillis(int millis) { if (millis == 0) { return this; } long instant = getChronology().millis().add(getLocalMillis(), millis); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified duration taken away. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to reduce this instant by * @return a copy of this datetime with the duration taken away * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDateTime minus(ReadableDuration duration) { return withDurationAdded(duration, -1); } /** * Returns a copy of this datetime with the specified period taken away. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusYears(int)}. * * @param period the period to reduce this instant by * @return a copy of this datetime with the period taken away * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDateTime minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime minus the specified number of years. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusYears(6);
     * LocalDateTime subtracted = dt.minus(Period.years(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.years(), -6);
     * 
* * @param years the amount of years to subtract, may be negative * @return the new LocalDateTime minus the increased years */ public LocalDateTime minusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().subtract(getLocalMillis(), years); return withLocalMillis(instant); } /** * Returns a copy of this datetime minus the specified number of months. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusMonths(6);
     * LocalDateTime subtracted = dt.minus(Period.months(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.months(), -6);
     * 
* * @param months the amount of months to subtract, may be negative * @return the new LocalDateTime minus the increased months */ public LocalDateTime minusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().subtract(getLocalMillis(), months); return withLocalMillis(instant); } /** * Returns a copy of this datetime minus the specified number of weeks. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusWeeks(6);
     * LocalDateTime subtracted = dt.minus(Period.weeks(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.weeks(), -6);
     * 
* * @param weeks the amount of weeks to subtract, may be negative * @return the new LocalDateTime minus the increased weeks */ public LocalDateTime minusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().subtract(getLocalMillis(), weeks); return withLocalMillis(instant); } /** * Returns a copy of this datetime minus the specified number of days. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusDays(6);
     * LocalDateTime subtracted = dt.minus(Period.days(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.days(), -6);
     * 
* * @param days the amount of days to subtract, may be negative * @return the new LocalDateTime minus the increased days */ public LocalDateTime minusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().subtract(getLocalMillis(), days); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime minus the specified number of hours. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusHours(6);
     * LocalDateTime subtracted = dt.minus(Period.hours(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.hours(), -6);
     * 
* * @param hours the amount of hours to subtract, may be negative * @return the new LocalDateTime minus the increased hours */ public LocalDateTime minusHours(int hours) { if (hours == 0) { return this; } long instant = getChronology().hours().subtract(getLocalMillis(), hours); return withLocalMillis(instant); } /** * Returns a copy of this datetime minus the specified number of minutes. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusMinutes(6);
     * LocalDateTime subtracted = dt.minus(Period.minutes(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.minutes(), -6);
     * 
* * @param minutes the amount of minutes to subtract, may be negative * @return the new LocalDateTime minus the increased minutes */ public LocalDateTime minusMinutes(int minutes) { if (minutes == 0) { return this; } long instant = getChronology().minutes().subtract(getLocalMillis(), minutes); return withLocalMillis(instant); } /** * Returns a copy of this datetime minus the specified number of seconds. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusSeconds(6);
     * LocalDateTime subtracted = dt.minus(Period.seconds(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.seconds(), -6);
     * 
* * @param seconds the amount of seconds to subtract, may be negative * @return the new LocalDateTime minus the increased seconds */ public LocalDateTime minusSeconds(int seconds) { if (seconds == 0) { return this; } long instant = getChronology().seconds().subtract(getLocalMillis(), seconds); return withLocalMillis(instant); } /** * Returns a copy of this datetime minus the specified number of millis. *

* This LocalDateTime instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDateTime subtracted = dt.minusMillis(6);
     * LocalDateTime subtracted = dt.minus(Period.millis(6));
     * LocalDateTime subtracted = dt.withFieldAdded(DurationFieldType.millis(), -6);
     * 
* * @param millis the amount of millis to subtract, may be negative * @return the new LocalDateTime minus the increased millis */ public LocalDateTime minusMillis(int millis) { if (millis == 0) { return this; } long instant = getChronology().millis().subtract(getLocalMillis(), millis); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains many * useful methods. * * @param fieldType the field type to get the chronology for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } return new Property(this, fieldType.getField(getChronology())); } //----------------------------------------------------------------------- /** * Get the era field value. * * @return the era */ public int getEra() { return getChronology().era().get(getLocalMillis()); } /** * Get the year of era field value. * * @return the year of era */ public int getCenturyOfEra() { return getChronology().centuryOfEra().get(getLocalMillis()); } /** * Get the year of era field value. * * @return the year of era */ public int getYearOfEra() { return getChronology().yearOfEra().get(getLocalMillis()); } /** * Get the year of century field value. * * @return the year of century */ public int getYearOfCentury() { return getChronology().yearOfCentury().get(getLocalMillis()); } /** * Get the year field value. * * @return the year */ public int getYear() { return getChronology().year().get(getLocalMillis()); } /** * Get the weekyear field value. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. * * @return the weekyear */ public int getWeekyear() { return getChronology().weekyear().get(getLocalMillis()); } /** * Get the month of year field value. * * @return the month of year */ public int getMonthOfYear() { return getChronology().monthOfYear().get(getLocalMillis()); } /** * Get the week of weekyear field value. *

* This field is associated with the "weekyear" via {@link #getWeekyear()}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * * @return the week of a week based year */ public int getWeekOfWeekyear() { return getChronology().weekOfWeekyear().get(getLocalMillis()); } /** * Get the day of year field value. * * @return the day of year */ public int getDayOfYear() { return getChronology().dayOfYear().get(getLocalMillis()); } /** * Get the day of month field value. *

* The values for the day of month are defined in {@link org.joda.time.DateTimeConstants}. * * @return the day of month */ public int getDayOfMonth() { return getChronology().dayOfMonth().get(getLocalMillis()); } /** * Get the day of week field value. *

* The values for the day of week are defined in {@link org.joda.time.DateTimeConstants}. * * @return the day of week */ public int getDayOfWeek() { return getChronology().dayOfWeek().get(getLocalMillis()); } //----------------------------------------------------------------------- /** * Get the hour of day field value. * * @return the hour of day */ public int getHourOfDay() { return getChronology().hourOfDay().get(getLocalMillis()); } /** * Get the minute of hour field value. * * @return the minute of hour */ public int getMinuteOfHour() { return getChronology().minuteOfHour().get(getLocalMillis()); } /** * Get the second of minute field value. * * @return the second of minute */ public int getSecondOfMinute() { return getChronology().secondOfMinute().get(getLocalMillis()); } /** * Get the millis of second field value. * * @return the millis of second */ public int getMillisOfSecond() { return getChronology().millisOfSecond().get(getLocalMillis()); } /** * Get the millis of day field value. * * @return the millis of day */ public int getMillisOfDay() { return getChronology().millisOfDay().get(getLocalMillis()); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the era field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * era changed. * * @param era the era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withEra(int era) { return withLocalMillis(getChronology().era().set(getLocalMillis(), era)); } /** * Returns a copy of this datetime with the century of era field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * century of era changed. * * @param centuryOfEra the centurey of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withCenturyOfEra(int centuryOfEra) { return withLocalMillis(getChronology().centuryOfEra().set(getLocalMillis(), centuryOfEra)); } /** * Returns a copy of this datetime with the year of era field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of era changed. * * @param yearOfEra the year of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withYearOfEra(int yearOfEra) { return withLocalMillis(getChronology().yearOfEra().set(getLocalMillis(), yearOfEra)); } /** * Returns a copy of this datetime with the year of century field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of century changed. * * @param yearOfCentury the year of century to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withYearOfCentury(int yearOfCentury) { return withLocalMillis(getChronology().yearOfCentury().set(getLocalMillis(), yearOfCentury)); } /** * Returns a copy of this datetime with the year field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year changed. * * @param year the year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withYear(int year) { return withLocalMillis(getChronology().year().set(getLocalMillis(), year)); } /** * Returns a copy of this datetime with the weekyear field updated. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * weekyear changed. * * @param weekyear the weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withWeekyear(int weekyear) { return withLocalMillis(getChronology().weekyear().set(getLocalMillis(), weekyear)); } /** * Returns a copy of this datetime with the month of year field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withMonthOfYear(int monthOfYear) { return withLocalMillis(getChronology().monthOfYear().set(getLocalMillis(), monthOfYear)); } /** * Returns a copy of this datetime with the week of weekyear field updated. *

* This field is associated with the "weekyear" via {@link #withWeekyear(int)}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * week of weekyear changed. * * @param weekOfWeekyear the week of weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withWeekOfWeekyear(int weekOfWeekyear) { return withLocalMillis(getChronology().weekOfWeekyear().set(getLocalMillis(), weekOfWeekyear)); } /** * Returns a copy of this datetime with the day of year field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of year changed. * * @param dayOfYear the day of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withDayOfYear(int dayOfYear) { return withLocalMillis(getChronology().dayOfYear().set(getLocalMillis(), dayOfYear)); } /** * Returns a copy of this datetime with the day of month field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of month changed. * * @param dayOfMonth the day of month to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withDayOfMonth(int dayOfMonth) { return withLocalMillis(getChronology().dayOfMonth().set(getLocalMillis(), dayOfMonth)); } /** * Returns a copy of this datetime with the day of week field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of week changed. * * @param dayOfWeek the day of week to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withDayOfWeek(int dayOfWeek) { return withLocalMillis(getChronology().dayOfWeek().set(getLocalMillis(), dayOfWeek)); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the hour of day field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * hour of day changed. * * @param hour the hour of day to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withHourOfDay(int hour) { return withLocalMillis(getChronology().hourOfDay().set(getLocalMillis(), hour)); } /** * Returns a copy of this datetime with the minute of hour field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * minute of hour changed. * * @param minute the minute of hour to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withMinuteOfHour(int minute) { return withLocalMillis(getChronology().minuteOfHour().set(getLocalMillis(), minute)); } /** * Returns a copy of this datetime with the second of minute field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * second of minute changed. * * @param second the second of minute to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withSecondOfMinute(int second) { return withLocalMillis(getChronology().secondOfMinute().set(getLocalMillis(), second)); } /** * Returns a copy of this datetime with the millis of second field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * millis of second changed. * * @param millis the millis of second to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withMillisOfSecond(int millis) { return withLocalMillis(getChronology().millisOfSecond().set(getLocalMillis(), millis)); } /** * Returns a copy of this datetime with the millis of day field updated. *

* LocalDateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * millis of day changed. * * @param millis the millis of day to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDateTime withMillisOfDay(int millis) { return withLocalMillis(getChronology().millisOfDay().set(getLocalMillis(), millis)); } //----------------------------------------------------------------------- /** * Get the era property which provides access to advanced functionality. * * @return the era property */ public Property era() { return new Property(this, getChronology().era()); } /** * Get the century of era property which provides access to advanced functionality. * * @return the year of era property */ public Property centuryOfEra() { return new Property(this, getChronology().centuryOfEra()); } /** * Get the year of century property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfCentury() { return new Property(this, getChronology().yearOfCentury()); } /** * Get the year of era property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfEra() { return new Property(this, getChronology().yearOfEra()); } /** * Get the year property which provides access to advanced functionality. * * @return the year property */ public Property year() { return new Property(this, getChronology().year()); } /** * Get the weekyear property which provides access to advanced functionality. * * @return the weekyear property */ public Property weekyear() { return new Property(this, getChronology().weekyear()); } /** * Get the month of year property which provides access to advanced functionality. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, getChronology().monthOfYear()); } /** * Get the week of a week based year property which provides access to advanced functionality. * * @return the week of a week based year property */ public Property weekOfWeekyear() { return new Property(this, getChronology().weekOfWeekyear()); } /** * Get the day of year property which provides access to advanced functionality. * * @return the day of year property */ public Property dayOfYear() { return new Property(this, getChronology().dayOfYear()); } /** * Get the day of month property which provides access to advanced functionality. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, getChronology().dayOfMonth()); } /** * Get the day of week property which provides access to advanced functionality. * * @return the day of week property */ public Property dayOfWeek() { return new Property(this, getChronology().dayOfWeek()); } //----------------------------------------------------------------------- /** * Get the hour of day field property which provides access to advanced functionality. * * @return the hour of day property */ public Property hourOfDay() { return new Property(this, getChronology().hourOfDay()); } /** * Get the minute of hour field property which provides access to advanced functionality. * * @return the minute of hour property */ public Property minuteOfHour() { return new Property(this, getChronology().minuteOfHour()); } /** * Get the second of minute field property which provides access to advanced functionality. * * @return the second of minute property */ public Property secondOfMinute() { return new Property(this, getChronology().secondOfMinute()); } /** * Get the millis of second property which provides access to advanced functionality. * * @return the millis of second property */ public Property millisOfSecond() { return new Property(this, getChronology().millisOfSecond()); } /** * Get the millis of day property which provides access to advanced functionality. * * @return the millis of day property */ public Property millisOfDay() { return new Property(this, getChronology().millisOfDay()); } //----------------------------------------------------------------------- /** * Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSS). * * @return ISO8601 time formatted string. */ @ToString public String toString() { return ISODateTimeFormat.dateTime().print(this); } /** * Output the date using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the date using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) throws IllegalArgumentException { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } //----------------------------------------------------------------------- /** * LocalDateTime.Property binds a LocalDateTime to a DateTimeField allowing * powerful datetime functionality to be easily accessed. *

* The simplest use of this class is as an alternative get method, here used to * get the year '1972' (as an int) and the month 'December' (as a String). *

     * LocalDateTime dt = new LocalDateTime(1972, 12, 3, 0, 0);
     * int year = dt.year().get();
     * String monthStr = dt.month().getAsText();
     * 
*

* Methods are also provided that allow date modification. These return * new instances of LocalDateTime - they do not modify the original. * The example below yields two independent immutable date objects * 20 years apart. *

     * LocalDateTime dt = new LocalDateTime(1972, 12, 3, 0, 0);
     * LocalDateTime dt1920 = dt.year().setCopy(1920);
     * 
*

* LocalDateTime.Property itself is thread-safe and immutable, as well as the * LocalDateTime being operated on. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.3 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization version */ private static final long serialVersionUID = -358138762846288L; /** The instant this property is working against */ private transient LocalDateTime iInstant; /** The field this property is working against */ private transient DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(LocalDateTime instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Writes the property in a safe serialization format. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(iInstant); oos.writeObject(iField.getType()); } /** * Reads the property from a safe serialization format. */ private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException { iInstant = (LocalDateTime) oos.readObject(); DateTimeFieldType type = (DateTimeFieldType) oos.readObject(); iField = type.getField(iInstant.getChronology()); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the milliseconds of the datetime that this property is linked to. * * @return the milliseconds */ protected long getMillis() { return iInstant.getLocalMillis(); } /** * Gets the chronology of the datetime that this property is linked to. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { return iInstant.getChronology(); } /** * Gets the LocalDateTime object linked to this property. * * @return the linked LocalDateTime */ public LocalDateTime getLocalDateTime() { return iInstant; } //----------------------------------------------------------------------- /** * Adds to this field in a copy of this LocalDateTime. *

* The LocalDateTime attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalDateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalDateTime addToCopy(int value) { return iInstant.withLocalMillis(iField.add(iInstant.getLocalMillis(), value)); } /** * Adds to this field in a copy of this LocalDateTime. *

* The LocalDateTime attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalDateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalDateTime addToCopy(long value) { return iInstant.withLocalMillis(iField.add(iInstant.getLocalMillis(), value)); } /** * Adds to this field, possibly wrapped, in a copy of this LocalDateTime. * A field wrapped operation only changes this field. * Thus 31st January addWrapField one day goes to the 1st January. *

* The LocalDateTime attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalDateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalDateTime addWrapFieldToCopy(int value) { return iInstant.withLocalMillis(iField.addWrapField(iInstant.getLocalMillis(), value)); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the LocalDateTime. *

* The LocalDateTime attached to this property is unchanged by this call. * * @param value the value to set the field in the copy to * @return a copy of the LocalDateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalDateTime setCopy(int value) { return iInstant.withLocalMillis(iField.set(iInstant.getLocalMillis(), value)); } /** * Sets this field in a copy of the LocalDateTime to a parsed text value. *

* The LocalDateTime attached to this property is unchanged by this call. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the LocalDateTime with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public LocalDateTime setCopy(String text, Locale locale) { return iInstant.withLocalMillis(iField.set(iInstant.getLocalMillis(), text, locale)); } /** * Sets this field in a copy of the LocalDateTime to a parsed text value. *

* The LocalDateTime attached to this property is unchanged by this call. * * @param text the text value to set * @return a copy of the LocalDateTime with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public LocalDateTime setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new LocalDateTime with this field set to the maximum value * for this field. *

* This operation is useful for obtaining a LocalDateTime on the last day * of the month, as month lengths vary. *

         * LocalDateTime lastDayOfMonth = dt.dayOfMonth().withMaximumValue();
         * 
*

* The LocalDateTime attached to this property is unchanged by this call. * * @return a copy of the LocalDateTime with this field set to its maximum */ public LocalDateTime withMaximumValue() { return setCopy(getMaximumValue()); } /** * Returns a new LocalDateTime with this field set to the minimum value * for this field. *

* The LocalDateTime attached to this property is unchanged by this call. * * @return a copy of the LocalDateTime with this field set to its minimum */ public LocalDateTime withMinimumValue() { return setCopy(getMinimumValue()); } //----------------------------------------------------------------------- /** * Rounds to the lowest whole unit of this field on a copy of this * LocalDateTime. *

* For example, rounding floor on the hourOfDay field of a LocalDateTime * where the time is 10:30 would result in new LocalDateTime with the * time of 10:00. * * @return a copy of the LocalDateTime with the field value changed */ public LocalDateTime roundFloorCopy() { return iInstant.withLocalMillis(iField.roundFloor(iInstant.getLocalMillis())); } /** * Rounds to the highest whole unit of this field on a copy of this * LocalDateTime. *

* For example, rounding floor on the hourOfDay field of a LocalDateTime * where the time is 10:30 would result in new LocalDateTime with the * time of 11:00. * * @return a copy of the LocalDateTime with the field value changed */ public LocalDateTime roundCeilingCopy() { return iInstant.withLocalMillis(iField.roundCeiling(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalDateTime, favoring the floor if halfway. * * @return a copy of the LocalDateTime with the field value changed */ public LocalDateTime roundHalfFloorCopy() { return iInstant.withLocalMillis(iField.roundHalfFloor(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalDateTime, favoring the ceiling if halfway. * * @return a copy of the LocalDateTime with the field value changed */ public LocalDateTime roundHalfCeilingCopy() { return iInstant.withLocalMillis(iField.roundHalfCeiling(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalDateTime. If halfway, the ceiling is favored over the floor * only if it makes this field's value even. * * @return a copy of the LocalDateTime with the field value changed */ public LocalDateTime roundHalfEvenCopy() { return iInstant.withLocalMillis(iField.roundHalfEven(iInstant.getLocalMillis())); } } } joda-time-2.3/src/main/java/org/joda/time/DateTimeComparator.java0000644000175000017500000002205511564251363024256 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import java.util.Comparator; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.InstantConverter; /** * DateTimeComparator provides comparators to compare one date with another. *

* Dates may be specified using any object recognised by the * {@link org.joda.time.convert.ConverterManager ConverterManager} class. *

* The default objects recognised by the comparator are: *

    *
  • ReadableInstant *
  • String *
  • Calendar *
  • Date *
  • Long (milliseconds) *
  • null (now) *
* *

* DateTimeComparator is thread-safe and immutable. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public class DateTimeComparator implements Comparator, Serializable { /** Serialization lock */ private static final long serialVersionUID = -6097339773320178364L; /** Singleton instance */ private static final DateTimeComparator ALL_INSTANCE = new DateTimeComparator(null, null); /** Singleton instance */ private static final DateTimeComparator DATE_INSTANCE = new DateTimeComparator(DateTimeFieldType.dayOfYear(), null); /** Singleton instance */ private static final DateTimeComparator TIME_INSTANCE = new DateTimeComparator(null, DateTimeFieldType.dayOfYear()); /** The lower limit of fields to compare, null if no limit */ private final DateTimeFieldType iLowerLimit; /** The upper limit of fields to compare, null if no limit */ private final DateTimeFieldType iUpperLimit; //----------------------------------------------------------------------- /** * Returns a DateTimeComparator the compares the entire date time value. * * @return a comparator over all fields */ public static DateTimeComparator getInstance() { return ALL_INSTANCE; } /** * Returns a DateTimeComparator with a lower limit only. Fields of a * magnitude less than the lower limit are excluded from comparisons. * * @param lowerLimit inclusive lower limit for fields to be compared, null means no limit * @return a comparator over all fields above the lower limit */ public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit) { return getInstance(lowerLimit, null); } /** * Returns a DateTimeComparator with a lower and upper limit. Fields of a * magnitude less than the lower limit are excluded from comparisons. * Fields of a magnitude greater than or equal to the upper limit are also * excluded from comparisons. Either limit may be specified as null, which * indicates an unbounded limit. * * @param lowerLimit inclusive lower limit for fields to be compared, null means no limit * @param upperLimit exclusive upper limit for fields to be compared, null means no limit * @return a comparator over all fields between the limits */ public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit) { if (lowerLimit == null && upperLimit == null) { return ALL_INSTANCE; } if (lowerLimit == DateTimeFieldType.dayOfYear() && upperLimit == null) { return DATE_INSTANCE; } if (lowerLimit == null && upperLimit == DateTimeFieldType.dayOfYear()) { return TIME_INSTANCE; } return new DateTimeComparator(lowerLimit, upperLimit); } /** * Returns a comparator that only considers date fields. * Time of day is ignored. * * @return a comparator over all date fields */ public static DateTimeComparator getDateOnlyInstance() { return DATE_INSTANCE; } /** * Returns a comparator that only considers time fields. * Date is ignored. * * @return a comparator over all time fields */ public static DateTimeComparator getTimeOnlyInstance() { return TIME_INSTANCE; } /** * Restricted constructor. * * @param lowerLimit the lower field limit, null means no limit * @param upperLimit the upper field limit, null means no limit */ protected DateTimeComparator(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit) { super(); iLowerLimit = lowerLimit; iUpperLimit = upperLimit; } //----------------------------------------------------------------------- /** * Gets the field type that represents the lower limit of comparison. * * @return the field type, null if no upper limit */ public DateTimeFieldType getLowerLimit() { return iLowerLimit; } /** * Gets the field type that represents the upper limit of comparison. * * @return the field type, null if no upper limit */ public DateTimeFieldType getUpperLimit() { return iUpperLimit; } /** * Compare two objects against only the range of date time fields as * specified in the constructor. * * @param lhsObj the first object, * logically on the left of a < comparison, null means now * @param rhsObj the second object, * logically on the right of a < comparison, null means now * @return zero if order does not matter, * negative value if lhsObj < rhsObj, positive value otherwise. * @throws IllegalArgumentException if either argument is not supported */ public int compare(Object lhsObj, Object rhsObj) { InstantConverter conv = ConverterManager.getInstance().getInstantConverter(lhsObj); Chronology lhsChrono = conv.getChronology(lhsObj, (Chronology) null); long lhsMillis = conv.getInstantMillis(lhsObj, lhsChrono); conv = ConverterManager.getInstance().getInstantConverter(rhsObj); Chronology rhsChrono = conv.getChronology(rhsObj, (Chronology) null); long rhsMillis = conv.getInstantMillis(rhsObj, rhsChrono); if (iLowerLimit != null) { lhsMillis = iLowerLimit.getField(lhsChrono).roundFloor(lhsMillis); rhsMillis = iLowerLimit.getField(rhsChrono).roundFloor(rhsMillis); } if (iUpperLimit != null) { lhsMillis = iUpperLimit.getField(lhsChrono).remainder(lhsMillis); rhsMillis = iUpperLimit.getField(rhsChrono).remainder(rhsMillis); } if (lhsMillis < rhsMillis) { return -1; } else if (lhsMillis > rhsMillis) { return 1; } else { return 0; } } //----------------------------------------------------------------------- /** * Support serialization singletons. * * @return the resolved singleton instance */ private Object readResolve() { return getInstance(iLowerLimit, iUpperLimit); } /** * Compares this comparator to another. * * @param object the object to compare to * @return true if equal */ public boolean equals(Object object) { if (object instanceof DateTimeComparator) { DateTimeComparator other = (DateTimeComparator) object; return (iLowerLimit == other.getLowerLimit() || (iLowerLimit != null && iLowerLimit.equals(other.getLowerLimit()))) && (iUpperLimit == other.getUpperLimit() || (iUpperLimit != null && iUpperLimit.equals(other.getUpperLimit()))); } return false; } /** * Gets a suitable hashcode. * * @return the hashcode */ public int hashCode() { return (iLowerLimit == null ? 0 : iLowerLimit.hashCode()) + (123 * (iUpperLimit == null ? 0 : iUpperLimit.hashCode())); } /** * Gets a debugging string. * * @return a debugging string */ public String toString() { if (iLowerLimit == iUpperLimit) { return "DateTimeComparator[" + (iLowerLimit == null ? "" : iLowerLimit.getName()) + "]"; } else { return "DateTimeComparator[" + (iLowerLimit == null ? "" : iLowerLimit.getName()) + "-" + (iUpperLimit == null ? "" : iUpperLimit.getName()) + "]"; } } } joda-time-2.3/src/main/java/org/joda/time/Minutes.java0000644000175000017500000004474111564251363022164 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseSingleFieldPeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period representing a number of minutes. *

* Minutes is an immutable period that can only store minutes. * It does not store years, months or hours for example. As such it is a * type-safe way of representing a number of minutes in an application. *

* The number of minutes is set in the constructor, and may be queried using * getMinutes(). Basic mathematical operations are provided - * plus(), minus(), multipliedBy() and * dividedBy(). *

* Minutes is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.4 */ public final class Minutes extends BaseSingleFieldPeriod { /** Constant representing zero minutes. */ public static final Minutes ZERO = new Minutes(0); /** Constant representing one minute. */ public static final Minutes ONE = new Minutes(1); /** Constant representing two minutes. */ public static final Minutes TWO = new Minutes(2); /** Constant representing three minutes. */ public static final Minutes THREE = new Minutes(3); /** Constant representing the maximum number of minutes that can be stored in this object. */ public static final Minutes MAX_VALUE = new Minutes(Integer.MAX_VALUE); /** Constant representing the minimum number of minutes that can be stored in this object. */ public static final Minutes MIN_VALUE = new Minutes(Integer.MIN_VALUE); /** The paser to use for this class. */ private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.minutes()); /** Serialization version. */ private static final long serialVersionUID = 87525275727380863L; //----------------------------------------------------------------------- /** * Obtains an instance of Minutes that may be cached. * Minutes is immutable, so instances can be cached and shared. * This factory method provides access to shared instances. * * @param minutes the number of minutes to obtain an instance for * @return the instance of Minutes */ public static Minutes minutes(int minutes) { switch (minutes) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Minutes(minutes); } } //----------------------------------------------------------------------- /** * Creates a Minutes representing the number of whole minutes * between the two specified datetimes. * * @param start the start instant, must not be null * @param end the end instant, must not be null * @return the period in minutes * @throws IllegalArgumentException if the instants are null or invalid */ public static Minutes minutesBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.minutes()); return Minutes.minutes(amount); } /** * Creates a Minutes representing the number of whole minutes * between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalTime objects. * * @param start the start partial date, must not be null * @param end the end partial date, must not be null * @return the period in minutes * @throws IllegalArgumentException if the partials are null or invalid */ public static Minutes minutesBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalTime && end instanceof LocalTime) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int minutes = chrono.minutes().getDifference( ((LocalTime) end).getLocalMillis(), ((LocalTime) start).getLocalMillis()); return Minutes.minutes(minutes); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Minutes.minutes(amount); } /** * Creates a Minutes representing the number of whole minutes * in the specified interval. * * @param interval the interval to extract minutes from, null returns zero * @return the period in minutes * @throws IllegalArgumentException if the partials are null or invalid */ public static Minutes minutesIn(ReadableInterval interval) { if (interval == null) { return Minutes.ZERO; } int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.minutes()); return Minutes.minutes(amount); } /** * Creates a new Minutes representing the number of complete * standard length minutes in the specified period. *

* This factory method converts all fields from the period to minutes using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. *

    *
  • One week consists of 7 days. *
  • One day consists of 24 hours. *
  • One hour consists of 60 minutes. *
  • One minute consists of 60 seconds. *
  • One second consists of 1000 milliseconds. *
* Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of minutes from, null returns zero * @return the period in minutes * @throws IllegalArgumentException if the period contains imprecise duration values */ public static Minutes standardMinutesIn(ReadablePeriod period) { int amount = BaseSingleFieldPeriod.standardPeriodIn(period, DateTimeConstants.MILLIS_PER_MINUTE); return Minutes.minutes(amount); } /** * Creates a new Minutes by parsing a string in the ISO8601 format 'PTnM'. *

* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the * minutes component may be non-zero. If any other component is non-zero, an exception * will be thrown. * * @param periodStr the period string, null returns zero * @return the period in minutes * @throws IllegalArgumentException if the string format is invalid */ @FromString public static Minutes parseMinutes(String periodStr) { if (periodStr == null) { return Minutes.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Minutes.minutes(p.getMinutes()); } //----------------------------------------------------------------------- /** * Creates a new instance representing a number of minutes. * You should consider using the factory method {@link #minutes(int)} * instead of the constructor. * * @param minutes the number of minutes to represent */ private Minutes(int minutes) { super(minutes); } /** * Resolves singletons. * * @return the singleton instance */ private Object readResolve() { return Minutes.minutes(getValue()); } //----------------------------------------------------------------------- /** * Gets the duration field type, which is minutes. * * @return the period type */ public DurationFieldType getFieldType() { return DurationFieldType.minutes(); } /** * Gets the period type, which is minutes. * * @return the period type */ public PeriodType getPeriodType() { return PeriodType.minutes(); } //----------------------------------------------------------------------- /** * Converts this period in minutes to a period in weeks assuming a * 7 days week, 24 hour day and 60 minute hour. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are * 7 days long, all days are 24 hours long and all hours are 60 minutes long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of whole weeks for this number of minutes */ public Weeks toStandardWeeks() { return Weeks.weeks(getValue() / DateTimeConstants.MINUTES_PER_WEEK); } /** * Converts this period in minutes to a period in days assuming a * 24 hour day and 60 minute hour. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all days are * 24 hours long and all hours are 60 minutes long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of whole days for this number of minutes */ public Days toStandardDays() { return Days.days(getValue() / DateTimeConstants.MINUTES_PER_DAY); } /** * Converts this period in minutes to a period in hours assuming a * 60 minute hour. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all hours are * 60 minutes long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of hours for this number of minutes */ public Hours toStandardHours() { return Hours.hours(getValue() / DateTimeConstants.MINUTES_PER_HOUR); } /** * Converts this period in minutes to a period in seconds assuming a * 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all minutes are * 60 seconds long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of seconds for this number of minutes * @throws ArithmeticException if the number of seconds is too large to be represented */ public Seconds toStandardSeconds() { return Seconds.seconds(FieldUtils.safeMultiply(getValue(), DateTimeConstants.SECONDS_PER_MINUTE)); } //----------------------------------------------------------------------- /** * Converts this period in minutes to a duration in milliseconds assuming a * 60 second minute. *

* This method allows you to convert from a period to a duration. * However to achieve this it makes the assumption that all minutes are * 60 seconds long. This might not be true for an unusual chronology, * for example one that takes leap seconds into account. * However, the method is included as it is a useful operation for many * applications and business rules. * * @return a duration equivalent to this number of minutes */ public Duration toStandardDuration() { long minutes = getValue(); // assign to a long return new Duration(minutes * DateTimeConstants.MILLIS_PER_MINUTE); } //----------------------------------------------------------------------- /** * Gets the number of minutes that this period represents. * * @return the number of minutes in the period */ public int getMinutes() { return getValue(); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of minutes added. *

* This instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to add, may be negative * @return the new period plus the specified number of minutes * @throws ArithmeticException if the result overflows an int */ public Minutes plus(int minutes) { if (minutes == 0) { return this; } return Minutes.minutes(FieldUtils.safeAdd(getValue(), minutes)); } /** * Returns a new instance with the specified number of minutes added. *

* This instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to add, may be negative, null means zero * @return the new period plus the specified number of minutes * @throws ArithmeticException if the result overflows an int */ public Minutes plus(Minutes minutes) { if (minutes == null) { return this; } return plus(minutes.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of minutes taken away. *

* This instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to take away, may be negative * @return the new period minus the specified number of minutes * @throws ArithmeticException if the result overflows an int */ public Minutes minus(int minutes) { return plus(FieldUtils.safeNegate(minutes)); } /** * Returns a new instance with the specified number of minutes taken away. *

* This instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to take away, may be negative, null means zero * @return the new period minus the specified number of minutes * @throws ArithmeticException if the result overflows an int */ public Minutes minus(Minutes minutes) { if (minutes == null) { return this; } return minus(minutes.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the minutes multiplied by the specified scalar. *

* This instance is immutable and unaffected by this method call. * * @param scalar the amount to multiply by, may be negative * @return the new period multiplied by the specified scalar * @throws ArithmeticException if the result overflows an int */ public Minutes multipliedBy(int scalar) { return Minutes.minutes(FieldUtils.safeMultiply(getValue(), scalar)); } /** * Returns a new instance with the minutes divided by the specified divisor. * The calculation uses integer division, thus 3 divided by 2 is 1. *

* This instance is immutable and unaffected by this method call. * * @param divisor the amount to divide by, may be negative * @return the new period divided by the specified divisor * @throws ArithmeticException if the divisor is zero */ public Minutes dividedBy(int divisor) { if (divisor == 1) { return this; } return Minutes.minutes(getValue() / divisor); } //----------------------------------------------------------------------- /** * Returns a new instance with the minutes value negated. * * @return the new period with a negated value * @throws ArithmeticException if the result overflows an int */ public Minutes negated() { return Minutes.minutes(FieldUtils.safeNegate(getValue())); } //----------------------------------------------------------------------- /** * Is this minutes instance greater than the specified number of minutes. * * @param other the other period, null means zero * @return true if this minutes instance is greater than the specified one */ public boolean isGreaterThan(Minutes other) { if (other == null) { return getValue() > 0; } return getValue() > other.getValue(); } /** * Is this minutes instance less than the specified number of minutes. * * @param other the other period, null means zero * @return true if this minutes instance is less than the specified one */ public boolean isLessThan(Minutes other) { if (other == null) { return getValue() < 0; } return getValue() < other.getValue(); } //----------------------------------------------------------------------- /** * Gets this instance as a String in the ISO8601 duration format. *

* For example, "PT4M" represents 4 minutes. * * @return the value as an ISO8601 string */ @ToString public String toString() { return "PT" + String.valueOf(getValue()) + "M"; } } joda-time-2.3/src/main/java/org/joda/time/Hours.java0000644000175000017500000004575011564251363021641 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseSingleFieldPeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period representing a number of hours. *

* Hours is an immutable period that can only store hours. * It does not store years, months or minutes for example. As such it is a * type-safe way of representing a number of hours in an application. *

* The number of hours is set in the constructor, and may be queried using * getHours(). Basic mathematical operations are provided - * plus(), minus(), multipliedBy() and * dividedBy(). *

* Hours is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.4 */ public final class Hours extends BaseSingleFieldPeriod { /** Constant representing zero hours. */ public static final Hours ZERO = new Hours(0); /** Constant representing one hour. */ public static final Hours ONE = new Hours(1); /** Constant representing two hours. */ public static final Hours TWO = new Hours(2); /** Constant representing three hours. */ public static final Hours THREE = new Hours(3); /** Constant representing four hours. */ public static final Hours FOUR = new Hours(4); /** Constant representing five hours. */ public static final Hours FIVE = new Hours(5); /** Constant representing six hours. */ public static final Hours SIX = new Hours(6); /** Constant representing seven hours. */ public static final Hours SEVEN = new Hours(7); /** Constant representing eight hours. */ public static final Hours EIGHT = new Hours(8); /** Constant representing the maximum number of hours that can be stored in this object. */ public static final Hours MAX_VALUE = new Hours(Integer.MAX_VALUE); /** Constant representing the minimum number of hours that can be stored in this object. */ public static final Hours MIN_VALUE = new Hours(Integer.MIN_VALUE); /** The paser to use for this class. */ private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.hours()); /** Serialization version. */ private static final long serialVersionUID = 87525275727380864L; //----------------------------------------------------------------------- /** * Obtains an instance of Hours that may be cached. * Hours is immutable, so instances can be cached and shared. * This factory method provides access to shared instances. * * @param hours the number of hours to obtain an instance for * @return the instance of Hours */ public static Hours hours(int hours) { switch (hours) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case 4: return FOUR; case 5: return FIVE; case 6: return SIX; case 7: return SEVEN; case 8: return EIGHT; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Hours(hours); } } //----------------------------------------------------------------------- /** * Creates a Hours representing the number of whole hours * between the two specified datetimes. * * @param start the start instant, must not be null * @param end the end instant, must not be null * @return the period in hours * @throws IllegalArgumentException if the instants are null or invalid */ public static Hours hoursBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.hours()); return Hours.hours(amount); } /** * Creates a Hours representing the number of whole hours * between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalTime objects. * * @param start the start partial date, must not be null * @param end the end partial date, must not be null * @return the period in hours * @throws IllegalArgumentException if the partials are null or invalid */ public static Hours hoursBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalTime && end instanceof LocalTime) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int hours = chrono.hours().getDifference( ((LocalTime) end).getLocalMillis(), ((LocalTime) start).getLocalMillis()); return Hours.hours(hours); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Hours.hours(amount); } /** * Creates a Hours representing the number of whole hours * in the specified interval. * * @param interval the interval to extract hours from, null returns zero * @return the period in hours * @throws IllegalArgumentException if the partials are null or invalid */ public static Hours hoursIn(ReadableInterval interval) { if (interval == null) { return Hours.ZERO; } int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.hours()); return Hours.hours(amount); } /** * Creates a new Hours representing the number of complete * standard length hours in the specified period. *

* This factory method converts all fields from the period to hours using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. *

    *
  • One week consists of 7 days. *
  • One day consists of 24 hours. *
  • One hour consists of 60 minutes. *
  • One minute consists of 60 seconds. *
  • One second consists of 1000 milliseconds. *
* Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of hours from, null returns zero * @return the period in hours * @throws IllegalArgumentException if the period contains imprecise duration values */ public static Hours standardHoursIn(ReadablePeriod period) { int amount = BaseSingleFieldPeriod.standardPeriodIn(period, DateTimeConstants.MILLIS_PER_HOUR); return Hours.hours(amount); } /** * Creates a new Hours by parsing a string in the ISO8601 format 'PTnH'. *

* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the * hours component may be non-zero. If any other component is non-zero, an exception * will be thrown. * * @param periodStr the period string, null returns zero * @return the period in hours * @throws IllegalArgumentException if the string format is invalid */ @FromString public static Hours parseHours(String periodStr) { if (periodStr == null) { return Hours.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Hours.hours(p.getHours()); } //----------------------------------------------------------------------- /** * Creates a new instance representing a number of hours. * You should consider using the factory method {@link #hours(int)} * instead of the constructor. * * @param hours the number of hours to represent */ private Hours(int hours) { super(hours); } /** * Resolves singletons. * * @return the singleton instance */ private Object readResolve() { return Hours.hours(getValue()); } //----------------------------------------------------------------------- /** * Gets the duration field type, which is hours. * * @return the period type */ public DurationFieldType getFieldType() { return DurationFieldType.hours(); } /** * Gets the period type, which is hours. * * @return the period type */ public PeriodType getPeriodType() { return PeriodType.hours(); } //----------------------------------------------------------------------- /** * Converts this period in hours to a period in weeks assuming a * 7 day week and 24 hour day. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are 7 days * long and all days are 24 hours long. * This is not true when daylight savings time is considered, and may also * not be true for some unusual chronologies. However, it is included as it * is a useful operation for many applications and business rules. * * @return a period representing the number of whole weeks for this number of hours */ public Weeks toStandardWeeks() { return Weeks.weeks(getValue() / DateTimeConstants.HOURS_PER_WEEK); } /** * Converts this period in hours to a period in days assuming a * 24 hour day. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all days are 24 hours long. * This is not true when daylight savings time is considered, and may also * not be true for some unusual chronologies. However, it is included as it * is a useful operation for many applications and business rules. * * @return a period representing the number of whole days for this number of hours */ public Days toStandardDays() { return Days.days(getValue() / DateTimeConstants.HOURS_PER_DAY); } /** * Converts this period in hours to a period in minutes assuming a * 60 minute hour. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all hours are 60 minutes long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of minutes for this number of hours * @throws ArithmeticException if the number of minutes is too large to be represented */ public Minutes toStandardMinutes() { return Minutes.minutes(FieldUtils.safeMultiply(getValue(), DateTimeConstants.MINUTES_PER_HOUR)); } /** * Converts this period in hours to a period in seconds assuming a * 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all hours are * 60 minutes long and all minutes are 60 seconds long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of seconds for this number of hours * @throws ArithmeticException if the number of seconds is too large to be represented */ public Seconds toStandardSeconds() { return Seconds.seconds(FieldUtils.safeMultiply(getValue(), DateTimeConstants.SECONDS_PER_HOUR)); } //----------------------------------------------------------------------- /** * Converts this period in hours to a duration in milliseconds assuming a * 60 minute hour and 60 second minute. *

* This method allows you to convert from a period to a duration. * However to achieve this it makes the assumption that all hours are * 60 minutes and all minutes are 60 seconds. This might not be true for an * unusual chronology, for example one that takes leap seconds into account. * However, the method is included as it is a useful operation for many * applications and business rules. * * @return a duration equivalent to this number of hours */ public Duration toStandardDuration() { long hours = getValue(); // assign to a long return new Duration(hours * DateTimeConstants.MILLIS_PER_HOUR); } //----------------------------------------------------------------------- /** * Gets the number of hours that this period represents. * * @return the number of hours in the period */ public int getHours() { return getValue(); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of hours added. *

* This instance is immutable and unaffected by this method call. * * @param hours the amount of hours to add, may be negative * @return the new period plus the specified number of hours * @throws ArithmeticException if the result overflows an int */ public Hours plus(int hours) { if (hours == 0) { return this; } return Hours.hours(FieldUtils.safeAdd(getValue(), hours)); } /** * Returns a new instance with the specified number of hours added. *

* This instance is immutable and unaffected by this method call. * * @param hours the amount of hours to add, may be negative, null means zero * @return the new period plus the specified number of hours * @throws ArithmeticException if the result overflows an int */ public Hours plus(Hours hours) { if (hours == null) { return this; } return plus(hours.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of hours taken away. *

* This instance is immutable and unaffected by this method call. * * @param hours the amount of hours to take away, may be negative * @return the new period minus the specified number of hours * @throws ArithmeticException if the result overflows an int */ public Hours minus(int hours) { return plus(FieldUtils.safeNegate(hours)); } /** * Returns a new instance with the specified number of hours taken away. *

* This instance is immutable and unaffected by this method call. * * @param hours the amount of hours to take away, may be negative, null means zero * @return the new period minus the specified number of hours * @throws ArithmeticException if the result overflows an int */ public Hours minus(Hours hours) { if (hours == null) { return this; } return minus(hours.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the hours multiplied by the specified scalar. *

* This instance is immutable and unaffected by this method call. * * @param scalar the amount to multiply by, may be negative * @return the new period multiplied by the specified scalar * @throws ArithmeticException if the result overflows an int */ public Hours multipliedBy(int scalar) { return Hours.hours(FieldUtils.safeMultiply(getValue(), scalar)); } /** * Returns a new instance with the hours divided by the specified divisor. * The calculation uses integer division, thus 3 divided by 2 is 1. *

* This instance is immutable and unaffected by this method call. * * @param divisor the amount to divide by, may be negative * @return the new period divided by the specified divisor * @throws ArithmeticException if the divisor is zero */ public Hours dividedBy(int divisor) { if (divisor == 1) { return this; } return Hours.hours(getValue() / divisor); } //----------------------------------------------------------------------- /** * Returns a new instance with the hours value negated. * * @return the new period with a negated value * @throws ArithmeticException if the result overflows an int */ public Hours negated() { return Hours.hours(FieldUtils.safeNegate(getValue())); } //----------------------------------------------------------------------- /** * Is this hours instance greater than the specified number of hours. * * @param other the other period, null means zero * @return true if this hours instance is greater than the specified one */ public boolean isGreaterThan(Hours other) { if (other == null) { return getValue() > 0; } return getValue() > other.getValue(); } /** * Is this hours instance less than the specified number of hours. * * @param other the other period, null means zero * @return true if this hours instance is less than the specified one */ public boolean isLessThan(Hours other) { if (other == null) { return getValue() < 0; } return getValue() < other.getValue(); } //----------------------------------------------------------------------- /** * Gets this instance as a String in the ISO8601 duration format. *

* For example, "PT4H" represents 4 hours. * * @return the value as an ISO8601 string */ @ToString public String toString() { return "PT" + String.valueOf(getValue()) + "H"; } } joda-time-2.3/src/main/java/org/joda/time/PeriodType.java0000644000175000017500000006456111667411635022632 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.joda.time.field.FieldUtils; /** * Controls a period implementation by specifying which duration fields are to be used. *

* The following implementations are provided: *

    *
  • Standard - years, months, weeks, days, hours, minutes, seconds, millis *
  • YearMonthDayTime - years, months, days, hours, minutes, seconds, millis *
  • YearMonthDay - years, months, days *
  • YearWeekDayTime - years, weeks, days, hours, minutes, seconds, millis *
  • YearWeekDay - years, weeks, days *
  • YearDayTime - years, days, hours, minutes, seconds, millis *
  • YearDay - years, days, hours *
  • DayTime - days, hours, minutes, seconds, millis *
  • Time - hours, minutes, seconds, millis *
  • plus one for each single type *
* *

* PeriodType is thread-safe and immutable, and all subclasses must be as well. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public class PeriodType implements Serializable { /** Serialization version */ private static final long serialVersionUID = 2274324892792009998L; /** Cache of all the known types. */ private static final Map cTypes = new HashMap(32); static int YEAR_INDEX = 0; static int MONTH_INDEX = 1; static int WEEK_INDEX = 2; static int DAY_INDEX = 3; static int HOUR_INDEX = 4; static int MINUTE_INDEX = 5; static int SECOND_INDEX = 6; static int MILLI_INDEX = 7; private static PeriodType cStandard; private static PeriodType cYMDTime; private static PeriodType cYMD; private static PeriodType cYWDTime; private static PeriodType cYWD; private static PeriodType cYDTime; private static PeriodType cYD; private static PeriodType cDTime; private static PeriodType cTime; private static PeriodType cYears; private static PeriodType cMonths; private static PeriodType cWeeks; private static PeriodType cDays; private static PeriodType cHours; private static PeriodType cMinutes; private static PeriodType cSeconds; private static PeriodType cMillis; /** * Gets a type that defines all standard fields. *

    *
  • years *
  • months *
  • weeks *
  • days *
  • hours *
  • minutes *
  • seconds *
  • milliseconds *
* * @return the period type */ public static PeriodType standard() { PeriodType type = cStandard; if (type == null) { type = new PeriodType( "Standard", new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.months(), DurationFieldType.weeks(), DurationFieldType.days(), DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, } ); cStandard = type; } return type; } /** * Gets a type that defines all standard fields except weeks. *
    *
  • years *
  • months *
  • days *
  • hours *
  • minutes *
  • seconds *
  • milliseconds *
* * @return the period type */ public static PeriodType yearMonthDayTime() { PeriodType type = cYMDTime; if (type == null) { type = new PeriodType( "YearMonthDayTime", new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.months(), DurationFieldType.days(), DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { 0, 1, -1, 2, 3, 4, 5, 6, } ); cYMDTime = type; } return type; } /** * Gets a type that defines the year, month and day fields. *
    *
  • years *
  • months *
  • days *
* * @return the period type * @since 1.1 */ public static PeriodType yearMonthDay() { PeriodType type = cYMD; if (type == null) { type = new PeriodType( "YearMonthDay", new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.months(), DurationFieldType.days(), }, new int[] { 0, 1, -1, 2, -1, -1, -1, -1, } ); cYMD = type; } return type; } /** * Gets a type that defines all standard fields except months. *
    *
  • years *
  • weeks *
  • days *
  • hours *
  • minutes *
  • seconds *
  • milliseconds *
* * @return the period type */ public static PeriodType yearWeekDayTime() { PeriodType type = cYWDTime; if (type == null) { type = new PeriodType( "YearWeekDayTime", new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.weeks(), DurationFieldType.days(), DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { 0, -1, 1, 2, 3, 4, 5, 6, } ); cYWDTime = type; } return type; } /** * Gets a type that defines year, week and day fields. *
    *
  • years *
  • weeks *
  • days *
* * @return the period type * @since 1.1 */ public static PeriodType yearWeekDay() { PeriodType type = cYWD; if (type == null) { type = new PeriodType( "YearWeekDay", new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.weeks(), DurationFieldType.days(), }, new int[] { 0, -1, 1, 2, -1, -1, -1, -1, } ); cYWD = type; } return type; } /** * Gets a type that defines all standard fields except months and weeks. *
    *
  • years *
  • days *
  • hours *
  • minutes *
  • seconds *
  • milliseconds *
* * @return the period type */ public static PeriodType yearDayTime() { PeriodType type = cYDTime; if (type == null) { type = new PeriodType( "YearDayTime", new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.days(), DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { 0, -1, -1, 1, 2, 3, 4, 5, } ); cYDTime = type; } return type; } /** * Gets a type that defines the year and day fields. *
    *
  • years *
  • days *
* * @return the period type * @since 1.1 */ public static PeriodType yearDay() { PeriodType type = cYD; if (type == null) { type = new PeriodType( "YearDay", new DurationFieldType[] { DurationFieldType.years(), DurationFieldType.days(), }, new int[] { 0, -1, -1, 1, -1, -1, -1, -1, } ); cYD = type; } return type; } /** * Gets a type that defines all standard fields from days downwards. *
    *
  • days *
  • hours *
  • minutes *
  • seconds *
  • milliseconds *
* * @return the period type */ public static PeriodType dayTime() { PeriodType type = cDTime; if (type == null) { type = new PeriodType( "DayTime", new DurationFieldType[] { DurationFieldType.days(), DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { -1, -1, -1, 0, 1, 2, 3, 4, } ); cDTime = type; } return type; } /** * Gets a type that defines all standard time fields. *
    *
  • hours *
  • minutes *
  • seconds *
  • milliseconds *
* * @return the period type */ public static PeriodType time() { PeriodType type = cTime; if (type == null) { type = new PeriodType( "Time", new DurationFieldType[] { DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { -1, -1, -1, -1, 0, 1, 2, 3, } ); cTime = type; } return type; } /** * Gets a type that defines just the years field. * * @return the period type */ public static PeriodType years() { PeriodType type = cYears; if (type == null) { type = new PeriodType( "Years", new DurationFieldType[] { DurationFieldType.years() }, new int[] { 0, -1, -1, -1, -1, -1, -1, -1, } ); cYears = type; } return type; } /** * Gets a type that defines just the months field. * * @return the period type */ public static PeriodType months() { PeriodType type = cMonths; if (type == null) { type = new PeriodType( "Months", new DurationFieldType[] { DurationFieldType.months() }, new int[] { -1, 0, -1, -1, -1, -1, -1, -1, } ); cMonths = type; } return type; } /** * Gets a type that defines just the weeks field. * * @return the period type */ public static PeriodType weeks() { PeriodType type = cWeeks; if (type == null) { type = new PeriodType( "Weeks", new DurationFieldType[] { DurationFieldType.weeks() }, new int[] { -1, -1, 0, -1, -1, -1, -1, -1, } ); cWeeks = type; } return type; } /** * Gets a type that defines just the days field. * * @return the period type */ public static PeriodType days() { PeriodType type = cDays; if (type == null) { type = new PeriodType( "Days", new DurationFieldType[] { DurationFieldType.days() }, new int[] { -1, -1, -1, 0, -1, -1, -1, -1, } ); cDays = type; } return type; } /** * Gets a type that defines just the hours field. * * @return the period type */ public static PeriodType hours() { PeriodType type = cHours; if (type == null) { type = new PeriodType( "Hours", new DurationFieldType[] { DurationFieldType.hours() }, new int[] { -1, -1, -1, -1, 0, -1, -1, -1, } ); cHours = type; } return type; } /** * Gets a type that defines just the minutes field. * * @return the period type */ public static PeriodType minutes() { PeriodType type = cMinutes; if (type == null) { type = new PeriodType( "Minutes", new DurationFieldType[] { DurationFieldType.minutes() }, new int[] { -1, -1, -1, -1, -1, 0, -1, -1, } ); cMinutes = type; } return type; } /** * Gets a type that defines just the seconds field. * * @return the period type */ public static PeriodType seconds() { PeriodType type = cSeconds; if (type == null) { type = new PeriodType( "Seconds", new DurationFieldType[] { DurationFieldType.seconds() }, new int[] { -1, -1, -1, -1, -1, -1, 0, -1, } ); cSeconds = type; } return type; } /** * Gets a type that defines just the millis field. * * @return the period type */ public static PeriodType millis() { PeriodType type = cMillis; if (type == null) { type = new PeriodType( "Millis", new DurationFieldType[] { DurationFieldType.millis() }, new int[] { -1, -1, -1, -1, -1, -1, -1, 0, } ); cMillis = type; } return type; } /** * Gets a period type that contains the duration types of the array. *

* Only the 8 standard duration field types are supported. * * @param types the types to include in the array. * @return the period type * @since 1.1 */ public static synchronized PeriodType forFields(DurationFieldType[] types) { if (types == null || types.length == 0) { throw new IllegalArgumentException("Types array must not be null or empty"); } for (int i = 0; i < types.length; i++) { if (types[i] == null) { throw new IllegalArgumentException("Types array must not contain null"); } } Map cache = cTypes; if (cache.isEmpty()) { cache.put(standard(), standard()); cache.put(yearMonthDayTime(), yearMonthDayTime()); cache.put(yearMonthDay(), yearMonthDay()); cache.put(yearWeekDayTime(), yearWeekDayTime()); cache.put(yearWeekDay(), yearWeekDay()); cache.put(yearDayTime(), yearDayTime()); cache.put(yearDay(), yearDay()); cache.put(dayTime(), dayTime()); cache.put(time(), time()); cache.put(years(), years()); cache.put(months(), months()); cache.put(weeks(), weeks()); cache.put(days(), days()); cache.put(hours(), hours()); cache.put(minutes(), minutes()); cache.put(seconds(), seconds()); cache.put(millis(), millis()); } PeriodType inPartType = new PeriodType(null, types, null); Object cached = cache.get(inPartType); if (cached instanceof PeriodType) { return (PeriodType) cached; } if (cached != null) { throw new IllegalArgumentException("PeriodType does not support fields: " + cached); } PeriodType type = standard(); List list = new ArrayList(Arrays.asList(types)); if (list.remove(DurationFieldType.years()) == false) { type = type.withYearsRemoved(); } if (list.remove(DurationFieldType.months()) == false) { type = type.withMonthsRemoved(); } if (list.remove(DurationFieldType.weeks()) == false) { type = type.withWeeksRemoved(); } if (list.remove(DurationFieldType.days()) == false) { type = type.withDaysRemoved(); } if (list.remove(DurationFieldType.hours()) == false) { type = type.withHoursRemoved(); } if (list.remove(DurationFieldType.minutes()) == false) { type = type.withMinutesRemoved(); } if (list.remove(DurationFieldType.seconds()) == false) { type = type.withSecondsRemoved(); } if (list.remove(DurationFieldType.millis()) == false) { type = type.withMillisRemoved(); } if (list.size() > 0) { cache.put(inPartType, list); throw new IllegalArgumentException("PeriodType does not support fields: " + list); } // recheck cache in case initial array order was wrong PeriodType checkPartType = new PeriodType(null, type.iTypes, null); PeriodType checkedType = (PeriodType) cache.get(checkPartType); if (checkedType != null) { cache.put(checkPartType, checkedType); return checkedType; } cache.put(checkPartType, type); return type; } //----------------------------------------------------------------------- /** The name of the type */ private final String iName; /** The array of types */ private final DurationFieldType[] iTypes; /** The array of indices */ private final int[] iIndices; /** * Constructor. * * @param name the name * @param types the types * @param indices the indices */ protected PeriodType(String name, DurationFieldType[] types, int[] indices) { super(); iName = name; iTypes = types; iIndices = indices; } //----------------------------------------------------------------------- /** * Gets the name of the period type. * * @return the name */ public String getName() { return iName; } /** * Gets the number of fields in the period type. * * @return the number of fields */ public int size() { return iTypes.length; } /** * Gets the field type by index. * * @param index the index to retrieve * @return the field type * @throws IndexOutOfBoundsException if the index is invalid */ public DurationFieldType getFieldType(int index) { return iTypes[index]; } /** * Checks whether the field specified is supported by this period. * * @param type the type to check, may be null which returns false * @return true if the field is supported */ public boolean isSupported(DurationFieldType type) { return (indexOf(type) >= 0); } /** * Gets the index of the field in this period. * * @param type the type to check, may be null which returns -1 * @return the index of -1 if not supported */ public int indexOf(DurationFieldType type) { for (int i = 0, isize = size(); i < isize; i++) { if (iTypes[i] == type) { return i; } } return -1; } /** * Gets a debugging to string. * * @return a string */ public String toString() { return "PeriodType[" + getName() + "]"; } //----------------------------------------------------------------------- /** * Gets the indexed field part of the period. * * @param period the period to query * @param index the index to use * @return the value of the field, zero if unsupported */ int getIndexedField(ReadablePeriod period, int index) { int realIndex = iIndices[index]; return (realIndex == -1 ? 0 : period.getValue(realIndex)); } /** * Sets the indexed field part of the period. * * @param period the period to query * @param index the index to use * @param values the array to populate * @param newValue the value to set * @throws UnsupportedOperationException if not supported */ boolean setIndexedField(ReadablePeriod period, int index, int[] values, int newValue) { int realIndex = iIndices[index]; if (realIndex == -1) { throw new UnsupportedOperationException("Field is not supported"); } values[realIndex] = newValue; return true; } /** * Adds to the indexed field part of the period. * * @param period the period to query * @param index the index to use * @param values the array to populate * @param valueToAdd the value to add * @return true if the array is updated * @throws UnsupportedOperationException if not supported */ boolean addIndexedField(ReadablePeriod period, int index, int[] values, int valueToAdd) { if (valueToAdd == 0) { return false; } int realIndex = iIndices[index]; if (realIndex == -1) { throw new UnsupportedOperationException("Field is not supported"); } values[realIndex] = FieldUtils.safeAdd(values[realIndex], valueToAdd); return true; } //----------------------------------------------------------------------- /** * Returns a version of this PeriodType instance that does not support years. * * @return a new period type that supports the original set of fields except years */ public PeriodType withYearsRemoved() { return withFieldRemoved(0, "NoYears"); } /** * Returns a version of this PeriodType instance that does not support months. * * @return a new period type that supports the original set of fields except months */ public PeriodType withMonthsRemoved() { return withFieldRemoved(1, "NoMonths"); } /** * Returns a version of this PeriodType instance that does not support weeks. * * @return a new period type that supports the original set of fields except weeks */ public PeriodType withWeeksRemoved() { return withFieldRemoved(2, "NoWeeks"); } /** * Returns a version of this PeriodType instance that does not support days. * * @return a new period type that supports the original set of fields except days */ public PeriodType withDaysRemoved() { return withFieldRemoved(3, "NoDays"); } /** * Returns a version of this PeriodType instance that does not support hours. * * @return a new period type that supports the original set of fields except hours */ public PeriodType withHoursRemoved() { return withFieldRemoved(4, "NoHours"); } /** * Returns a version of this PeriodType instance that does not support minutes. * * @return a new period type that supports the original set of fields except minutes */ public PeriodType withMinutesRemoved() { return withFieldRemoved(5, "NoMinutes"); } /** * Returns a version of this PeriodType instance that does not support seconds. * * @return a new period type that supports the original set of fields except seconds */ public PeriodType withSecondsRemoved() { return withFieldRemoved(6, "NoSeconds"); } /** * Returns a version of this PeriodType instance that does not support milliseconds. * * @return a new period type that supports the original set of fields except milliseconds */ public PeriodType withMillisRemoved() { return withFieldRemoved(7, "NoMillis"); } /** * Removes the field specified by indices index. * * @param indicesIndex the index to remove * @param name the name addition * @return the new type */ private PeriodType withFieldRemoved(int indicesIndex, String name) { int fieldIndex = iIndices[indicesIndex]; if (fieldIndex == -1) { return this; } DurationFieldType[] types = new DurationFieldType[size() - 1]; for (int i = 0; i < iTypes.length; i++) { if (i < fieldIndex) { types[i] = iTypes[i]; } else if (i > fieldIndex) { types[i - 1] = iTypes[i]; } } int[] indices = new int[8]; for (int i = 0; i < indices.length; i++) { if (i < indicesIndex) { indices[i] = iIndices[i]; } else if (i > indicesIndex) { indices[i] = (iIndices[i] == -1 ? -1 : iIndices[i] - 1); } else { indices[i] = -1; } } return new PeriodType(getName() + name, types, indices); } //----------------------------------------------------------------------- /** * Compares this type to another object. * To be equal, the object must be a PeriodType with the same set of fields. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof PeriodType == false) { return false; } PeriodType other = (PeriodType) obj; return (Arrays.equals(iTypes, other.iTypes)); } /** * Returns a hashcode based on the field types. * * @return a suitable hashcode */ public int hashCode() { int hash = 0; for (int i = 0; i < iTypes.length; i++) { hash += iTypes[i].hashCode(); } return hash; } } joda-time-2.3/src/main/java/org/joda/time/Instant.java0000644000175000017500000003355711616003375022157 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import org.joda.convert.FromString; import org.joda.time.base.AbstractInstant; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.InstantConverter; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Instant is the standard implementation of a fully immutable instant in time. *

* Instant is an implementation of {@link ReadableInstant}. * As with all instants, it represents an exact point on the time-line, * but limited to the precision of milliseconds. An Instant * should be used to represent a point in time irrespective of any other * factor, such as chronology or time zone. *

* Internally, the class holds one piece of data, the instant as milliseconds * from the Java epoch of 1970-01-01T00:00:00Z. *

* For example, an Instant can be used to compare two DateTime * objects irrespective of chronology or time zone. *

 * boolean sameInstant = dt1.toInstant().equals(dt2.toInstant());
 * 
* Note that the following code will also perform the same check: *
 * boolean sameInstant = dt1.isEqual(dt2);
 * 
*

* Instant is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.0 */ public final class Instant extends AbstractInstant implements ReadableInstant, Serializable { /** Serialization lock */ private static final long serialVersionUID = 3299096530934209741L; /** The millis from 1970-01-01T00:00:00Z */ private final long iMillis; //----------------------------------------------------------------------- /** * Obtains an {@code Instant} set to the current system millisecond time. * * @return the current instant, not null * @since 2.0 */ public static Instant now() { return new Instant(); } //----------------------------------------------------------------------- /** * Parses a {@code Instant} from the specified string. *

* This uses {@link ISODateTimeFormat#dateTimeParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static Instant parse(String str) { return parse(str, ISODateTimeFormat.dateTimeParser()); } /** * Parses a {@code Instant} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static Instant parse(String str, DateTimeFormatter formatter) { return formatter.parseDateTime(str).toInstant(); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current system millisecond time. * * @see #now() */ public Instant() { super(); iMillis = DateTimeUtils.currentTimeMillis(); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public Instant(long instant) { super(); iMillis = instant; } /** * Constructs an instance from an Object that represents a datetime. *

* The recognised object types are defined in {@link ConverterManager} and * include String, Calendar and Date. * * @param instant the datetime object, null means now * @throws IllegalArgumentException if the instant is invalid */ public Instant(Object instant) { super(); InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant); iMillis = converter.getInstantMillis(instant, ISOChronology.getInstanceUTC()); } //----------------------------------------------------------------------- /** * Get this object as an Instant by returning this. * * @return this */ public Instant toInstant() { return this; } //----------------------------------------------------------------------- /** * Gets a copy of this instant with different millis. *

* The returned object will be either be a new Instant or this. * * @param newMillis the new millis, from 1970-01-01T00:00:00Z * @return a copy of this instant with different millis */ public Instant withMillis(long newMillis) { return (newMillis == iMillis ? this : new Instant(newMillis)); } /** * Gets a copy of this instant with the specified duration added. *

* If the addition is zero, then this is returned. * * @param durationToAdd the duration to add to this one * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this instant with the duration added * @throws ArithmeticException if the new instant exceeds the capacity of a long */ public Instant withDurationAdded(long durationToAdd, int scalar) { if (durationToAdd == 0 || scalar == 0) { return this; } long instant = getChronology().add(getMillis(), durationToAdd, scalar); return withMillis(instant); } /** * Gets a copy of this instant with the specified duration added. *

* If the addition is zero, then this is returned. * * @param durationToAdd the duration to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this instant with the duration added * @throws ArithmeticException if the new instant exceeds the capacity of a long */ public Instant withDurationAdded(ReadableDuration durationToAdd, int scalar) { if (durationToAdd == null || scalar == 0) { return this; } return withDurationAdded(durationToAdd.getMillis(), scalar); } //----------------------------------------------------------------------- /** * Gets a copy of this instant with the specified duration added. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to add to this one * @return a copy of this instant with the duration added * @throws ArithmeticException if the new instant exceeds the capacity of a long */ public Instant plus(long duration) { return withDurationAdded(duration, 1); } /** * Gets a copy of this instant with the specified duration added. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to add to this one, null means zero * @return a copy of this instant with the duration added * @throws ArithmeticException if the new instant exceeds the capacity of a long */ public Instant plus(ReadableDuration duration) { return withDurationAdded(duration, 1); } //----------------------------------------------------------------------- /** * Gets a copy of this instant with the specified duration taken away. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to reduce this instant by * @return a copy of this instant with the duration taken away * @throws ArithmeticException if the new instant exceeds the capacity of a long */ public Instant minus(long duration) { return withDurationAdded(duration, -1); } /** * Gets a copy of this instant with the specified duration taken away. *

* If the amount is zero or null, then this is returned. * * @param duration the duration to reduce this instant by * @return a copy of this instant with the duration taken away * @throws ArithmeticException if the new instant exceeds the capacity of a long */ public Instant minus(ReadableDuration duration) { return withDurationAdded(duration, -1); } //----------------------------------------------------------------------- /** * Gets the milliseconds of the instant. * * @return the number of milliseconds since 1970-01-01T00:00:00Z */ public long getMillis() { return iMillis; } /** * Gets the chronology of the instant, which is ISO in the UTC zone. *

* This method returns {@link ISOChronology#getInstanceUTC()} which * corresponds to the definition of the Java epoch 1970-01-01T00:00:00Z. * * @return ISO in the UTC zone */ public Chronology getChronology() { return ISOChronology.getInstanceUTC(); } //----------------------------------------------------------------------- /** * Get this object as a DateTime using ISOChronology in the default zone. *

* This method returns a DateTime object in the default zone. * This differs from the similarly named method on DateTime, DateMidnight * or MutableDateTime which retains the time zone. The difference is * because Instant really represents a time without a zone, * thus calling this method we really have no zone to 'retain' and * hence expect to switch to the default zone. *

* This method definition preserves compatibility with earlier versions * of Joda-Time. * * @return a DateTime using the same millis */ public DateTime toDateTime() { return new DateTime(getMillis(), ISOChronology.getInstance()); } /** * Get this object as a DateTime using ISOChronology in the default zone. * This method is identical to toDateTime(). *

* This method returns a DateTime object in the default zone. * This differs from the similarly named method on DateTime, DateMidnight * or MutableDateTime which retains the time zone. The difference is * because Instant really represents a time without a zone, * thus calling this method we really have no zone to 'retain' and * hence expect to switch to the default zone. *

* This method is deprecated because it is a duplicate of {@link #toDateTime()}. * However, removing it would cause the superclass implementation to be used, * which would create silent bugs in any caller depending on this implementation. * As such, the method itself is not currently planned to be removed. *

* This method definition preserves compatibility with earlier versions * of Joda-Time. * * @return a DateTime using the same millis with ISOChronology * @deprecated Use toDateTime() as it is identical */ @Deprecated public DateTime toDateTimeISO() { return toDateTime(); } /** * Get this object as a MutableDateTime using ISOChronology in the default zone. *

* This method returns a MutableDateTime object in the default zone. * This differs from the similarly named method on DateTime, DateMidnight * or MutableDateTime which retains the time zone. The difference is * because Instant really represents a time without a zone, * thus calling this method we really have no zone to 'retain' and * hence expect to switch to the default zone. *

* This method definition preserves compatibility with earlier versions * of Joda-Time. * * @return a MutableDateTime using the same millis */ public MutableDateTime toMutableDateTime() { return new MutableDateTime(getMillis(), ISOChronology.getInstance()); } /** * Get this object as a MutableDateTime using ISOChronology in the default zone. * This method is identical to toMutableDateTime(). *

* This method returns a MutableDateTime object in the default zone. * This differs from the similarly named method on DateTime, DateMidnight * or MutableDateTime which retains the time zone. The difference is * because Instant really represents a time without a zone, * thus calling this method we really have no zone to 'retain' and * hence expect to switch to the default zone. *

* This method is deprecated because it is a duplicate of {@link #toMutableDateTime()}. * However, removing it would cause the superclass implementation to be used, * which would create silent bugs in any caller depending on this implementation. * As such, the method itself is not currently planned to be removed. *

* This method definition preserves compatibility with earlier versions * of Joda-Time. * * @return a MutableDateTime using the same millis with ISOChronology * @deprecated Use toMutableDateTime() as it is identical */ @Deprecated public MutableDateTime toMutableDateTimeISO() { return toMutableDateTime(); } } joda-time-2.3/src/main/java/org/joda/time/DateTimeField.java0000644000175000017500000007046411564251363023201 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.util.Locale; /** * Defines the calculation engine for date and time fields. * The interface defines a set of methods that manipulate a millisecond datetime * with regards to a single field, such as monthOfYear or secondOfMinute. *

* This design is extensible so, if you wish, you can extract a different field from * the milliseconds. A number of standard implementations are provided to assist. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public abstract class DateTimeField { /** * Get the type of the field. * * @return field type */ public abstract DateTimeFieldType getType(); /** * Get the name of the field. *

* By convention, names follow a pattern of "dddOfRrr", where "ddd" represents * the (singular) duration unit field name and "Rrr" represents the (singular) * duration range field name. If the range field is not applicable, then * the name of the field is simply the (singular) duration field name. * * @return field name */ public abstract String getName(); /** * Returns true if this field is supported. * * @return true if this field is supported */ public abstract boolean isSupported(); /** * Returns true if the set method is lenient. If so, it accepts values that * are out of bounds. For example, a lenient day of month field accepts 32 * for January, converting it to February 1. * * @return true if this field is lenient */ public abstract boolean isLenient(); // Main access API //------------------------------------------------------------------------ /** * Get the value of this field from the milliseconds. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the value of the field, in the units of the field */ public abstract int get(long instant); /** * Get the human-readable, text value of this field from the milliseconds. * If the specified locale is null, the default locale is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public abstract String getAsText(long instant, Locale locale); /** * Get the human-readable, text value of this field from the milliseconds. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the text value of the field */ public abstract String getAsText(long instant); /** * Get the human-readable, text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public abstract String getAsText(ReadablePartial partial, int fieldValue, Locale locale); /** * Get the human-readable, text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * * @param partial the partial instant to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public abstract String getAsText(ReadablePartial partial, Locale locale); /** * Get the human-readable, text value of this field from the field value. * If the specified locale is null, the default locale is used. * * @param fieldValue the numeric value to convert to text * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public abstract String getAsText(int fieldValue, Locale locale); /** * Get the human-readable, short text value of this field from the * milliseconds. If the specified locale is null, the default locale is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null for default * @return the short text value of the field */ public abstract String getAsShortText(long instant, Locale locale); /** * Get the human-readable, short text value of this field from the * milliseconds. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the short text value of the field */ public abstract String getAsShortText(long instant); /** * Get the human-readable, short text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public abstract String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale); /** * Get the human-readable, short text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * * @param partial the partial instant to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public abstract String getAsShortText(ReadablePartial partial, Locale locale); /** * Get the human-readable, short text value of this field from the field value. * If the specified locale is null, the default locale is used. * * @param fieldValue the numeric value to convert to text * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public abstract String getAsShortText(int fieldValue, Locale locale); /** * Adds a value (which may be negative) to the millis value, * overflowing into larger fields if necessary. *

* The value will be added to this field. If the value is too large to be * added solely to this field, larger fields will increase as required. * Smaller fields should be unaffected, except where the result would be * an invalid value for a smaller field. In this case the smaller field is * adjusted to be in range. *

* For example, in the ISO chronology:
* 2000-08-20 add six months is 2001-02-20
* 2000-08-20 add twenty months is 2002-04-20
* 2000-08-20 add minus nine months is 1999-11-20
* 2001-01-31 add one month is 2001-02-28
* 2001-01-31 add two months is 2001-03-31
* * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public abstract long add(long instant, int value); /** * Adds a value (which may be negative) to the millis value, * overflowing into larger fields if necessary. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the long value to add, in the units of the field * @return the updated milliseconds * @throws IllegalArgumentException if value is too large * @see #add(long,int) */ public abstract long add(long instant, long value); /** * Adds a value (which may be negative) to the partial instant, * throwing an exception if the maximum size of the instant is reached. *

* The value will be added to this field, overflowing into larger fields * if necessary. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* Partial instants only contain some fields. This may result in a maximum * possible value, such as TimeOfDay being limited to 23:59:59:999. If this * limit is breached by the add an exception is thrown. *

* For example, in the ISO chronology:
* 2000-08-20 add six months is 2000-02-20
* 2000-08-20 add twenty months is 2000-04-20
* 2000-08-20 add minus nine months is 2000-11-20
* 2001-01-31 add one month is 2001-02-28
* 2001-01-31 add two months is 2001-03-31
* * @param instant the partial instant * @param fieldIndex the index of this field in the instant * @param values the values of the partial instant which should be updated * @param valueToAdd the value to add, in the units of the field * @return the passed in values * @throws IllegalArgumentException if the value is invalid or the maximum instant is reached */ public abstract int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); /** * Adds a value (which may be negative) to the partial instant, * wrapping the whole partial if the maximum size of the partial is reached. *

* The value will be added to this field, overflowing into larger fields * if necessary. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* Partial instants only contain some fields. This may result in a maximum * possible value, such as TimeOfDay normally being limited to 23:59:59:999. * If ths limit is reached by the addition, this method will wrap back to * 00:00:00.000. In fact, you would generally only use this method for * classes that have a limitation such as this. *

* For example, in the ISO chronology:
* 10:20:30 add 20 minutes is 10:40:30
* 10:20:30 add 45 minutes is 11:05:30
* 10:20:30 add 16 hours is 02:20:30
* * @param instant the partial instant * @param fieldIndex the index of this field in the partial * @param values the values of the partial instant which should be updated * @param valueToAdd the value to add, in the units of the field * @return the passed in values * @throws IllegalArgumentException if the value is invalid or the maximum instant is reached */ public abstract int[] addWrapPartial(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); /** * Adds a value (which may be negative) to the millis value, * wrapping within this field. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps. Larger fields are always * unaffected. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* For example, in the ISO chronology:
* 2000-08-20 addWrapField six months is 2000-02-20
* 2000-08-20 addWrapField twenty months is 2000-04-20
* 2000-08-20 addWrapField minus nine months is 2000-11-20
* 2001-01-31 addWrapField one month is 2001-02-28
* 2001-01-31 addWrapField two months is 2001-03-31
* * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public abstract long addWrapField(long instant, int value) ; /** * Adds a value (which may be negative) to the partial instant, * wrapping within this field. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps. Larger fields are always * unaffected. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. *

* For example, in the ISO chronology:
* 2000-08-20 addWrapField six months is 2000-02-20
* 2000-08-20 addWrapField twenty months is 2000-04-20
* 2000-08-20 addWrapField minus nine months is 2000-11-20
* 2001-01-31 addWrapField one month is 2001-02-28
* 2001-01-31 addWrapField two months is 2001-03-31
* * @param instant the partial instant * @param fieldIndex the index of this field in the instant * @param values the values of the partial instant which should be updated * @param valueToAdd the value to add, in the units of the field * @return the passed in values * @throws IllegalArgumentException if the value is invalid */ public abstract int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *

     * long instant = ...
     * int v = ...
     * int age = getDifference(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public abstract int getDifference(long minuendInstant, long subtrahendInstant); /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * *
     * long instant = ...
     * long v = ...
     * long age = getDifferenceAsLong(add(instant, v), instant);
     * 
* * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public abstract long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); /** * Sets a value in the milliseconds supplied. *

* The value of this field will be set. * If the value is invalid, an exception if thrown. *

* If setting this field would make other fields invalid, then those fields * may be changed. For example if the current date is the 31st January, and * the month is set to February, the day would be invalid. Instead, the day * would be changed to the closest value - the 28th/29th February as appropriate. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param value the value to set, in the units of the field * @return the updated milliseconds * @throws IllegalArgumentException if the value is invalid */ public abstract long set(long instant, int value); /** * Sets a value using the specified partial instant. *

* The value of this field (specified by the index) will be set. * If the value is invalid, an exception if thrown. *

* If setting this field would make other fields invalid, then those fields * may be changed. For example if the current date is the 31st January, and * the month is set to February, the day would be invalid. Instead, the day * would be changed to the closest value - the 28th/29th February as appropriate. * * @param instant the partial instant * @param fieldIndex the index of this field in the instant * @param values the values of the partial instant which should be updated * @param newValue the value to set, in the units of the field * @return the passed in values * @throws IllegalArgumentException if the value is invalid */ public abstract int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue); /** * Sets a value in the milliseconds supplied from a human-readable, text value. * If the specified locale is null, the default locale is used. *

* If setting this field would make other fields invalid, then those fields * may be changed. For example if the current date is the 31st January, and * the month is set to February, the day would be invalid. Instead, the day * would be changed to the closest value - the 28th/29th February as appropriate. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param text the text value to set * @param locale the locale to use for selecting a text symbol, null for default * @return the updated milliseconds * @throws IllegalArgumentException if the text value is invalid */ public abstract long set(long instant, String text, Locale locale); /** * Sets a value in the milliseconds supplied from a human-readable, text value. *

* If setting this field would make other fields invalid, then those fields * may be changed. For example if the current date is the 31st January, and * the month is set to February, the day would be invalid. Instead, the day * would be changed to the closest value - the 28th/29th February as appropriate. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in * @param text the text value to set * @return the updated milliseconds * @throws IllegalArgumentException if the text value is invalid */ public abstract long set(long instant, String text); /** * Sets a value in the milliseconds supplied from a human-readable, text value. * If the specified locale is null, the default locale is used. *

* If setting this field would make other fields invalid, then those fields * may be changed. For example if the current date is the 31st January, and * the month is set to February, the day would be invalid. Instead, the day * would be changed to the closest value - the 28th/29th February as appropriate. * * @param instant the partial instant * @param fieldIndex the index of this field in the instant * @param values the values of the partial instant which should be updated * @param text the text value to set * @param locale the locale to use for selecting a text symbol, null for default * @return the passed in values * @throws IllegalArgumentException if the text value is invalid */ public abstract int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale); // Extra information API //------------------------------------------------------------------------ /** * Returns the duration per unit value of this field. For example, if this * field represents "hour of day", then the duration is an hour. * * @return the duration of this field, or UnsupportedDurationField if field * has no duration */ public abstract DurationField getDurationField(); /** * Returns the range duration of this field. For example, if this field * represents "hour of day", then the range duration is a day. * * @return the range duration of this field, or null if field has no range */ public abstract DurationField getRangeDurationField(); /** * Returns whether this field is 'leap' for the specified instant. *

* For example, a leap year would return true, a non leap year would return * false. * * @param instant the instant to check for leap status * @return true if the field is 'leap' */ public abstract boolean isLeap(long instant); /** * Gets the amount by which this field is 'leap' for the specified instant. *

* For example, a leap year would return one, a non leap year would return * zero. * * @param instant the instant to check for leap status * @return the amount, in units of the leap duration field, that the field is leap */ public abstract int getLeapAmount(long instant); /** * If this field were to leap, then it would be in units described by the * returned duration. If this field doesn't ever leap, null is returned. * * @return the leap duration field if field can be leap, null if it can't */ public abstract DurationField getLeapDurationField(); /** * Get the minimum allowable value for this field. * * @return the minimum valid value for this field, in the units of the * field */ public abstract int getMinimumValue(); /** * Get the minimum value for this field evaluated at the specified time. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the minimum value for this field, in the units of the field */ public abstract int getMinimumValue(long instant); /** * Get the minimum value for this field evaluated at the specified time. * * @param instant the partial instant to query * @return the minimum value for this field, in the units of the field */ public abstract int getMinimumValue(ReadablePartial instant); /** * Get the minimum value for this field using the partial instant and * the specified values. * * @param instant the partial instant to query * @param values the values to use * @return the minimum value for this field, in the units of the field */ public abstract int getMinimumValue(ReadablePartial instant, int[] values); /** * Get the maximum allowable value for this field. * * @return the maximum valid value for this field, in the units of the * field */ public abstract int getMaximumValue(); /** * Get the maximum value for this field evaluated at the specified time. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the maximum value for this field, in the units of the field */ public abstract int getMaximumValue(long instant); /** * Get the maximum value for this field evaluated at the specified time. * * @param instant the partial instant to query * @return the maximum value for this field, in the units of the field */ public abstract int getMaximumValue(ReadablePartial instant); /** * Get the maximum value for this field using the partial instant and * the specified values. * * @param instant the partial instant to query * @param values the values to use * @return the maximum value for this field, in the units of the field */ public abstract int getMaximumValue(ReadablePartial instant, int[] values); /** * Get the maximum text value for this field. * * @param locale the locale to use for selecting a text symbol * @return the maximum text length */ public abstract int getMaximumTextLength(Locale locale); /** * Get the maximum short text value for this field. * * @param locale the locale to use for selecting a text symbol * @return the maximum short text length */ public abstract int getMaximumShortTextLength(Locale locale); // Calculation API //------------------------------------------------------------------------ /** * Round to the lowest whole unit of this field. After rounding, the value * of this field and all fields of a higher magnitude are retained. The * fractional millis that cannot be expressed in whole increments of this * field are set to minimum. *

* For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * lowest whole hour is 2002-11-02T23:00:00.000. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundFloor(long instant); /** * Round to the highest whole unit of this field. The value of this field * and all fields of a higher magnitude may be incremented in order to * achieve this result. The fractional millis that cannot be expressed in * whole increments of this field are set to minimum. *

* For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * highest whole hour is 2002-11-03T00:00:00.000. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundCeiling(long instant); /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor or is exactly halfway, this function * behaves like roundFloor. If the millisecond value is closer to the * ceiling, this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundHalfFloor(long instant); /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling or is exactly halfway, * this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundHalfCeiling(long instant); /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling, this function behaves * like roundCeiling. *

* If the millisecond value is exactly halfway between the floor and * ceiling, the ceiling is chosen over the floor only if it makes this * field's value even. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundHalfEven(long instant); /** * Returns the fractional duration milliseconds of this field. In other * words, calling remainder returns the duration that roundFloor would * subtract. *

* For example, on a datetime of 2002-11-02T23:34:56.789, the remainder by * hour is 34 minutes and 56.789 seconds. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to get the * remainder * @return remainder duration, in milliseconds */ public abstract long remainder(long instant); /** * Get a suitable debug string. * * @return debug string */ public abstract String toString(); } joda-time-2.3/src/main/java/org/joda/time/IllegalInstantException.java0000644000175000017500000000664412072543747025336 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.time.format.DateTimeFormat; /** * Exception thrown when attempting to create an instant or date-time that cannot exist. *

* Classes like {@code DateTime} only store valid date-times. * One of the cases where validity is important is handling daylight savings time (DST). * In many places DST is used, where the local clock moves forward by an hour in spring and back by an hour in autumn/fall. * This means that in spring, there is a "gap" where a local time does not exist. *

* This exception refers to this gap, and it means that your application tried to create * a date-time inside the gap - a time that did not exist. * Since Joda-Time objects must be valid, this is not allowed. *

* Possible solutions may be as follows:
* Use LocalDateTime, as all local date-times are valid.
* When converting a LocalDate to a DateTime, then use toDateTimeAsStartOfDay() * as this handles and manages any gaps.
* When parsing, use parseLocalDateTime() if the string being parsed has no time-zone. * * @author Stephen Colebourne * @since 2.2 */ public class IllegalInstantException extends IllegalArgumentException { /** Serialization lock. */ private static final long serialVersionUID = 2858712538216L; /** * Constructor. * * @param message the message */ public IllegalInstantException(String message) { super(message); } /** * Constructor. * * @param instantLocal the local instant * @param zoneId the time-zone ID, may be null */ public IllegalInstantException(long instantLocal, String zoneId) { super(createMessage(instantLocal, zoneId)); } private static String createMessage(long instantLocal, String zoneId) { String localDateTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").print(new Instant(instantLocal)); String zone = (zoneId != null ? " (" + zoneId + ")" : ""); return "Illegal instant due to time zone offset transition (daylight savings time 'gap'): " + localDateTime + zone; } //----------------------------------------------------------------------- /** * Checks if the exception is, or has a cause, of {@code IllegalInstantException}. * * @param ex the exception to check * @return true if an {@code IllegalInstantException} */ public static boolean isIllegalInstant(Throwable ex) { if (ex instanceof IllegalInstantException) { return true; } while (ex.getCause() != null && ex.getCause() != ex) { return isIllegalInstant(ex.getCause()); } return false; } } joda-time-2.3/src/main/java/org/joda/time/Months.java0000644000175000017500000003533411564251363022006 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseSingleFieldPeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period representing a number of months. *

* Months is an immutable period that can only store months. * It does not store years, days or hours for example. As such it is a * type-safe way of representing a number of months in an application. *

* The number of months is set in the constructor, and may be queried using * getMonths(). Basic mathematical operations are provided - * plus(), minus(), multipliedBy() and * dividedBy(). *

* Months is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.4 */ public final class Months extends BaseSingleFieldPeriod { /** Constant representing zero months. */ public static final Months ZERO = new Months(0); /** Constant representing one month. */ public static final Months ONE = new Months(1); /** Constant representing two months. */ public static final Months TWO = new Months(2); /** Constant representing three months. */ public static final Months THREE = new Months(3); /** Constant representing four months. */ public static final Months FOUR = new Months(4); /** Constant representing five months. */ public static final Months FIVE = new Months(5); /** Constant representing six months. */ public static final Months SIX = new Months(6); /** Constant representing seven months. */ public static final Months SEVEN = new Months(7); /** Constant representing eight months. */ public static final Months EIGHT = new Months(8); /** Constant representing nine months. */ public static final Months NINE = new Months(9); /** Constant representing ten months. */ public static final Months TEN = new Months(10); /** Constant representing eleven months. */ public static final Months ELEVEN = new Months(11); /** Constant representing twelve months. */ public static final Months TWELVE = new Months(12); /** Constant representing the maximum number of months that can be stored in this object. */ public static final Months MAX_VALUE = new Months(Integer.MAX_VALUE); /** Constant representing the minimum number of months that can be stored in this object. */ public static final Months MIN_VALUE = new Months(Integer.MIN_VALUE); /** The parser to use for this class. */ private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.months()); /** Serialization version. */ private static final long serialVersionUID = 87525275727380867L; //----------------------------------------------------------------------- /** * Obtains an instance of Months that may be cached. * Months is immutable, so instances can be cached and shared. * This factory method provides access to shared instances. * * @param months the number of months to obtain an instance for * @return the instance of Months */ public static Months months(int months) { switch (months) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case 4: return FOUR; case 5: return FIVE; case 6: return SIX; case 7: return SEVEN; case 8: return EIGHT; case 9: return NINE; case 10: return TEN; case 11: return ELEVEN; case 12: return TWELVE; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Months(months); } } //----------------------------------------------------------------------- /** * Creates a Months representing the number of whole months * between the two specified datetimes. This method corectly handles * any daylight savings time changes that may occur during the interval. * * @param start the start instant, must not be null * @param end the end instant, must not be null * @return the period in months * @throws IllegalArgumentException if the instants are null or invalid */ public static Months monthsBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.months()); return Months.months(amount); } /** * Creates a Months representing the number of whole months * between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalDate objects. * * @param start the start partial date, must not be null * @param end the end partial date, must not be null * @return the period in months * @throws IllegalArgumentException if the partials are null or invalid */ public static Months monthsBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalDate && end instanceof LocalDate) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int months = chrono.months().getDifference( ((LocalDate) end).getLocalMillis(), ((LocalDate) start).getLocalMillis()); return Months.months(months); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Months.months(amount); } /** * Creates a Months representing the number of whole months * in the specified interval. This method corectly handles any daylight * savings time changes that may occur during the interval. * * @param interval the interval to extract months from, null returns zero * @return the period in months * @throws IllegalArgumentException if the partials are null or invalid */ public static Months monthsIn(ReadableInterval interval) { if (interval == null) { return Months.ZERO; } int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.months()); return Months.months(amount); } /** * Creates a new Months by parsing a string in the ISO8601 format 'PnM'. *

* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the * months component may be non-zero. If any other component is non-zero, an exception * will be thrown. * * @param periodStr the period string, null returns zero * @return the period in months * @throws IllegalArgumentException if the string format is invalid */ @FromString public static Months parseMonths(String periodStr) { if (periodStr == null) { return Months.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Months.months(p.getMonths()); } //----------------------------------------------------------------------- /** * Creates a new instance representing a number of months. * You should consider using the factory method {@link #months(int)} * instead of the constructor. * * @param months the number of months to represent */ private Months(int months) { super(months); } /** * Resolves singletons. * * @return the singleton instance */ private Object readResolve() { return Months.months(getValue()); } //----------------------------------------------------------------------- /** * Gets the duration field type, which is months. * * @return the period type */ public DurationFieldType getFieldType() { return DurationFieldType.months(); } /** * Gets the period type, which is months. * * @return the period type */ public PeriodType getPeriodType() { return PeriodType.months(); } //----------------------------------------------------------------------- /** * Gets the number of months that this period represents. * * @return the number of months in the period */ public int getMonths() { return getValue(); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of months added. *

* This instance is immutable and unaffected by this method call. * * @param months the amount of months to add, may be negative * @return the new period plus the specified number of months * @throws ArithmeticException if the result overflows an int */ public Months plus(int months) { if (months == 0) { return this; } return Months.months(FieldUtils.safeAdd(getValue(), months)); } /** * Returns a new instance with the specified number of months added. *

* This instance is immutable and unaffected by this method call. * * @param months the amount of months to add, may be negative, null means zero * @return the new period plus the specified number of months * @throws ArithmeticException if the result overflows an int */ public Months plus(Months months) { if (months == null) { return this; } return plus(months.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of months taken away. *

* This instance is immutable and unaffected by this method call. * * @param months the amount of months to take away, may be negative * @return the new period minus the specified number of months * @throws ArithmeticException if the result overflows an int */ public Months minus(int months) { return plus(FieldUtils.safeNegate(months)); } /** * Returns a new instance with the specified number of months taken away. *

* This instance is immutable and unaffected by this method call. * * @param months the amount of months to take away, may be negative, null means zero * @return the new period minus the specified number of months * @throws ArithmeticException if the result overflows an int */ public Months minus(Months months) { if (months == null) { return this; } return minus(months.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the months multiplied by the specified scalar. *

* This instance is immutable and unaffected by this method call. * * @param scalar the amount to multiply by, may be negative * @return the new period multiplied by the specified scalar * @throws ArithmeticException if the result overflows an int */ public Months multipliedBy(int scalar) { return Months.months(FieldUtils.safeMultiply(getValue(), scalar)); } /** * Returns a new instance with the months divided by the specified divisor. * The calculation uses integer division, thus 3 divided by 2 is 1. *

* This instance is immutable and unaffected by this method call. * * @param divisor the amount to divide by, may be negative * @return the new period divided by the specified divisor * @throws ArithmeticException if the divisor is zero */ public Months dividedBy(int divisor) { if (divisor == 1) { return this; } return Months.months(getValue() / divisor); } //----------------------------------------------------------------------- /** * Returns a new instance with the months value negated. * * @return the new period with a negated value * @throws ArithmeticException if the result overflows an int */ public Months negated() { return Months.months(FieldUtils.safeNegate(getValue())); } //----------------------------------------------------------------------- /** * Is this months instance greater than the specified number of months. * * @param other the other period, null means zero * @return true if this months instance is greater than the specified one */ public boolean isGreaterThan(Months other) { if (other == null) { return getValue() > 0; } return getValue() > other.getValue(); } /** * Is this months instance less than the specified number of months. * * @param other the other period, null means zero * @return true if this months instance is less than the specified one */ public boolean isLessThan(Months other) { if (other == null) { return getValue() < 0; } return getValue() < other.getValue(); } //----------------------------------------------------------------------- /** * Gets this instance as a String in the ISO8601 duration format. *

* For example, "P4M" represents 4 months. * * @return the value as an ISO8601 string */ @ToString public String toString() { return "P" + String.valueOf(getValue()) + "M"; } } joda-time-2.3/src/main/java/org/joda/time/Days.java0000644000175000017500000004614711564251363021442 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseSingleFieldPeriod; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period representing a number of days. *

* Days is an immutable period that can only store days. * It does not store years, months or hours for example. As such it is a * type-safe way of representing a number of days in an application. *

* The number of days is set in the constructor, and may be queried using * getDays(). Basic mathematical operations are provided - * plus(), minus(), multipliedBy() and * dividedBy(). *

* Days is thread-safe and immutable. * * @author Stephen Colebourne * @since 1.4 */ public final class Days extends BaseSingleFieldPeriod { /** Constant representing zero days. */ public static final Days ZERO = new Days(0); /** Constant representing one day. */ public static final Days ONE = new Days(1); /** Constant representing two days. */ public static final Days TWO = new Days(2); /** Constant representing three days. */ public static final Days THREE = new Days(3); /** Constant representing four days. */ public static final Days FOUR = new Days(4); /** Constant representing five days. */ public static final Days FIVE = new Days(5); /** Constant representing six days. */ public static final Days SIX = new Days(6); /** Constant representing seven days. */ public static final Days SEVEN = new Days(7); /** Constant representing the maximum number of days that can be stored in this object. */ public static final Days MAX_VALUE = new Days(Integer.MAX_VALUE); /** Constant representing the minimum number of days that can be stored in this object. */ public static final Days MIN_VALUE = new Days(Integer.MIN_VALUE); /** The paser to use for this class. */ private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.days()); /** Serialization version. */ private static final long serialVersionUID = 87525275727380865L; //----------------------------------------------------------------------- /** * Obtains an instance of Days that may be cached. * Days is immutable, so instances can be cached and shared. * This factory method provides access to shared instances. * * @param days the number of days to obtain an instance for * @return the instance of Days */ public static Days days(int days) { switch (days) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case 4: return FOUR; case 5: return FIVE; case 6: return SIX; case 7: return SEVEN; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Days(days); } } //----------------------------------------------------------------------- /** * Creates a Days representing the number of whole days * between the two specified datetimes. This method corectly handles * any daylight savings time changes that may occur during the interval. * * @param start the start instant, must not be null * @param end the end instant, must not be null * @return the period in days * @throws IllegalArgumentException if the instants are null or invalid */ public static Days daysBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.days()); return Days.days(amount); } /** * Creates a Days representing the number of whole days * between the two specified partial datetimes. *

* The two partials must contain the same fields, for example you can specify * two LocalDate objects. * * @param start the start partial date, must not be null * @param end the end partial date, must not be null * @return the period in days * @throws IllegalArgumentException if the partials are null or invalid */ public static Days daysBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalDate && end instanceof LocalDate) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int days = chrono.days().getDifference( ((LocalDate) end).getLocalMillis(), ((LocalDate) start).getLocalMillis()); return Days.days(days); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Days.days(amount); } /** * Creates a Days representing the number of whole days * in the specified interval. This method corectly handles any daylight * savings time changes that may occur during the interval. * * @param interval the interval to extract days from, null returns zero * @return the period in days * @throws IllegalArgumentException if the partials are null or invalid */ public static Days daysIn(ReadableInterval interval) { if (interval == null) { return Days.ZERO; } int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.days()); return Days.days(amount); } /** * Creates a new Days representing the number of complete * standard length days in the specified period. *

* This factory method converts all fields from the period to hours using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. *

    *
  • One week consists of 7 days. *
  • One day consists of 24 hours. *
  • One hour consists of 60 minutes. *
  • One minute consists of 60 seconds. *
  • One second consists of 1000 milliseconds. *
* Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of hours from, null returns zero * @return the period in days * @throws IllegalArgumentException if the period contains imprecise duration values */ public static Days standardDaysIn(ReadablePeriod period) { int amount = BaseSingleFieldPeriod.standardPeriodIn(period, DateTimeConstants.MILLIS_PER_DAY); return Days.days(amount); } /** * Creates a new Days by parsing a string in the ISO8601 format 'PnD'. *

* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the * days component may be non-zero. If any other component is non-zero, an exception * will be thrown. * * @param periodStr the period string, null returns zero * @return the period in days * @throws IllegalArgumentException if the string format is invalid */ @FromString public static Days parseDays(String periodStr) { if (periodStr == null) { return Days.ZERO; } Period p = PARSER.parsePeriod(periodStr); return Days.days(p.getDays()); } //----------------------------------------------------------------------- /** * Creates a new instance representing a number of days. * You should consider using the factory method {@link #days(int)} * instead of the constructor. * * @param days the number of days to represent */ private Days(int days) { super(days); } /** * Resolves singletons. * * @return the singleton instance */ private Object readResolve() { return Days.days(getValue()); } //----------------------------------------------------------------------- /** * Gets the duration field type, which is days. * * @return the period type */ public DurationFieldType getFieldType() { return DurationFieldType.days(); } /** * Gets the period type, which is days. * * @return the period type */ public PeriodType getPeriodType() { return PeriodType.days(); } //----------------------------------------------------------------------- /** * Converts this period in days to a period in weeks assuming a * 7 day week. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all weeks are * 7 days long. * This may not be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of weeks for this number of days */ public Weeks toStandardWeeks() { return Weeks.weeks(getValue() / DateTimeConstants.DAYS_PER_WEEK); } /** * Converts this period in days to a period in hours assuming a * 24 hour day. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all days are 24 hours long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of hours for this number of days * @throws ArithmeticException if the number of hours is too large to be represented */ public Hours toStandardHours() { return Hours.hours(FieldUtils.safeMultiply(getValue(), DateTimeConstants.HOURS_PER_DAY)); } /** * Converts this period in days to a period in minutes assuming a * 24 hour day and 60 minute hour. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all days are 24 hours * long and all hours are 60 minutes long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of minutes for this number of days * @throws ArithmeticException if the number of minutes is too large to be represented */ public Minutes toStandardMinutes() { return Minutes.minutes(FieldUtils.safeMultiply(getValue(), DateTimeConstants.MINUTES_PER_DAY)); } /** * Converts this period in days to a period in seconds assuming a * 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all days are 24 hours * long, all hours are 60 minutes long and all minutes are 60 seconds long. * This is not true when daylight savings is considered and may also not * be true for some unusual chronologies. However, it is included * as it is a useful operation for many applications and business rules. * * @return a period representing the number of seconds for this number of days * @throws ArithmeticException if the number of seconds is too large to be represented */ public Seconds toStandardSeconds() { return Seconds.seconds(FieldUtils.safeMultiply(getValue(), DateTimeConstants.SECONDS_PER_DAY)); } //----------------------------------------------------------------------- /** * Converts this period in days to a duration in milliseconds assuming a * 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert from a period to a duration. * However to achieve this it makes the assumption that all days are 24 hours * long, all hours are 60 minutes and all minutes are 60 seconds. * This is not true when daylight savings time is considered, and may also * not be true for some unusual chronologies. However, it is included as it * is a useful operation for many applications and business rules. * * @return a duration equivalent to this number of days */ public Duration toStandardDuration() { long days = getValue(); // assign to a long return new Duration(days * DateTimeConstants.MILLIS_PER_DAY); } //----------------------------------------------------------------------- /** * Gets the number of days that this period represents. * * @return the number of days in the period */ public int getDays() { return getValue(); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of days added. *

* This instance is immutable and unaffected by this method call. * * @param days the amount of days to add, may be negative * @return the new period plus the specified number of days * @throws ArithmeticException if the result overflows an int */ public Days plus(int days) { if (days == 0) { return this; } return Days.days(FieldUtils.safeAdd(getValue(), days)); } /** * Returns a new instance with the specified number of days added. *

* This instance is immutable and unaffected by this method call. * * @param days the amount of days to add, may be negative, null means zero * @return the new period plus the specified number of days * @throws ArithmeticException if the result overflows an int */ public Days plus(Days days) { if (days == null) { return this; } return plus(days.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the specified number of days taken away. *

* This instance is immutable and unaffected by this method call. * * @param days the amount of days to take away, may be negative * @return the new period minus the specified number of days * @throws ArithmeticException if the result overflows an int */ public Days minus(int days) { return plus(FieldUtils.safeNegate(days)); } /** * Returns a new instance with the specified number of days taken away. *

* This instance is immutable and unaffected by this method call. * * @param days the amount of days to take away, may be negative, null means zero * @return the new period minus the specified number of days * @throws ArithmeticException if the result overflows an int */ public Days minus(Days days) { if (days == null) { return this; } return minus(days.getValue()); } //----------------------------------------------------------------------- /** * Returns a new instance with the days multiplied by the specified scalar. *

* This instance is immutable and unaffected by this method call. * * @param scalar the amount to multiply by, may be negative * @return the new period multiplied by the specified scalar * @throws ArithmeticException if the result overflows an int */ public Days multipliedBy(int scalar) { return Days.days(FieldUtils.safeMultiply(getValue(), scalar)); } /** * Returns a new instance with the days divided by the specified divisor. * The calculation uses integer division, thus 3 divided by 2 is 1. *

* This instance is immutable and unaffected by this method call. * * @param divisor the amount to divide by, may be negative * @return the new period divided by the specified divisor * @throws ArithmeticException if the divisor is zero */ public Days dividedBy(int divisor) { if (divisor == 1) { return this; } return Days.days(getValue() / divisor); } //----------------------------------------------------------------------- /** * Returns a new instance with the days value negated. * * @return the new period with a negated value * @throws ArithmeticException if the result overflows an int */ public Days negated() { return Days.days(FieldUtils.safeNegate(getValue())); } //----------------------------------------------------------------------- /** * Is this days instance greater than the specified number of days. * * @param other the other period, null means zero * @return true if this days instance is greater than the specified one */ public boolean isGreaterThan(Days other) { if (other == null) { return getValue() > 0; } return getValue() > other.getValue(); } /** * Is this days instance less than the specified number of days. * * @param other the other period, null means zero * @return true if this days instance is less than the specified one */ public boolean isLessThan(Days other) { if (other == null) { return getValue() < 0; } return getValue() < other.getValue(); } //----------------------------------------------------------------------- /** * Gets this instance as a String in the ISO8601 duration format. *

* For example, "P4D" represents 4 days. * * @return the value as an ISO8601 string */ @ToString public String toString() { return "P" + String.valueOf(getValue()) + "D"; } } joda-time-2.3/src/main/java/org/joda/time/YearMonth.java0000644000175000017500000011346111616003375022436 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BasePartial; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractPartialFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * YearMonth is an immutable partial supporting the year and monthOfYear fields. *

* NOTE: This class only supports the two fields listed above. * It is impossible to query any other fields, such as dayOfWeek or centuryOfEra. *

* Calculations on YearMonth are performed using a {@link Chronology}. * This chronology is set to be in the UTC time zone for all calculations. *

* One use case for this class is to store a credit card expiry date, as that only * references the year and month. * This class can be used as the gYearMonth type in XML Schema. *

* Each individual field can be queried in two ways: *

    *
  • getMonthOfYear() *
  • monthOfYear().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value - monthOfYear().get() *
  • text value - monthOfYear().getAsText() *
  • short text value - monthOfYear().getAsShortText() *
  • maximum/minimum values - monthOfYear().getMaximumValue() *
  • add/subtract - monthOfYear().addToCopy() *
  • set - monthOfYear().setCopy() *
*

* YearMonth is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @since 2.0 */ public final class YearMonth extends BasePartial implements ReadablePartial, Serializable { /** Serialization version */ private static final long serialVersionUID = 797544782896179L; /** The singleton set of field types */ private static final DateTimeFieldType[] FIELD_TYPES = new DateTimeFieldType[] { DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), }; /** The index of the year field in the field array */ public static final int YEAR = 0; /** The index of the monthOfYear field in the field array */ public static final int MONTH_OF_YEAR = 1; //----------------------------------------------------------------------- /** * Obtains a {@code YearMonth} set to the current system millisecond time * using ISOChronology in the default time zone. * The resulting object does not use the zone. * * @return the current year-month, not null * @since 2.0 */ public static YearMonth now() { return new YearMonth(); } /** * Obtains a {@code YearMonth} set to the current system millisecond time * using ISOChronology in the specified time zone. * The resulting object does not use the zone. * * @param zone the time zone, not null * @return the current year-month, not null * @since 2.0 */ public static YearMonth now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new YearMonth(zone); } /** * Obtains a {@code YearMonth} set to the current system millisecond time * using the specified chronology. * The resulting object does not use the zone. * * @param chronology the chronology, not null * @return the current year-month, not null * @since 2.0 */ public static YearMonth now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new YearMonth(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code YearMonth} from the specified string. *

* This uses {@link ISODateTimeFormat#localDateParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static YearMonth parse(String str) { return parse(str, ISODateTimeFormat.localDateParser()); } /** * Parses a {@code YearMonth} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static YearMonth parse(String str, DateTimeFormatter formatter) { LocalDate date = formatter.parseLocalDate(str); return new YearMonth(date.getYear(), date.getMonthOfYear()); } //----------------------------------------------------------------------- /** * Constructs a YearMonth from a java.util.Calendar * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Calendar and assigned to the YearMonth. *

* This factory method ignores the type of the calendar and always * creates a YearMonth with ISO chronology. It is expected that you * will only pass in instances of GregorianCalendar however * this is not validated. * * @param calendar the Calendar to extract fields from * @return the created YearMonth, never null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the year or month is invalid for the ISO chronology */ public static YearMonth fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } return new YearMonth(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1); } /** * Constructs a YearMonth from a java.util.Date * using exactly the same field values avoiding any time zone effects. *

* Each field is queried from the Date and assigned to the YearMonth. *

* This factory method always creates a YearMonth with ISO chronology. * * @param date the Date to extract fields from * @return the created YearMonth, never null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the year or month is invalid for the ISO chronology */ @SuppressWarnings("deprecation") public static YearMonth fromDateFields(Date date) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } return new YearMonth(date.getYear() + 1900, date.getMonth() + 1); } //----------------------------------------------------------------------- /** * Constructs a YearMonth with the current year-month, using ISOChronology in * the default zone to extract the fields. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @see #now() */ public YearMonth() { super(); } /** * Constructs a YearMonth with the current year-month, using ISOChronology in * the specified zone to extract the fields. *

* The constructor uses the specified time zone to obtain the current year-month. * Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @param zone the zone to use, null means default zone * @see #now(DateTimeZone) */ public YearMonth(DateTimeZone zone) { super(ISOChronology.getInstance(zone)); } /** * Constructs a YearMonth with the current year-month, using the specified chronology * and zone to extract the fields. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * * @param chronology the chronology, null means ISOChronology in the default zone * @see #now(Chronology) */ public YearMonth(Chronology chronology) { super(chronology); } /** * Constructs a YearMonth extracting the partial fields from the specified * milliseconds using the ISOChronology in the default zone. *

* The constructor uses the default time zone, resulting in the local time * being initialised. Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public YearMonth(long instant) { super(instant); } /** * Constructs a YearMonth extracting the partial fields from the specified * milliseconds using the chronology provided. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in the default zone */ public YearMonth(long instant, Chronology chronology) { super(instant, chronology); } /** * Constructs a YearMonth from an Object that represents some form of time. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateParser()}. *

* The chronology used will be derived from the object, defaulting to ISO. * * @param instant the date-time object, null means now * @throws IllegalArgumentException if the instant is invalid */ public YearMonth(Object instant) { super(instant, null, ISODateTimeFormat.localDateParser()); } /** * Constructs a YearMonth from an Object that represents some form of time, * using the specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateParser()}. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * The specified chronology overrides that of the object. * * @param instant the date-time object, null means now * @param chronology the chronology, null means ISO default * @throws IllegalArgumentException if the instant is invalid */ public YearMonth(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology), ISODateTimeFormat.localDateParser()); } /** * Constructs a YearMonth with specified year and month * using ISOChronology. *

* The constructor uses the no time zone initialising the fields as provided. * Once the constructor is complete, all further calculations * are performed without reference to a time-zone (by switching to UTC). * * @param year the year * @param monthOfYear the month of the year */ public YearMonth(int year, int monthOfYear) { this(year, monthOfYear, null); } /** * Constructs an instance set to the specified year and month * using the specified chronology, whose zone is ignored. *

* If the chronology is null, ISOChronology is used. *

* The constructor uses the time zone of the chronology specified. * Once the constructor is complete, all further calculations are performed * without reference to a time-zone (by switching to UTC). * * @param year the year * @param monthOfYear the month of the year * @param chronology the chronology, null means ISOChronology in the default zone */ public YearMonth(int year, int monthOfYear, Chronology chronology) { super(new int[] {year, monthOfYear}, chronology); } /** * Constructs a YearMonth with chronology from this instance and new values. * * @param partial the partial to base this new instance on * @param values the new set of values */ YearMonth(YearMonth partial, int[] values) { super(partial, values); } /** * Constructs a YearMonth with values from this instance and a new chronology. * * @param partial the partial to base this new instance on * @param chrono the new chronology */ YearMonth(YearMonth partial, Chronology chrono) { super(partial, chrono); } /** * Handle broken serialization from other tools. * @return the resolved object, not null */ private Object readResolve() { if (DateTimeZone.UTC.equals(getChronology().getZone()) == false) { return new YearMonth(this, getChronology().withUTC()); } return this; } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial, which is two. * The supported fields are Year and MonthOfYear. * Note that only these fields may be queried. * * @return the field count, two */ public int size() { return 2; } /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field, never null */ protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case YEAR: return chrono.year(); case MONTH_OF_YEAR: return chrono.monthOfYear(); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index, never null * @throws IndexOutOfBoundsException if the index is invalid */ public DateTimeFieldType getFieldType(int index) { return FIELD_TYPES[index]; } /** * Gets an array of the field type of each of the fields that this partial supports. *

* The fields are returned largest to smallest, Year, Month. * * @return the array of field types (cloned), largest to smallest, never null */ public DateTimeFieldType[] getFieldTypes() { return (DateTimeFieldType[]) FIELD_TYPES.clone(); } //----------------------------------------------------------------------- /** * Returns a copy of this year-month with the specified chronology. * This instance is immutable and unaffected by this method call. *

* This method retains the values of the fields, thus the result will * typically refer to a different instant. *

* The time zone of the specified chronology is ignored, as YearMonth * operates without a time zone. * * @param newChronology the new chronology, null means ISO * @return a copy of this year-month with a different chronology, never null * @throws IllegalArgumentException if the values are invalid for the new chronology */ public YearMonth withChronologyRetainFields(Chronology newChronology) { newChronology = DateTimeUtils.getChronology(newChronology); newChronology = newChronology.withUTC(); if (newChronology == getChronology()) { return this; } else { YearMonth newYearMonth = new YearMonth(this, newChronology); newChronology.validate(newYearMonth, getValues()); return newYearMonth; } } /** * Returns a copy of this year-month with the specified field set to a new value. *

* For example, if the field type is monthOfYear then the month * would be changed in the returned instance. *

* These three lines are equivalent: *

     * YearMonth updated = ym.withField(DateTimeFieldType.monthOfYear(), 6);
     * YearMonth updated = ym.monthOfYear().setCopy(6);
     * YearMonth updated = ym.property(DateTimeFieldType.monthOfYear()).setCopy(6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this instance with the field set, never null * @throws IllegalArgumentException if the value is null or invalid */ public YearMonth withField(DateTimeFieldType fieldType, int value) { int index = indexOfSupported(fieldType); if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new YearMonth(this, newValues); } /** * Returns a copy of this year-month with the value of the specified field increased. *

* If the addition is zero, then this is returned. *

* These three lines are equivalent: *

     * YearMonth added = ym.withFieldAdded(DurationFieldType.months(), 6);
     * YearMonth added = ym.plusMonths(6);
     * YearMonth added = ym.monthOfYear().addToCopy(6);
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this instance with the field updated, never null * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new date-time exceeds the capacity */ public YearMonth withFieldAdded(DurationFieldType fieldType, int amount) { int index = indexOfSupported(fieldType); if (amount == 0) { return this; } int[] newValues = getValues(); newValues = getField(index).add(this, index, newValues, amount); return new YearMonth(this, newValues); } /** * Returns a copy of this year-month with the specified period added. *

* If the addition is zero, then this is returned. * Fields in the period that aren't present in the partial are ignored. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusYears(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this instance with the period added, never null * @throws ArithmeticException if the new date-time exceeds the capacity */ public YearMonth withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } int[] newValues = getValues(); for (int i = 0; i < period.size(); i++) { DurationFieldType fieldType = period.getFieldType(i); int index = indexOf(fieldType); if (index >= 0) { newValues = getField(index).add(this, index, newValues, FieldUtils.safeMultiply(period.getValue(i), scalar)); } } return new YearMonth(this, newValues); } //----------------------------------------------------------------------- /** * Returns a copy of this year-month with the specified period added. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusYears(int)}. * * @param period the duration to add to this one, null means zero * @return a copy of this instance with the period added, never null * @throws ArithmeticException if the new year-month exceeds the capacity */ public YearMonth plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this year-month plus the specified number of years. *

* This year-month instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonth added = ym.plusYears(6);
     * YearMonth added = ym.plus(Period.years(6));
     * YearMonth added = ym.withFieldAdded(DurationFieldType.years(), 6);
     * 
* * @param years the amount of years to add, may be negative * @return the new year-month plus the increased years, never null */ public YearMonth plusYears(int years) { return withFieldAdded(DurationFieldType.years(), years); } /** * Returns a copy of this year-month plus the specified number of months. *

* This year-month instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonth added = ym.plusMonths(6);
     * YearMonth added = ym.plus(Period.months(6));
     * YearMonth added = ym.withFieldAdded(DurationFieldType.months(), 6);
     * 
* * @param months the amount of months to add, may be negative * @return the new year-month plus the increased months, never null */ public YearMonth plusMonths(int months) { return withFieldAdded(DurationFieldType.months(), months); } //----------------------------------------------------------------------- /** * Returns a copy of this year-month with the specified period taken away. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusYears(int)}. * * @param period the period to reduce this instant by * @return a copy of this instance with the period taken away, never null * @throws ArithmeticException if the new year-month exceeds the capacity */ public YearMonth minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this year-month minus the specified number of years. *

* This year-month instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonth subtracted = ym.minusYears(6);
     * YearMonth subtracted = ym.minus(Period.years(6));
     * YearMonth subtracted = ym.withFieldAdded(DurationFieldType.years(), -6);
     * 
* * @param years the amount of years to subtract, may be negative * @return the new year-month minus the increased years, never null */ public YearMonth minusYears(int years) { return withFieldAdded(DurationFieldType.years(), FieldUtils.safeNegate(years)); } /** * Returns a copy of this year-month minus the specified number of months. *

* This year-month instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * YearMonth subtracted = ym.minusMonths(6);
     * YearMonth subtracted = ym.minus(Period.months(6));
     * YearMonth subtracted = ym.withFieldAdded(DurationFieldType.months(), -6);
     * 
* * @param months the amount of months to subtract, may be negative * @return the new year-month minus the increased months, never null */ public YearMonth minusMonths(int months) { return withFieldAdded(DurationFieldType.months(), FieldUtils.safeNegate(months)); } //----------------------------------------------------------------------- /** * Converts this object to a LocalDate with the same year-month and chronology. * * @param dayOfMonth the day of month to use, valid for chronology, such as 1-31 for ISO * @return a LocalDate with the same year-month and chronology, never null */ public LocalDate toLocalDate(int dayOfMonth) { return new LocalDate(getYear(), getMonthOfYear(), dayOfMonth, getChronology()); } //----------------------------------------------------------------------- /** * Converts this object to an Interval representing the whole month. *

* The interval will use the chronology of the year-month in the default zone. *

* This instance is immutable and unaffected by this method call. * * @return an interval over the month, never null */ public Interval toInterval() { return toInterval(null); } /** * Converts this object to an Interval representing the whole month. *

* The interval will use the chronology of the year-month in the specified zone. *

* This instance is immutable and unaffected by this method call. * * @param zone the zone to get the Interval in, null means default * @return an interval over the month, never null */ public Interval toInterval(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); DateTime start = toLocalDate(1).toDateTimeAtStartOfDay(zone); DateTime end = plusMonths(1).toLocalDate(1).toDateTimeAtStartOfDay(zone); return new Interval(start, end); } //----------------------------------------------------------------------- /** * Get the year field value. * * @return the year */ public int getYear() { return getValue(YEAR); } /** * Get the month of year field value. * * @return the month of year */ public int getMonthOfYear() { return getValue(MONTH_OF_YEAR); } //----------------------------------------------------------------------- /** * Returns a copy of this year-month with the year field updated. *

* YearMonth is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year changed. * * @param year the year to set * @return a copy of this object with the field set, never null * @throws IllegalArgumentException if the value is invalid */ public YearMonth withYear(int year) { int[] newValues = getValues(); newValues = getChronology().year().set(this, YEAR, newValues, year); return new YearMonth(this, newValues); } /** * Returns a copy of this year-month with the month of year field updated. *

* YearMonth is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set, never null * @throws IllegalArgumentException if the value is invalid */ public YearMonth withMonthOfYear(int monthOfYear) { int[] newValues = getValues(); newValues = getChronology().monthOfYear().set(this, MONTH_OF_YEAR, newValues, monthOfYear); return new YearMonth(this, newValues); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains * many useful methods. * * @param type the field type to get the property for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType type) { return new Property(this, indexOfSupported(type)); } //----------------------------------------------------------------------- /** * Get the year field property which provides access to advanced functionality. * * @return the year property */ public Property year() { return new Property(this, YEAR); } /** * Get the month of year field property which provides access to advanced functionality. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, MONTH_OF_YEAR); } //----------------------------------------------------------------------- /** * Output the year-month in ISO8601 format (yyyy-MM). * * @return ISO8601 time formatted string. */ @ToString public String toString() { return ISODateTimeFormat.yearMonth().print(this); } /** * Output the year-month using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the year-month using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) throws IllegalArgumentException { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } //----------------------------------------------------------------------- /** * The property class for YearMonth. *

* This class binds a YearMonth to a DateTimeField. * * @author Stephen Colebourne * @since 2.0 */ public static class Property extends AbstractPartialFieldProperty implements Serializable { /** Serialization version */ private static final long serialVersionUID = 5727734012190224363L; /** The partial */ private final YearMonth iBase; /** The field index */ private final int iFieldIndex; /** * Constructs a property. * * @param partial the partial instance * @param fieldIndex the index in the partial */ Property(YearMonth partial, int fieldIndex) { super(); iBase = partial; iFieldIndex = fieldIndex; } /** * Gets the field that this property uses. * * @return the field */ public DateTimeField getField() { return iBase.getField(iFieldIndex); } /** * Gets the partial that this property belongs to. * * @return the partial */ protected ReadablePartial getReadablePartial() { return iBase; } /** * Gets the partial that this property belongs to. * * @return the partial */ public YearMonth getYearMonth() { return iBase; } /** * Gets the value of this field. * * @return the field value */ public int get() { return iBase.getValue(iFieldIndex); } //----------------------------------------------------------------------- /** * Adds to the value of this field in a copy of this YearMonth. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it will affect larger fields. * Smaller fields are unaffected. *

* If the result would be too large, beyond the maximum year, then an * IllegalArgumentException is thrown. *

* The YearMonth attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the YearMonth with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public YearMonth addToCopy(int valueToAdd) { int[] newValues = iBase.getValues(); newValues = getField().add(iBase, iFieldIndex, newValues, valueToAdd); return new YearMonth(iBase, newValues); } /** * Adds to the value of this field in a copy of this YearMonth wrapping * within this field if the maximum value is reached. *

* The value will be added to this field. If the value is too large to be * added solely to this field then it wraps within this field. * Other fields are unaffected. *

* For example, * 2004-12 addWrapField one month returns 2004-01. *

* The YearMonth attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param valueToAdd the value to add to the field in the copy * @return a copy of the YearMonth with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public YearMonth addWrapFieldToCopy(int valueToAdd) { int[] newValues = iBase.getValues(); newValues = getField().addWrapField(iBase, iFieldIndex, newValues, valueToAdd); return new YearMonth(iBase, newValues); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the YearMonth. *

* The YearMonth attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param value the value to set the field in the copy to * @return a copy of the YearMonth with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public YearMonth setCopy(int value) { int[] newValues = iBase.getValues(); newValues = getField().set(iBase, iFieldIndex, newValues, value); return new YearMonth(iBase, newValues); } /** * Sets this field in a copy of the YearMonth to a parsed text value. *

* The YearMonth attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the YearMonth with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public YearMonth setCopy(String text, Locale locale) { int[] newValues = iBase.getValues(); newValues = getField().set(iBase, iFieldIndex, newValues, text, locale); return new YearMonth(iBase, newValues); } /** * Sets this field in a copy of the YearMonth to a parsed text value. *

* The YearMonth attached to this property is unchanged by this call. * Instead, a new instance is returned. * * @param text the text value to set * @return a copy of the YearMonth with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public YearMonth setCopy(String text) { return setCopy(text, null); } } } joda-time-2.3/src/main/java/org/joda/time/Chronology.java0000644000175000017500000004336611564251363022665 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Chronology provides access to the individual date time fields for a * chronological calendar system. *

* Various chronologies are supported by subclasses including ISO * and GregorianJulian. To construct a Chronology you should use the * factory methods on the chronology subclass in the chrono package. *

* For example, to obtain the current time in the coptic calendar system: *

 * DateTime dt = new DateTime(CopticChronology.getInstance());
 * 
*

* The provided chronology implementations are: *

    *
  • ISO - Based on the ISO8601 standard and suitable for use after about 1600 *
  • GJ - Historically accurate calendar with Julian followed by Gregorian *
  • Gregorian - The Gregorian calendar system used for all time (proleptic) *
  • Julian - The Julian calendar system used for all time (proleptic) *
  • Buddhist - The Buddhist calendar system which is an offset in years from GJ *
  • Coptic - The Coptic calendar system which defines 30 day months *
  • Ethiopic - The Ethiopic calendar system which defines 30 day months *
* Hopefully future releases will contain more chronologies. *

* This class defines a number of fields with names from the ISO8601 standard. * It does not 'strongly' define these fields however, thus implementations * are free to interpret the field names as they wish. * For example, a week could be defined as 10 days and a month as 40 days in a * special WeirdChronology implementation. Clearly the GJ and ISO * implementations provided use the field names as you would expect. * * @see org.joda.time.chrono.ISOChronology * @see org.joda.time.chrono.GJChronology * @see org.joda.time.chrono.GregorianChronology * @see org.joda.time.chrono.JulianChronology * @see org.joda.time.chrono.CopticChronology * @see org.joda.time.chrono.BuddhistChronology * @see org.joda.time.chrono.EthiopicChronology * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public abstract class Chronology { /** * Returns the DateTimeZone that this Chronology operates in, or null if * unspecified. * * @return the DateTimeZone, null if unspecified */ public abstract DateTimeZone getZone(); /** * Returns an instance of this Chronology that operates in the UTC time * zone. Chronologies that do not operate in a time zone or are already * UTC must return themself. * * @return a version of this chronology that ignores time zones */ public abstract Chronology withUTC(); /** * Returns an instance of this Chronology that operates in any time zone. * * @return a version of this chronology with a specific time zone * @param zone to use, or default if null * @see org.joda.time.chrono.ZonedChronology */ public abstract Chronology withZone(DateTimeZone zone); /** * Returns a datetime millisecond instant, formed from the given year, * month, day, and millisecond values. The set of given values must refer * to a valid datetime, or else an IllegalArgumentException is thrown. *

* The default implementation calls upon separate DateTimeFields to * determine the result. Subclasses are encouraged to provide a more * efficient implementation. * * @param year year to use * @param monthOfYear month to use * @param dayOfMonth day of month to use * @param millisOfDay millisecond to use * @return millisecond instant from 1970-01-01T00:00:00Z * @throws IllegalArgumentException if the values are invalid */ public abstract long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay); /** * Returns a datetime millisecond instant, formed from the given year, * month, day, hour, minute, second, and millisecond values. The set of * given values must refer to a valid datetime, or else an * IllegalArgumentException is thrown. *

* The default implementation calls upon separate DateTimeFields to * determine the result. Subclasses are encouraged to provide a more * efficient implementation. * * @param year year to use * @param monthOfYear month to use * @param dayOfMonth day of month to use * @param hourOfDay hour to use * @param minuteOfHour minute to use * @param secondOfMinute second to use * @param millisOfSecond millisecond to use * @return millisecond instant from 1970-01-01T00:00:00Z * @throws IllegalArgumentException if the values are invalid */ public abstract long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond); /** * Returns a datetime millisecond instant, from from the given instant, * hour, minute, second, and millisecond values. The set of given values * must refer to a valid datetime, or else an IllegalArgumentException is * thrown. *

* The default implementation calls upon separate DateTimeFields to * determine the result. Subclasses are encouraged to provide a more * efficient implementation. * * @param instant instant to start from * @param hourOfDay hour to use * @param minuteOfHour minute to use * @param secondOfMinute second to use * @param millisOfSecond millisecond to use * @return millisecond instant from 1970-01-01T00:00:00Z * @throws IllegalArgumentException if the values are invalid */ public abstract long getDateTimeMillis(long instant, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond); //----------------------------------------------------------------------- /** * Validates whether the values are valid for the fields of a partial instant. * * @param partial the partial instant to validate * @param values the values to validate, not null, match fields in partial * @throws IllegalArgumentException if the instant is invalid */ public abstract void validate(ReadablePartial partial, int[] values); /** * Gets the values of a partial from an instant. * * @param partial the partial instant to use * @param instant the instant to query * @return the values of this partial extracted from the instant */ public abstract int[] get(ReadablePartial partial, long instant); /** * Sets the partial into the instant. * * @param partial the partial instant to use * @param instant the instant to update * @return the updated instant */ public abstract long set(ReadablePartial partial, long instant); //----------------------------------------------------------------------- /** * Gets the values of a period from an interval. * * @param period the period instant to use * @param startInstant the start instant of an interval to query * @param endInstant the start instant of an interval to query * @return the values of the period extracted from the interval */ public abstract int[] get(ReadablePeriod period, long startInstant, long endInstant); /** * Gets the values of a period from an interval. * * @param period the period instant to use * @param duration the duration to query * @return the values of the period extracted from the duration */ public abstract int[] get(ReadablePeriod period, long duration); /** * Adds the period to the instant, specifying the number of times to add. * * @param period the period to add, null means add nothing * @param instant the instant to add to * @param scalar the number of times to add * @return the updated instant */ public abstract long add(ReadablePeriod period, long instant, int scalar); //----------------------------------------------------------------------- /** * Adds the duration to the instant, specifying the number of times to add. * * @param instant the instant to add to * @param duration the duration to add * @param scalar the number of times to add * @return the updated instant */ public abstract long add(long instant, long duration, int scalar); // Millis //----------------------------------------------------------------------- /** * Get the millis duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField millis(); /** * Get the millis of second field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField millisOfSecond(); /** * Get the millis of day field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField millisOfDay(); // Second //----------------------------------------------------------------------- /** * Get the seconds duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField seconds(); /** * Get the second of minute field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField secondOfMinute(); /** * Get the second of day field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField secondOfDay(); // Minute //----------------------------------------------------------------------- /** * Get the minutes duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField minutes(); /** * Get the minute of hour field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField minuteOfHour(); /** * Get the minute of day field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField minuteOfDay(); // Hour //----------------------------------------------------------------------- /** * Get the hours duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField hours(); /** * Get the hour of day (0-23) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField hourOfDay(); /** * Get the hour of day (offset to 1-24) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField clockhourOfDay(); // Halfday //----------------------------------------------------------------------- /** * Get the halfdays duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField halfdays(); /** * Get the hour of am/pm (0-11) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField hourOfHalfday(); /** * Get the hour of am/pm (offset to 1-12) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField clockhourOfHalfday(); /** * Get the AM(0) PM(1) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField halfdayOfDay(); // Day //----------------------------------------------------------------------- /** * Get the days duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField days(); /** * Get the day of week field for this chronology. * *

DayOfWeek values are defined in {@link DateTimeConstants}. * They use the ISO definitions, where 1 is Monday and 7 is Sunday. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField dayOfWeek(); /** * Get the day of month field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField dayOfMonth(); /** * Get the day of year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField dayOfYear(); // Week //----------------------------------------------------------------------- /** * Get the weeks duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField weeks(); /** * Get the week of a week based year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField weekOfWeekyear(); // Weekyear //----------------------------------------------------------------------- /** * Get the weekyears duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField weekyears(); /** * Get the year of a week based year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField weekyear(); /** * Get the year of a week based year in a century field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField weekyearOfCentury(); // Month //----------------------------------------------------------------------- /** * Get the months duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField months(); /** * Get the month of year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField monthOfYear(); // Year //----------------------------------------------------------------------- /** * Get the years duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField years(); /** * Get the year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField year(); /** * Get the year of era field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField yearOfEra(); /** * Get the year of century field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField yearOfCentury(); // Century //----------------------------------------------------------------------- /** * Get the centuries duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField centuries(); /** * Get the century of era field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField centuryOfEra(); // Era //----------------------------------------------------------------------- /** * Get the eras duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public abstract DurationField eras(); /** * Get the era field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public abstract DateTimeField era(); //----------------------------------------------------------------------- /** * Gets a debugging toString. * * @return a debugging string */ public abstract String toString(); } joda-time-2.3/src/main/java/org/joda/time/chrono/0000755000175000017500000000000012205344143021143 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/chrono/BasicMonthOfYearDateTimeField.java0000644000175000017500000003404512203434736027540 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; import org.joda.time.field.FieldUtils; import org.joda.time.field.ImpreciseDateTimeField; /** * Provides time calculations for the month of the year component of time. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.2, refactored from GJMonthOfYearDateTimeField */ class BasicMonthOfYearDateTimeField extends ImpreciseDateTimeField { /** Serialization version */ @SuppressWarnings("unused") private static final long serialVersionUID = -8258715387168736L; private static final int MIN = DateTimeConstants.JANUARY; private final BasicChronology iChronology; private final int iMax; private final int iLeapMonth; /** * Restricted constructor. * * @param leapMonth the month of year that leaps */ BasicMonthOfYearDateTimeField(BasicChronology chronology, int leapMonth) { super(DateTimeFieldType.monthOfYear(), chronology.getAverageMillisPerMonth()); iChronology = chronology; iMax = iChronology.getMaxMonth(); iLeapMonth = leapMonth; } //----------------------------------------------------------------------- public boolean isLenient() { return false; } //----------------------------------------------------------------------- /** * Get the Month component of the specified time instant. * * @see org.joda.time.DateTimeField#get(long) * @see org.joda.time.ReadableDateTime#getMonthOfYear() * @param instant the time instant in millis to query. * @return the month extracted from the input. */ public int get(long instant) { return iChronology.getMonthOfYear(instant); } //----------------------------------------------------------------------- /** * Add the specified month to the specified time instant. * The amount added may be negative.

* If the new month has less total days than the specified * day of the month, this value is coerced to the nearest * sane value. e.g.

* 07-31 - (1 month) = 06-30

* 03-31 - (1 month) = 02-28 or 02-29 depending

* * @see org.joda.time.DateTimeField#add * @see org.joda.time.ReadWritableDateTime#addMonths(int) * @param instant the time instant in millis to update. * @param months the months to add (can be negative). * @return the updated time instant. */ public long add(long instant, int months) { if (months == 0) { return instant; // the easy case } // // Save time part first. // long timePart = iChronology.getMillisOfDay(instant); // // // Get this year and month. // int thisYear = iChronology.getYear(instant); int thisMonth = iChronology.getMonthOfYear(instant, thisYear); // ---------------------------------------------------------- // // Do not refactor without careful consideration. // Order of calculation is important. // int yearToUse; // Initially, monthToUse is zero-based int monthToUse = thisMonth - 1 + months; if (monthToUse >= 0) { yearToUse = thisYear + (monthToUse / iMax); monthToUse = (monthToUse % iMax) + 1; } else { yearToUse = thisYear + (monthToUse / iMax) - 1; monthToUse = Math.abs(monthToUse); int remMonthToUse = monthToUse % iMax; // Take care of the boundary condition if (remMonthToUse == 0) { remMonthToUse = iMax; } monthToUse = iMax - remMonthToUse + 1; // Take care of the boundary condition if (monthToUse == 1) { yearToUse += 1; } } // End of do not refactor. // ---------------------------------------------------------- // // Quietly force DOM to nearest sane value. // int dayToUse = iChronology.getDayOfMonth(instant, thisYear, thisMonth); int maxDay = iChronology.getDaysInYearMonth(yearToUse, monthToUse); if (dayToUse > maxDay) { dayToUse = maxDay; } // // get proper date part, and return result // long datePart = iChronology.getYearMonthDayMillis(yearToUse, monthToUse, dayToUse); return datePart + timePart; } //----------------------------------------------------------------------- public long add(long instant, long months) { int i_months = (int)months; if (i_months == months) { return add(instant, i_months); } // Copied from add(long, int) and modified slightly: long timePart = iChronology.getMillisOfDay(instant); int thisYear = iChronology.getYear(instant); int thisMonth = iChronology.getMonthOfYear(instant, thisYear); long yearToUse; long monthToUse = thisMonth - 1 + months; if (monthToUse >= 0) { yearToUse = thisYear + (monthToUse / iMax); monthToUse = (monthToUse % iMax) + 1; } else { yearToUse = thisYear + (monthToUse / iMax) - 1; monthToUse = Math.abs(monthToUse); int remMonthToUse = (int)(monthToUse % iMax); if (remMonthToUse == 0) { remMonthToUse = iMax; } monthToUse = iMax - remMonthToUse + 1; if (monthToUse == 1) { yearToUse += 1; } } if (yearToUse < iChronology.getMinYear() || yearToUse > iChronology.getMaxYear()) { throw new IllegalArgumentException ("Magnitude of add amount is too large: " + months); } int i_yearToUse = (int)yearToUse; int i_monthToUse = (int)monthToUse; int dayToUse = iChronology.getDayOfMonth(instant, thisYear, thisMonth); int maxDay = iChronology.getDaysInYearMonth(i_yearToUse, i_monthToUse); if (dayToUse > maxDay) { dayToUse = maxDay; } long datePart = iChronology.getYearMonthDayMillis(i_yearToUse, i_monthToUse, dayToUse); return datePart + timePart; } //----------------------------------------------------------------------- public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) { // overridden as superclass algorithm can't handle // 2004-02-29 + 48 months -> 2008-02-29 type dates if (valueToAdd == 0) { return values; } if (partial.size() > 0 && partial.getFieldType(0).equals(DateTimeFieldType.monthOfYear()) && fieldIndex == 0) { // month is largest field and being added to, such as month-day int curMonth0 = partial.getValue(0) - 1; int newMonth = ((curMonth0 + (valueToAdd % 12) + 12) % 12) + 1; return set(partial, 0, values, newMonth); } if (DateTimeUtils.isContiguous(partial)) { long instant = 0L; for (int i = 0, isize = partial.size(); i < isize; i++) { instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]); } instant = add(instant, valueToAdd); return iChronology.get(partial, instant); } else { return super.add(partial, fieldIndex, values, valueToAdd); } } //----------------------------------------------------------------------- /** * Add to the Month component of the specified time instant * wrapping around within that component if necessary. * * @see org.joda.time.DateTimeField#addWrapField * @param instant the time instant in millis to update. * @param months the months to add (can be negative). * @return the updated time instant. */ public long addWrapField(long instant, int months) { return set(instant, FieldUtils.getWrappedValue(get(instant), months, MIN, iMax)); } //----------------------------------------------------------------------- public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant < subtrahendInstant) { return -getDifference(subtrahendInstant, minuendInstant); } int minuendYear = iChronology.getYear(minuendInstant); int minuendMonth = iChronology.getMonthOfYear(minuendInstant, minuendYear); int subtrahendYear = iChronology.getYear(subtrahendInstant); int subtrahendMonth = iChronology.getMonthOfYear(subtrahendInstant, subtrahendYear); long difference = (minuendYear - subtrahendYear) * ((long) iMax) + minuendMonth - subtrahendMonth; // Before adjusting for remainder, account for special case of add // where the day-of-month is forced to the nearest sane value. int minuendDom = iChronology.getDayOfMonth (minuendInstant, minuendYear, minuendMonth); if (minuendDom == iChronology.getDaysInYearMonth(minuendYear, minuendMonth)) { // Last day of the minuend month... int subtrahendDom = iChronology.getDayOfMonth (subtrahendInstant, subtrahendYear, subtrahendMonth); if (subtrahendDom > minuendDom) { // ...and day of subtrahend month is larger. // Note: This works fine, but it ideally shouldn't invoke other // fields from within a field. subtrahendInstant = iChronology.dayOfMonth().set(subtrahendInstant, minuendDom); } } // Inlined remainder method to avoid duplicate calls. long minuendRem = minuendInstant - iChronology.getYearMonthMillis(minuendYear, minuendMonth); long subtrahendRem = subtrahendInstant - iChronology.getYearMonthMillis(subtrahendYear, subtrahendMonth); if (minuendRem < subtrahendRem) { difference--; } return difference; } //----------------------------------------------------------------------- /** * Set the Month component of the specified time instant.

* If the new month has less total days than the specified * day of the month, this value is coerced to the nearest * sane value. e.g.

* 07-31 to month 6 = 06-30

* 03-31 to month 2 = 02-28 or 02-29 depending

* * @param instant the time instant in millis to update. * @param month the month (1,12) to update the time to. * @return the updated time instant. * @throws IllegalArgumentException if month is invalid */ public long set(long instant, int month) { FieldUtils.verifyValueBounds(this, month, MIN, iMax); // int thisYear = iChronology.getYear(instant); // int thisDom = iChronology.getDayOfMonth(instant, thisYear); int maxDom = iChronology.getDaysInYearMonth(thisYear, month); if (thisDom > maxDom) { // Quietly force DOM to nearest sane value. thisDom = maxDom; } // Return newly calculated millis value return iChronology.getYearMonthDayMillis(thisYear, month, thisDom) + iChronology.getMillisOfDay(instant); } //----------------------------------------------------------------------- public DurationField getRangeDurationField() { return iChronology.years(); } //----------------------------------------------------------------------- public boolean isLeap(long instant) { int thisYear = iChronology.getYear(instant); if (iChronology.isLeapYear(thisYear)) { return (iChronology.getMonthOfYear(instant, thisYear) == iLeapMonth); } return false; } //----------------------------------------------------------------------- public int getLeapAmount(long instant) { return isLeap(instant) ? 1 : 0; } //----------------------------------------------------------------------- public DurationField getLeapDurationField() { return iChronology.days(); } //----------------------------------------------------------------------- public int getMinimumValue() { return MIN; } //----------------------------------------------------------------------- public int getMaximumValue() { return iMax; } //----------------------------------------------------------------------- public long roundFloor(long instant) { int year = iChronology.getYear(instant); int month = iChronology.getMonthOfYear(instant, year); return iChronology.getYearMonthMillis(year, month); } //----------------------------------------------------------------------- public long remainder(long instant) { return instant - roundFloor(instant); } //----------------------------------------------------------------------- /** * Serialization singleton */ private Object readResolve() { return iChronology.monthOfYear(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicDayOfMonthDateTimeField.java0000644000175000017500000000702112203434653027345 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; import org.joda.time.field.PreciseDurationDateTimeField; /** * Provides time calculations for the day of the month component of time. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.1, refactored from GJDayOfMonthDateTimeField */ final class BasicDayOfMonthDateTimeField extends PreciseDurationDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = -4677223814028011723L; private final BasicChronology iChronology; /** * Restricted constructor. */ BasicDayOfMonthDateTimeField(BasicChronology chronology, DurationField days) { super(DateTimeFieldType.dayOfMonth(), days); iChronology = chronology; } //----------------------------------------------------------------------- public int get(long instant) { return iChronology.getDayOfMonth(instant); } public DurationField getRangeDurationField() { return iChronology.months(); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return iChronology.getDaysInMonthMax(); } public int getMaximumValue(long instant) { return iChronology.getDaysInMonthMax(instant); } public int getMaximumValue(ReadablePartial partial) { if (partial.isSupported(DateTimeFieldType.monthOfYear())) { int month = partial.get(DateTimeFieldType.monthOfYear()); if (partial.isSupported(DateTimeFieldType.year())) { int year = partial.get(DateTimeFieldType.year()); return iChronology.getDaysInYearMonth(year, month); } return iChronology.getDaysInMonthMax(month); } return getMaximumValue(); } public int getMaximumValue(ReadablePartial partial, int[] values) { int size = partial.size(); for (int i = 0; i < size; i++) { if (partial.getFieldType(i) == DateTimeFieldType.monthOfYear()) { int month = values[i]; for (int j = 0; j < size; j++) { if (partial.getFieldType(j) == DateTimeFieldType.year()) { int year = values[j]; return iChronology.getDaysInYearMonth(year, month); } } return iChronology.getDaysInMonthMax(month); } } return getMaximumValue(); } protected int getMaximumValueForSet(long instant, int value) { return iChronology.getDaysInMonthMaxForSet(instant, value); } /** * Serialization singleton */ private Object readResolve() { return iChronology.dayOfMonth(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/BaseChronology.java0000644000175000017500000006120212203434660024727 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.io.Serializable; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.IllegalFieldValueException; import org.joda.time.ReadablePartial; import org.joda.time.ReadablePeriod; import org.joda.time.field.FieldUtils; import org.joda.time.field.UnsupportedDateTimeField; import org.joda.time.field.UnsupportedDurationField; /** * BaseChronology provides a skeleton implementation for chronology * classes. Many utility methods are defined, but all fields are unsupported. *

* BaseChronology is thread-safe and immutable, and all subclasses must be * as well. * * @author Brian S O'Neill * @since 1.0 */ public abstract class BaseChronology extends Chronology implements Serializable { /** Serialization version. */ private static final long serialVersionUID = -7310865996721419676L; /** * Restricted constructor. */ protected BaseChronology() { super(); } /** * Returns the DateTimeZone that this Chronology operates in, or null if * unspecified. * * @return DateTimeZone null if unspecified */ public abstract DateTimeZone getZone(); /** * Returns an instance of this Chronology that operates in the UTC time * zone. Chronologies that do not operate in a time zone or are already * UTC must return themself. * * @return a version of this chronology that ignores time zones */ public abstract Chronology withUTC(); /** * Returns an instance of this Chronology that operates in any time zone. * * @return a version of this chronology with a specific time zone * @param zone to use, or default if null * @see org.joda.time.chrono.ZonedChronology */ public abstract Chronology withZone(DateTimeZone zone); /** * Returns a datetime millisecond instant, formed from the given year, * month, day, and millisecond values. The set of given values must refer * to a valid datetime, or else an IllegalArgumentException is thrown. *

* The default implementation calls upon separate DateTimeFields to * determine the result. Subclasses are encouraged to provide a more * efficient implementation. * * @param year year to use * @param monthOfYear month to use * @param dayOfMonth day of month to use * @param millisOfDay millisecond to use * @return millisecond instant from 1970-01-01T00:00:00Z */ public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { long instant = year().set(0, year); instant = monthOfYear().set(instant, monthOfYear); instant = dayOfMonth().set(instant, dayOfMonth); return millisOfDay().set(instant, millisOfDay); } /** * Returns a datetime millisecond instant, formed from the given year, * month, day, hour, minute, second, and millisecond values. The set of * given values must refer to a valid datetime, or else an * IllegalArgumentException is thrown. *

* The default implementation calls upon separate DateTimeFields to * determine the result. Subclasses are encouraged to provide a more * efficient implementation. * * @param year year to use * @param monthOfYear month to use * @param dayOfMonth day of month to use * @param hourOfDay hour to use * @param minuteOfHour minute to use * @param secondOfMinute second to use * @param millisOfSecond millisecond to use * @return millisecond instant from 1970-01-01T00:00:00Z */ public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { long instant = year().set(0, year); instant = monthOfYear().set(instant, monthOfYear); instant = dayOfMonth().set(instant, dayOfMonth); instant = hourOfDay().set(instant, hourOfDay); instant = minuteOfHour().set(instant, minuteOfHour); instant = secondOfMinute().set(instant, secondOfMinute); return millisOfSecond().set(instant, millisOfSecond); } /** * Returns a datetime millisecond instant, from from the given instant, * hour, minute, second, and millisecond values. The set of given values * must refer to a valid datetime, or else an IllegalArgumentException is * thrown. *

* The default implementation calls upon separate DateTimeFields to * determine the result. Subclasses are encouraged to provide a more * efficient implementation. * * @param instant instant to start from * @param hourOfDay hour to use * @param minuteOfHour minute to use * @param secondOfMinute second to use * @param millisOfSecond millisecond to use * @return millisecond instant from 1970-01-01T00:00:00Z */ public long getDateTimeMillis(long instant, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { instant = hourOfDay().set(instant, hourOfDay); instant = minuteOfHour().set(instant, minuteOfHour); instant = secondOfMinute().set(instant, secondOfMinute); return millisOfSecond().set(instant, millisOfSecond); } //----------------------------------------------------------------------- /** * Validates whether the fields stored in a partial instant are valid. *

* This implementation uses {@link DateTimeField#getMinimumValue(ReadablePartial, int[])} * and {@link DateTimeField#getMaximumValue(ReadablePartial, int[])}. * * @param partial the partial instant to validate * @param values the values to validate, not null unless the partial is empty * @throws IllegalArgumentException if the instant is invalid */ public void validate(ReadablePartial partial, int[] values) { // check values in standard range, catching really stupid cases like -1 // this means that the second check will not hit trouble int size = partial.size(); for (int i = 0; i < size; i++) { int value = values[i]; DateTimeField field = partial.getField(i); if (value < field.getMinimumValue()) { throw new IllegalFieldValueException (field.getType(), Integer.valueOf(value), Integer.valueOf(field.getMinimumValue()), null); } if (value > field.getMaximumValue()) { throw new IllegalFieldValueException (field.getType(), Integer.valueOf(value), null, Integer.valueOf(field.getMaximumValue())); } } // check values in specific range, catching really odd cases like 30th Feb for (int i = 0; i < size; i++) { int value = values[i]; DateTimeField field = partial.getField(i); if (value < field.getMinimumValue(partial, values)) { throw new IllegalFieldValueException (field.getType(), Integer.valueOf(value), Integer.valueOf(field.getMinimumValue(partial, values)), null); } if (value > field.getMaximumValue(partial, values)) { throw new IllegalFieldValueException (field.getType(), Integer.valueOf(value), null, Integer.valueOf(field.getMaximumValue(partial, values))); } } } /** * Gets the values of a partial from an instant. * * @param partial the partial instant to use * @param instant the instant to query * @return the values of the partial extracted from the instant */ public int[] get(ReadablePartial partial, long instant) { int size = partial.size(); int[] values = new int[size]; for (int i = 0; i < size; i++) { values[i] = partial.getFieldType(i).getField(this).get(instant); } return values; } /** * Sets the partial into the instant. * * @param partial the partial instant to use * @param instant the instant to update * @return the updated instant */ public long set(ReadablePartial partial, long instant) { for (int i = 0, isize = partial.size(); i < isize; i++) { instant = partial.getFieldType(i).getField(this).set(instant, partial.getValue(i)); } return instant; } //----------------------------------------------------------------------- /** * Gets the values of a period from an interval. * * @param period the period instant to use * @param startInstant the start instant of an interval to query * @param endInstant the start instant of an interval to query * @return the values of the period extracted from the interval */ public int[] get(ReadablePeriod period, long startInstant, long endInstant) { int size = period.size(); int[] values = new int[size]; if (startInstant != endInstant) { for (int i = 0; i < size; i++) { DurationField field = period.getFieldType(i).getField(this); int value = field.getDifference(endInstant, startInstant); startInstant = field.add(startInstant, value); values[i] = value; } } return values; } /** * Gets the values of a period from an interval. * * @param period the period instant to use * @param duration the duration to query * @return the values of the period extracted from the duration */ public int[] get(ReadablePeriod period, long duration) { int size = period.size(); int[] values = new int[size]; if (duration != 0) { long current = 0; for (int i = 0; i < size; i++) { DurationField field = period.getFieldType(i).getField(this); if (field.isPrecise()) { int value = field.getDifference(duration, current); current = field.add(current, value); values[i] = value; } } } return values; } /** * Adds the period to the instant, specifying the number of times to add. * * @param period the period to add, null means add nothing * @param instant the instant to add to * @param scalar the number of times to add * @return the updated instant */ public long add(ReadablePeriod period, long instant, int scalar) { if (scalar != 0 && period != null) { for (int i = 0, isize = period.size(); i < isize; i++) { long value = period.getValue(i); // use long to allow for multiplication (fits OK) if (value != 0) { instant = period.getFieldType(i).getField(this).add(instant, value * scalar); } } } return instant; } //----------------------------------------------------------------------- /** * Adds the duration to the instant, specifying the number of times to add. * * @param instant the instant to add to * @param duration the duration to add * @param scalar the number of times to add * @return the updated instant */ public long add(long instant, long duration, int scalar) { if (duration == 0 || scalar == 0) { return instant; } long add = FieldUtils.safeMultiply(duration, scalar); return FieldUtils.safeAdd(instant, add); } // Millis //----------------------------------------------------------------------- /** * Get the millis duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField millis() { return UnsupportedDurationField.getInstance(DurationFieldType.millis()); } /** * Get the millis of second field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField millisOfSecond() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.millisOfSecond(), millis()); } /** * Get the millis of day field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField millisOfDay() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.millisOfDay(), millis()); } // Second //----------------------------------------------------------------------- /** * Get the seconds duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField seconds() { return UnsupportedDurationField.getInstance(DurationFieldType.seconds()); } /** * Get the second of minute field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField secondOfMinute() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.secondOfMinute(), seconds()); } /** * Get the second of day field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField secondOfDay() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.secondOfDay(), seconds()); } // Minute //----------------------------------------------------------------------- /** * Get the minutes duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField minutes() { return UnsupportedDurationField.getInstance(DurationFieldType.minutes()); } /** * Get the minute of hour field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField minuteOfHour() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.minuteOfHour(), minutes()); } /** * Get the minute of day field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField minuteOfDay() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.minuteOfDay(), minutes()); } // Hour //----------------------------------------------------------------------- /** * Get the hours duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField hours() { return UnsupportedDurationField.getInstance(DurationFieldType.hours()); } /** * Get the hour of day (0-23) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField hourOfDay() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.hourOfDay(), hours()); } /** * Get the hour of day (offset to 1-24) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField clockhourOfDay() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.clockhourOfDay(), hours()); } // Halfday //----------------------------------------------------------------------- /** * Get the halfdays duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField halfdays() { return UnsupportedDurationField.getInstance(DurationFieldType.halfdays()); } /** * Get the hour of am/pm (0-11) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField hourOfHalfday() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.hourOfHalfday(), hours()); } /** * Get the hour of am/pm (offset to 1-12) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField clockhourOfHalfday() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.clockhourOfHalfday(), hours()); } /** * Get the AM(0) PM(1) field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField halfdayOfDay() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.halfdayOfDay(), halfdays()); } // Day //----------------------------------------------------------------------- /** * Get the days duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField days() { return UnsupportedDurationField.getInstance(DurationFieldType.days()); } /** * Get the day of week field for this chronology. * *

DayOfWeek values are defined in * {@link org.joda.time.DateTimeConstants DateTimeConstants}. * They use the ISO definitions, where 1 is Monday and 7 is Sunday. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField dayOfWeek() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.dayOfWeek(), days()); } /** * Get the day of month field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField dayOfMonth() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.dayOfMonth(), days()); } /** * Get the day of year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField dayOfYear() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.dayOfYear(), days()); } // Week //----------------------------------------------------------------------- /** * Get the weeks duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField weeks() { return UnsupportedDurationField.getInstance(DurationFieldType.weeks()); } /** * Get the week of a week based year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField weekOfWeekyear() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.weekOfWeekyear(), weeks()); } // Weekyear //----------------------------------------------------------------------- /** * Get the weekyears duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField weekyears() { return UnsupportedDurationField.getInstance(DurationFieldType.weekyears()); } /** * Get the year of a week based year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField weekyear() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.weekyear(), weekyears()); } /** * Get the year of a week based year in a century field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField weekyearOfCentury() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.weekyearOfCentury(), weekyears()); } // Month //----------------------------------------------------------------------- /** * Get the months duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField months() { return UnsupportedDurationField.getInstance(DurationFieldType.months()); } /** * Get the month of year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField monthOfYear() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.monthOfYear(), months()); } // Year //----------------------------------------------------------------------- /** * Get the years duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField years() { return UnsupportedDurationField.getInstance(DurationFieldType.years()); } /** * Get the year field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField year() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.year(), years()); } /** * Get the year of era field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField yearOfEra() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.yearOfEra(), years()); } /** * Get the year of century field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField yearOfCentury() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.yearOfCentury(), years()); } // Century //----------------------------------------------------------------------- /** * Get the centuries duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField centuries() { return UnsupportedDurationField.getInstance(DurationFieldType.centuries()); } /** * Get the century of era field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField centuryOfEra() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.centuryOfEra(), centuries()); } // Era //----------------------------------------------------------------------- /** * Get the eras duration field for this chronology. * * @return DurationField or UnsupportedDurationField if unsupported */ public DurationField eras() { return UnsupportedDurationField.getInstance(DurationFieldType.eras()); } /** * Get the era field for this chronology. * * @return DateTimeField or UnsupportedDateTimeField if unsupported */ public DateTimeField era() { return UnsupportedDateTimeField.getInstance(DateTimeFieldType.era(), eras()); } //----------------------------------------------------------------------- /** * Gets a debugging toString. * * @return a debugging string */ public abstract String toString(); } joda-time-2.3/src/main/java/org/joda/time/chrono/LimitChronology.java0000644000175000017500000005511112203435057025136 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Locale; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.MutableDateTime; import org.joda.time.ReadableDateTime; import org.joda.time.field.DecoratedDateTimeField; import org.joda.time.field.DecoratedDurationField; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Wraps another Chronology to impose limits on the range of instants that * the fields within a Chronology may support. The limits are applied to both * DateTimeFields and DurationFields. *

* Methods in DateTimeField and DurationField throw an IllegalArgumentException * whenever given an input instant that is outside the limits or when an * attempt is made to move an instant outside the limits. *

* LimitChronology is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class LimitChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = 7670866536893052522L; /** * Wraps another chronology, with datetime limits. When withUTC or * withZone is called, the returned LimitChronology instance has * the same limits, except they are time zone adjusted. * * @param base base chronology to wrap * @param lowerLimit inclusive lower limit, or null if none * @param upperLimit exclusive upper limit, or null if none * @throws IllegalArgumentException if chronology is null or limits are invalid */ public static LimitChronology getInstance(Chronology base, ReadableDateTime lowerLimit, ReadableDateTime upperLimit) { if (base == null) { throw new IllegalArgumentException("Must supply a chronology"); } lowerLimit = lowerLimit == null ? null : lowerLimit.toDateTime(); upperLimit = upperLimit == null ? null : upperLimit.toDateTime(); if (lowerLimit != null && upperLimit != null) { if (!lowerLimit.isBefore(upperLimit)) { throw new IllegalArgumentException ("The lower limit must be come before than the upper limit"); } } return new LimitChronology(base, (DateTime)lowerLimit, (DateTime)upperLimit); } final DateTime iLowerLimit; final DateTime iUpperLimit; private transient LimitChronology iWithUTC; /** * Wraps another chronology, with datetime limits. When withUTC or * withZone is called, the returned LimitChronology instance has * the same limits, except they are time zone adjusted. * * @param lowerLimit inclusive lower limit, or null if none * @param upperLimit exclusive upper limit, or null if none */ private LimitChronology(Chronology base, DateTime lowerLimit, DateTime upperLimit) { super(base, null); // These can be set after assembly. iLowerLimit = lowerLimit; iUpperLimit = upperLimit; } /** * Returns the inclusive lower limit instant. * * @return lower limit */ public DateTime getLowerLimit() { return iLowerLimit; } /** * Returns the inclusive upper limit instant. * * @return upper limit */ public DateTime getUpperLimit() { return iUpperLimit; } /** * If this LimitChronology is already UTC, then this is * returned. Otherwise, a new instance is returned, with the limits * adjusted to the new time zone. */ public Chronology withUTC() { return withZone(DateTimeZone.UTC); } /** * If this LimitChronology has the same time zone as the one given, then * this is returned. Otherwise, a new instance is returned, with the limits * adjusted to the new time zone. */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } if (zone == DateTimeZone.UTC && iWithUTC != null) { return iWithUTC; } DateTime lowerLimit = iLowerLimit; if (lowerLimit != null) { MutableDateTime mdt = lowerLimit.toMutableDateTime(); mdt.setZoneRetainFields(zone); lowerLimit = mdt.toDateTime(); } DateTime upperLimit = iUpperLimit; if (upperLimit != null) { MutableDateTime mdt = upperLimit.toMutableDateTime(); mdt.setZoneRetainFields(zone); upperLimit = mdt.toDateTime(); } LimitChronology chrono = getInstance (getBase().withZone(zone), lowerLimit, upperLimit); if (zone == DateTimeZone.UTC) { iWithUTC = chrono; } return chrono; } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { long instant = getBase().getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); checkLimits(instant, "resulting"); return instant; } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { long instant = getBase().getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); checkLimits(instant, "resulting"); return instant; } public long getDateTimeMillis(long instant, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { checkLimits(instant, null); instant = getBase().getDateTimeMillis (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); checkLimits(instant, "resulting"); return instant; } protected void assemble(Fields fields) { // Keep a local cache of converted fields so as not to create redundant // objects. HashMap converted = new HashMap(); // Convert duration fields... fields.eras = convertField(fields.eras, converted); fields.centuries = convertField(fields.centuries, converted); fields.years = convertField(fields.years, converted); fields.months = convertField(fields.months, converted); fields.weekyears = convertField(fields.weekyears, converted); fields.weeks = convertField(fields.weeks, converted); fields.days = convertField(fields.days, converted); fields.halfdays = convertField(fields.halfdays, converted); fields.hours = convertField(fields.hours, converted); fields.minutes = convertField(fields.minutes, converted); fields.seconds = convertField(fields.seconds, converted); fields.millis = convertField(fields.millis, converted); // Convert datetime fields... fields.year = convertField(fields.year, converted); fields.yearOfEra = convertField(fields.yearOfEra, converted); fields.yearOfCentury = convertField(fields.yearOfCentury, converted); fields.centuryOfEra = convertField(fields.centuryOfEra, converted); fields.era = convertField(fields.era, converted); fields.dayOfWeek = convertField(fields.dayOfWeek, converted); fields.dayOfMonth = convertField(fields.dayOfMonth, converted); fields.dayOfYear = convertField(fields.dayOfYear, converted); fields.monthOfYear = convertField(fields.monthOfYear, converted); fields.weekOfWeekyear = convertField(fields.weekOfWeekyear, converted); fields.weekyear = convertField(fields.weekyear, converted); fields.weekyearOfCentury = convertField(fields.weekyearOfCentury, converted); fields.millisOfSecond = convertField(fields.millisOfSecond, converted); fields.millisOfDay = convertField(fields.millisOfDay, converted); fields.secondOfMinute = convertField(fields.secondOfMinute, converted); fields.secondOfDay = convertField(fields.secondOfDay, converted); fields.minuteOfHour = convertField(fields.minuteOfHour, converted); fields.minuteOfDay = convertField(fields.minuteOfDay, converted); fields.hourOfDay = convertField(fields.hourOfDay, converted); fields.hourOfHalfday = convertField(fields.hourOfHalfday, converted); fields.clockhourOfDay = convertField(fields.clockhourOfDay, converted); fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday, converted); fields.halfdayOfDay = convertField(fields.halfdayOfDay, converted); } private DurationField convertField(DurationField field, HashMap converted) { if (field == null || !field.isSupported()) { return field; } if (converted.containsKey(field)) { return (DurationField)converted.get(field); } LimitDurationField limitField = new LimitDurationField(field); converted.put(field, limitField); return limitField; } private DateTimeField convertField(DateTimeField field, HashMap converted) { if (field == null || !field.isSupported()) { return field; } if (converted.containsKey(field)) { return (DateTimeField)converted.get(field); } LimitDateTimeField limitField = new LimitDateTimeField(field, convertField(field.getDurationField(), converted), convertField(field.getRangeDurationField(), converted), convertField(field.getLeapDurationField(), converted)); converted.put(field, limitField); return limitField; } void checkLimits(long instant, String desc) { DateTime limit; if ((limit = iLowerLimit) != null && instant < limit.getMillis()) { throw new LimitException(desc, true); } if ((limit = iUpperLimit) != null && instant >= limit.getMillis()) { throw new LimitException(desc, false); } } //----------------------------------------------------------------------- /** * A limit chronology is only equal to a limit chronology with the * same base chronology and limits. * * @param obj the object to compare to * @return true if equal * @since 1.4 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof LimitChronology == false) { return false; } LimitChronology chrono = (LimitChronology) obj; return getBase().equals(chrono.getBase()) && FieldUtils.equals(getLowerLimit(), chrono.getLowerLimit()) && FieldUtils.equals(getUpperLimit(), chrono.getUpperLimit()); } /** * A suitable hashcode for the chronology. * * @return the hashcode * @since 1.4 */ public int hashCode() { int hash = 317351877; hash += (getLowerLimit() != null ? getLowerLimit().hashCode() : 0); hash += (getUpperLimit() != null ? getUpperLimit().hashCode() : 0); hash += getBase().hashCode() * 7; return hash; } /** * A debugging string for the chronology. * * @return the debugging string */ public String toString() { return "LimitChronology[" + getBase().toString() + ", " + (getLowerLimit() == null ? "NoLimit" : getLowerLimit().toString()) + ", " + (getUpperLimit() == null ? "NoLimit" : getUpperLimit().toString()) + ']'; } //----------------------------------------------------------------------- /** * Extends IllegalArgumentException such that the exception message is not * generated unless it is actually requested. */ private class LimitException extends IllegalArgumentException { private static final long serialVersionUID = -5924689995607498581L; private final boolean iIsLow; LimitException(String desc, boolean isLow) { super(desc); iIsLow = isLow; } public String getMessage() { StringBuffer buf = new StringBuffer(85); buf.append("The"); String desc = super.getMessage(); if (desc != null) { buf.append(' '); buf.append(desc); } buf.append(" instant is "); DateTimeFormatter p = ISODateTimeFormat.dateTime(); p = p.withChronology(getBase()); if (iIsLow) { buf.append("below the supported minimum of "); p.printTo(buf, getLowerLimit().getMillis()); } else { buf.append("above the supported maximum of "); p.printTo(buf, getUpperLimit().getMillis()); } buf.append(" ("); buf.append(getBase()); buf.append(')'); return buf.toString(); } public String toString() { return "IllegalArgumentException: " + getMessage(); } } private class LimitDurationField extends DecoratedDurationField { private static final long serialVersionUID = 8049297699408782284L; LimitDurationField(DurationField field) { super(field, field.getType()); } public int getValue(long duration, long instant) { checkLimits(instant, null); return getWrappedField().getValue(duration, instant); } public long getValueAsLong(long duration, long instant) { checkLimits(instant, null); return getWrappedField().getValueAsLong(duration, instant); } public long getMillis(int value, long instant) { checkLimits(instant, null); return getWrappedField().getMillis(value, instant); } public long getMillis(long value, long instant) { checkLimits(instant, null); return getWrappedField().getMillis(value, instant); } public long add(long instant, int amount) { checkLimits(instant, null); long result = getWrappedField().add(instant, amount); checkLimits(result, "resulting"); return result; } public long add(long instant, long amount) { checkLimits(instant, null); long result = getWrappedField().add(instant, amount); checkLimits(result, "resulting"); return result; } public int getDifference(long minuendInstant, long subtrahendInstant) { checkLimits(minuendInstant, "minuend"); checkLimits(subtrahendInstant, "subtrahend"); return getWrappedField().getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { checkLimits(minuendInstant, "minuend"); checkLimits(subtrahendInstant, "subtrahend"); return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } } private class LimitDateTimeField extends DecoratedDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = -2435306746995699312L; private final DurationField iDurationField; private final DurationField iRangeDurationField; private final DurationField iLeapDurationField; LimitDateTimeField(DateTimeField field, DurationField durationField, DurationField rangeDurationField, DurationField leapDurationField) { super(field, field.getType()); iDurationField = durationField; iRangeDurationField = rangeDurationField; iLeapDurationField = leapDurationField; } public int get(long instant) { checkLimits(instant, null); return getWrappedField().get(instant); } public String getAsText(long instant, Locale locale) { checkLimits(instant, null); return getWrappedField().getAsText(instant, locale); } public String getAsShortText(long instant, Locale locale) { checkLimits(instant, null); return getWrappedField().getAsShortText(instant, locale); } public long add(long instant, int amount) { checkLimits(instant, null); long result = getWrappedField().add(instant, amount); checkLimits(result, "resulting"); return result; } public long add(long instant, long amount) { checkLimits(instant, null); long result = getWrappedField().add(instant, amount); checkLimits(result, "resulting"); return result; } public long addWrapField(long instant, int amount) { checkLimits(instant, null); long result = getWrappedField().addWrapField(instant, amount); checkLimits(result, "resulting"); return result; } public int getDifference(long minuendInstant, long subtrahendInstant) { checkLimits(minuendInstant, "minuend"); checkLimits(subtrahendInstant, "subtrahend"); return getWrappedField().getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { checkLimits(minuendInstant, "minuend"); checkLimits(subtrahendInstant, "subtrahend"); return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long set(long instant, int value) { checkLimits(instant, null); long result = getWrappedField().set(instant, value); checkLimits(result, "resulting"); return result; } public long set(long instant, String text, Locale locale) { checkLimits(instant, null); long result = getWrappedField().set(instant, text, locale); checkLimits(result, "resulting"); return result; } public final DurationField getDurationField() { return iDurationField; } public final DurationField getRangeDurationField() { return iRangeDurationField; } public boolean isLeap(long instant) { checkLimits(instant, null); return getWrappedField().isLeap(instant); } public int getLeapAmount(long instant) { checkLimits(instant, null); return getWrappedField().getLeapAmount(instant); } public final DurationField getLeapDurationField() { return iLeapDurationField; } public long roundFloor(long instant) { checkLimits(instant, null); long result = getWrappedField().roundFloor(instant); checkLimits(result, "resulting"); return result; } public long roundCeiling(long instant) { checkLimits(instant, null); long result = getWrappedField().roundCeiling(instant); checkLimits(result, "resulting"); return result; } public long roundHalfFloor(long instant) { checkLimits(instant, null); long result = getWrappedField().roundHalfFloor(instant); checkLimits(result, "resulting"); return result; } public long roundHalfCeiling(long instant) { checkLimits(instant, null); long result = getWrappedField().roundHalfCeiling(instant); checkLimits(result, "resulting"); return result; } public long roundHalfEven(long instant) { checkLimits(instant, null); long result = getWrappedField().roundHalfEven(instant); checkLimits(result, "resulting"); return result; } public long remainder(long instant) { checkLimits(instant, null); long result = getWrappedField().remainder(instant); checkLimits(result, "resulting"); return result; } public int getMinimumValue(long instant) { checkLimits(instant, null); return getWrappedField().getMinimumValue(instant); } public int getMaximumValue(long instant) { checkLimits(instant, null); return getWrappedField().getMaximumValue(instant); } public int getMaximumTextLength(Locale locale) { return getWrappedField().getMaximumTextLength(locale); } public int getMaximumShortTextLength(Locale locale) { return getWrappedField().getMaximumShortTextLength(locale); } } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicWeekOfWeekyearDateTimeField.java0000644000175000017500000000767312203434750030225 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; import org.joda.time.field.PreciseDurationDateTimeField; /** * Provides time calculations for the week of a week based year component of time. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.1, refactored from GJWeekOfWeekyearDateTimeField */ final class BasicWeekOfWeekyearDateTimeField extends PreciseDurationDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = -1587436826395135328L; private final BasicChronology iChronology; /** * Restricted constructor */ BasicWeekOfWeekyearDateTimeField(BasicChronology chronology, DurationField weeks) { super(DateTimeFieldType.weekOfWeekyear(), weeks); iChronology = chronology; } /** * Get the week of a week based year component of the specified time instant. * * @see org.joda.time.DateTimeField#get(long) * @param instant the time instant in millis to query. * @return the week of the year extracted from the input. */ public int get(long instant) { return iChronology.getWeekOfWeekyear(instant); } public DurationField getRangeDurationField() { return iChronology.weekyears(); } // 1970-01-01 is day of week 4, Thursday. The rounding methods need to // apply a corrective alignment since weeks begin on day of week 1, Monday. public long roundFloor(long instant) { return super.roundFloor(instant + 3 * DateTimeConstants.MILLIS_PER_DAY) - 3 * DateTimeConstants.MILLIS_PER_DAY; } public long roundCeiling(long instant) { return super.roundCeiling(instant + 3 * DateTimeConstants.MILLIS_PER_DAY) - 3 * DateTimeConstants.MILLIS_PER_DAY; } public long remainder(long instant) { return super.remainder(instant + 3 * DateTimeConstants.MILLIS_PER_DAY); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return 53; } public int getMaximumValue(long instant) { int weekyear = iChronology.getWeekyear(instant); return iChronology.getWeeksInYear(weekyear); } public int getMaximumValue(ReadablePartial partial) { if (partial.isSupported(DateTimeFieldType.weekyear())) { int weekyear = partial.get(DateTimeFieldType.weekyear()); return iChronology.getWeeksInYear(weekyear); } return 53; } public int getMaximumValue(ReadablePartial partial, int[] values) { int size = partial.size(); for (int i = 0; i < size; i++) { if (partial.getFieldType(i) == DateTimeFieldType.weekyear()) { int weekyear = values[i]; return iChronology.getWeeksInYear(weekyear); } } return 53; } protected int getMaximumValueForSet(long instant, int value) { return value > 52 ? getMaximumValue(instant) : 52; } /** * Serialization singleton */ private Object readResolve() { return iChronology.weekOfWeekyear(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/GJDayOfWeekDateTimeField.java0000644000175000017500000001055212203435007026427 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.field.PreciseDurationDateTimeField; /** * GJDayOfWeekDateTimeField provides time calculations for the * day of the week component of time. * * @since 1.0 * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill */ final class GJDayOfWeekDateTimeField extends PreciseDurationDateTimeField { /** Serialization version */ @SuppressWarnings("unused") private static final long serialVersionUID = -3857947176719041436L; private final BasicChronology iChronology; /** * Restricted constructor. */ GJDayOfWeekDateTimeField(BasicChronology chronology, DurationField days) { super(DateTimeFieldType.dayOfWeek(), days); iChronology = chronology; } /** * Get the value of the specified time instant. * * @param instant the time instant in millis to query * @return the day of the week extracted from the input */ public int get(long instant) { return iChronology.getDayOfWeek(instant); } /** * Get the textual value of the specified time instant. * * @param fieldValue the field value to query * @param locale the locale to use * @return the day of the week, such as 'Monday' */ public String getAsText(int fieldValue, Locale locale) { return GJLocaleSymbols.forLocale(locale).dayOfWeekValueToText(fieldValue); } /** * Get the abbreviated textual value of the specified time instant. * * @param fieldValue the field value to query * @param locale the locale to use * @return the day of the week, such as 'Mon' */ public String getAsShortText(int fieldValue, Locale locale) { return GJLocaleSymbols.forLocale(locale).dayOfWeekValueToShortText(fieldValue); } /** * Convert the specified text and locale into a value. * * @param text the text to convert * @param locale the locale to convert using * @return the value extracted from the text * @throws IllegalArgumentException if the text is invalid */ protected int convertText(String text, Locale locale) { return GJLocaleSymbols.forLocale(locale).dayOfWeekTextToValue(text); } public DurationField getRangeDurationField() { return iChronology.weeks(); } /** * Get the minimum value that this field can have. * * @return the field's minimum value */ public int getMinimumValue() { return DateTimeConstants.MONDAY; } /** * Get the maximum value that this field can have. * * @return the field's maximum value */ public int getMaximumValue() { return DateTimeConstants.SUNDAY; } /** * Get the maximum length of the text returned by this field. * * @param locale the locale to use * @return the maximum textual length */ public int getMaximumTextLength(Locale locale) { return GJLocaleSymbols.forLocale(locale).getDayOfWeekMaxTextLength(); } /** * Get the maximum length of the abbreviated text returned by this field. * * @param locale the locale to use * @return the maximum abbreviated textual length */ public int getMaximumShortTextLength(Locale locale) { return GJLocaleSymbols.forLocale(locale).getDayOfWeekMaxShortTextLength(); } /** * Serialization singleton */ private Object readResolve() { return iChronology.dayOfWeek(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/GregorianChronology.java0000644000175000017500000002017311564251363026002 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeZone; /** * Implements a pure proleptic Gregorian calendar system, which defines every * fourth year as leap, unless the year is divisible by 100 and not by 400. * This improves upon the Julian calendar leap year rule. *

* Although the Gregorian calendar did not exist before 1582 CE, this * chronology assumes it did, thus it is proleptic. This implementation also * fixes the start of the year at January 1, and defines the year zero. *

* GregorianChronology is thread-safe and immutable. * * @see Wikipedia * @see JulianChronology * @see GJChronology * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public final class GregorianChronology extends BasicGJChronology { /** Serialization lock */ private static final long serialVersionUID = -861407383323710522L; private static final long MILLIS_PER_YEAR = (long) (365.2425 * DateTimeConstants.MILLIS_PER_DAY); private static final long MILLIS_PER_MONTH = (long) (365.2425 * DateTimeConstants.MILLIS_PER_DAY / 12); private static final int DAYS_0000_TO_1970 = 719527; /** The lowest year that can be fully supported. */ private static final int MIN_YEAR = -292275054; /** The highest year that can be fully supported. */ private static final int MAX_YEAR = 292278993; /** Singleton instance of a UTC GregorianChronology */ private static final GregorianChronology INSTANCE_UTC; /** Cache of zone to chronology arrays */ private static final Map cCache = new HashMap(); static { INSTANCE_UTC = getInstance(DateTimeZone.UTC); } /** * Gets an instance of the GregorianChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ public static GregorianChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the GregorianChronology in the default time zone. * * @return a chronology in the default time zone */ public static GregorianChronology getInstance() { return getInstance(DateTimeZone.getDefault(), 4); } /** * Gets an instance of the GregorianChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @return a chronology in the specified time zone */ public static GregorianChronology getInstance(DateTimeZone zone) { return getInstance(zone, 4); } /** * Gets an instance of the GregorianChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 * @return a chronology in the specified time zone */ public static GregorianChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { if (zone == null) { zone = DateTimeZone.getDefault(); } GregorianChronology chrono; synchronized (cCache) { GregorianChronology[] chronos = cCache.get(zone); if (chronos == null) { chronos = new GregorianChronology[7]; cCache.put(zone, chronos); } try { chrono = chronos[minDaysInFirstWeek - 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException ("Invalid min days in first week: " + minDaysInFirstWeek); } if (chrono == null) { if (zone == DateTimeZone.UTC) { chrono = new GregorianChronology(null, null, minDaysInFirstWeek); } else { chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); chrono = new GregorianChronology (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); } chronos[minDaysInFirstWeek - 1] = chrono; } } return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor */ private GregorianChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } /** * Serialization singleton */ private Object readResolve() { Chronology base = getBase(); int minDays = getMinimumDaysInFirstWeek(); minDays = (minDays == 0 ? 4 : minDays); // handle rename of BaseGJChronology return base == null ? getInstance(DateTimeZone.UTC, minDays) : getInstance(base.getZone(), minDays); } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } protected void assemble(Fields fields) { if (getBase() == null) { super.assemble(fields); } } boolean isLeapYear(int year) { return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0); } long calculateFirstDayOfYearMillis(int year) { // Initial value is just temporary. int leapYears = year / 100; if (year < 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. When the expression is written as // (year / 4) - (year / 100) + (year / 400), // it works for both positive and negative values, except this optimization // eliminates two divisions. leapYears = ((year + 3) >> 2) - leapYears + ((leapYears + 3) >> 2) - 1; } else { leapYears = (year >> 2) - leapYears + (leapYears >> 2); if (isLeapYear(year)) { leapYears--; } } return (year * 365L + (leapYears - DAYS_0000_TO_1970)) * DateTimeConstants.MILLIS_PER_DAY; } int getMinYear() { return MIN_YEAR; } int getMaxYear() { return MAX_YEAR; } long getAverageMillisPerYear() { return MILLIS_PER_YEAR; } long getAverageMillisPerYearDividedByTwo() { return MILLIS_PER_YEAR / 2; } long getAverageMillisPerMonth() { return MILLIS_PER_MONTH; } long getApproxMillisAtEpochDividedByTwo() { return (1970L * MILLIS_PER_YEAR) / 2; } } joda-time-2.3/src/main/java/org/joda/time/chrono/ZonedChronology.java0000644000175000017500000005655712203435064025154 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Locale; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.IllegalFieldValueException; import org.joda.time.IllegalInstantException; import org.joda.time.ReadablePartial; import org.joda.time.field.BaseDateTimeField; import org.joda.time.field.BaseDurationField; /** * Wraps another Chronology to add support for time zones. *

* ZonedChronology is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class ZonedChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = -1079258847191166848L; /** * Create a ZonedChronology for any chronology, overriding any time zone it * may already have. * * @param base base chronology to wrap * @param zone the time zone * @throws IllegalArgumentException if chronology or time zone is null */ public static ZonedChronology getInstance(Chronology base, DateTimeZone zone) { if (base == null) { throw new IllegalArgumentException("Must supply a chronology"); } base = base.withUTC(); if (base == null) { throw new IllegalArgumentException("UTC chronology must not be null"); } if (zone == null) { throw new IllegalArgumentException("DateTimeZone must not be null"); } return new ZonedChronology(base, zone); } static boolean useTimeArithmetic(DurationField field) { // Use time of day arithmetic rules for unit durations less than // typical time zone offsets. return field != null && field.getUnitMillis() < DateTimeConstants.MILLIS_PER_HOUR * 12; } /** * Restricted constructor * * @param base base chronology to wrap * @param zone the time zone */ private ZonedChronology(Chronology base, DateTimeZone zone) { super(base, zone); } public DateTimeZone getZone() { return (DateTimeZone)getParam(); } public Chronology withUTC() { return getBase(); } public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getParam()) { return this; } if (zone == DateTimeZone.UTC) { return getBase(); } return new ZonedChronology(getBase(), zone); } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { return localToUTC(getBase().getDateTimeMillis (year, monthOfYear, dayOfMonth, millisOfDay)); } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { return localToUTC(getBase().getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond)); } public long getDateTimeMillis(long instant, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { return localToUTC(getBase().getDateTimeMillis (instant + getZone().getOffset(instant), hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond)); } /** * @param localInstant the instant from 1970-01-01T00:00:00 local time * @return the instant from 1970-01-01T00:00:00Z */ private long localToUTC(long localInstant) { DateTimeZone zone = getZone(); int offset = zone.getOffsetFromLocal(localInstant); localInstant -= offset; if (offset != zone.getOffset(localInstant)) { throw new IllegalInstantException(localInstant, zone.getID()); } return localInstant; } protected void assemble(Fields fields) { // Keep a local cache of converted fields so as not to create redundant // objects. HashMap converted = new HashMap(); // Convert duration fields... fields.eras = convertField(fields.eras, converted); fields.centuries = convertField(fields.centuries, converted); fields.years = convertField(fields.years, converted); fields.months = convertField(fields.months, converted); fields.weekyears = convertField(fields.weekyears, converted); fields.weeks = convertField(fields.weeks, converted); fields.days = convertField(fields.days, converted); fields.halfdays = convertField(fields.halfdays, converted); fields.hours = convertField(fields.hours, converted); fields.minutes = convertField(fields.minutes, converted); fields.seconds = convertField(fields.seconds, converted); fields.millis = convertField(fields.millis, converted); // Convert datetime fields... fields.year = convertField(fields.year, converted); fields.yearOfEra = convertField(fields.yearOfEra, converted); fields.yearOfCentury = convertField(fields.yearOfCentury, converted); fields.centuryOfEra = convertField(fields.centuryOfEra, converted); fields.era = convertField(fields.era, converted); fields.dayOfWeek = convertField(fields.dayOfWeek, converted); fields.dayOfMonth = convertField(fields.dayOfMonth, converted); fields.dayOfYear = convertField(fields.dayOfYear, converted); fields.monthOfYear = convertField(fields.monthOfYear, converted); fields.weekOfWeekyear = convertField(fields.weekOfWeekyear, converted); fields.weekyear = convertField(fields.weekyear, converted); fields.weekyearOfCentury = convertField(fields.weekyearOfCentury, converted); fields.millisOfSecond = convertField(fields.millisOfSecond, converted); fields.millisOfDay = convertField(fields.millisOfDay, converted); fields.secondOfMinute = convertField(fields.secondOfMinute, converted); fields.secondOfDay = convertField(fields.secondOfDay, converted); fields.minuteOfHour = convertField(fields.minuteOfHour, converted); fields.minuteOfDay = convertField(fields.minuteOfDay, converted); fields.hourOfDay = convertField(fields.hourOfDay, converted); fields.hourOfHalfday = convertField(fields.hourOfHalfday, converted); fields.clockhourOfDay = convertField(fields.clockhourOfDay, converted); fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday, converted); fields.halfdayOfDay = convertField(fields.halfdayOfDay, converted); } private DurationField convertField(DurationField field, HashMap converted) { if (field == null || !field.isSupported()) { return field; } if (converted.containsKey(field)) { return (DurationField)converted.get(field); } ZonedDurationField zonedField = new ZonedDurationField(field, getZone()); converted.put(field, zonedField); return zonedField; } private DateTimeField convertField(DateTimeField field, HashMap converted) { if (field == null || !field.isSupported()) { return field; } if (converted.containsKey(field)) { return (DateTimeField)converted.get(field); } ZonedDateTimeField zonedField = new ZonedDateTimeField(field, getZone(), convertField(field.getDurationField(), converted), convertField(field.getRangeDurationField(), converted), convertField(field.getLeapDurationField(), converted)); converted.put(field, zonedField); return zonedField; } //----------------------------------------------------------------------- /** * A zoned chronology is only equal to a zoned chronology with the * same base chronology and zone. * * @param obj the object to compare to * @return true if equal * @since 1.4 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ZonedChronology == false) { return false; } ZonedChronology chrono = (ZonedChronology) obj; return getBase().equals(chrono.getBase()) && getZone().equals(chrono.getZone()); } /** * A suitable hashcode for the chronology. * * @return the hashcode * @since 1.4 */ public int hashCode() { return 326565 + getZone().hashCode() * 11 + getBase().hashCode() * 7; } /** * A debugging string for the chronology. * * @return the debugging string */ public String toString() { return "ZonedChronology[" + getBase() + ", " + getZone().getID() + ']'; } //----------------------------------------------------------------------- /* * Because time durations are typically smaller than time zone offsets, the * arithmetic methods subtract the original offset. This produces a more * expected behavior when crossing time zone offset transitions. For dates, * the new offset is subtracted off. This behavior, if applied to time * fields, can nullify or reverse an add when crossing a transition. */ static class ZonedDurationField extends BaseDurationField { private static final long serialVersionUID = -485345310999208286L; final DurationField iField; final boolean iTimeField; final DateTimeZone iZone; ZonedDurationField(DurationField field, DateTimeZone zone) { super(field.getType()); if (!field.isSupported()) { throw new IllegalArgumentException(); } iField = field; iTimeField = useTimeArithmetic(field); iZone = zone; } public boolean isPrecise() { return iTimeField ? iField.isPrecise() : iField.isPrecise() && this.iZone.isFixed(); } public long getUnitMillis() { return iField.getUnitMillis(); } public int getValue(long duration, long instant) { return iField.getValue(duration, addOffset(instant)); } public long getValueAsLong(long duration, long instant) { return iField.getValueAsLong(duration, addOffset(instant)); } public long getMillis(int value, long instant) { return iField.getMillis(value, addOffset(instant)); } public long getMillis(long value, long instant) { return iField.getMillis(value, addOffset(instant)); } public long add(long instant, int value) { int offset = getOffsetToAdd(instant); instant = iField.add(instant + offset, value); return instant - (iTimeField ? offset : getOffsetFromLocalToSubtract(instant)); } public long add(long instant, long value) { int offset = getOffsetToAdd(instant); instant = iField.add(instant + offset, value); return instant - (iTimeField ? offset : getOffsetFromLocalToSubtract(instant)); } public int getDifference(long minuendInstant, long subtrahendInstant) { int offset = getOffsetToAdd(subtrahendInstant); return iField.getDifference (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)), subtrahendInstant + offset); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { int offset = getOffsetToAdd(subtrahendInstant); return iField.getDifferenceAsLong (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)), subtrahendInstant + offset); } private int getOffsetToAdd(long instant) { int offset = this.iZone.getOffset(instant); long sum = instant + offset; // If there is a sign change, but the two values have the same sign... if ((instant ^ sum) < 0 && (instant ^ offset) >= 0) { throw new ArithmeticException("Adding time zone offset caused overflow"); } return offset; } private int getOffsetFromLocalToSubtract(long instant) { int offset = this.iZone.getOffsetFromLocal(instant); long diff = instant - offset; // If there is a sign change, but the two values have different signs... if ((instant ^ diff) < 0 && (instant ^ offset) < 0) { throw new ArithmeticException("Subtracting time zone offset caused overflow"); } return offset; } private long addOffset(long instant) { return iZone.convertUTCToLocal(instant); } } /** * A DateTimeField that decorates another to add timezone behaviour. *

* This class converts passed in instants to local wall time, and vice * versa on output. */ static final class ZonedDateTimeField extends BaseDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = -3968986277775529794L; final DateTimeField iField; final DateTimeZone iZone; final DurationField iDurationField; final boolean iTimeField; final DurationField iRangeDurationField; final DurationField iLeapDurationField; ZonedDateTimeField(DateTimeField field, DateTimeZone zone, DurationField durationField, DurationField rangeDurationField, DurationField leapDurationField) { super(field.getType()); if (!field.isSupported()) { throw new IllegalArgumentException(); } iField = field; iZone = zone; iDurationField = durationField; iTimeField = useTimeArithmetic(durationField); iRangeDurationField = rangeDurationField; iLeapDurationField = leapDurationField; } public boolean isLenient() { return iField.isLenient(); } public int get(long instant) { long localInstant = iZone.convertUTCToLocal(instant); return iField.get(localInstant); } public String getAsText(long instant, Locale locale) { long localInstant = iZone.convertUTCToLocal(instant); return iField.getAsText(localInstant, locale); } public String getAsShortText(long instant, Locale locale) { long localInstant = iZone.convertUTCToLocal(instant); return iField.getAsShortText(localInstant, locale); } public String getAsText(int fieldValue, Locale locale) { return iField.getAsText(fieldValue, locale); } public String getAsShortText(int fieldValue, Locale locale) { return iField.getAsShortText(fieldValue, locale); } public long add(long instant, int value) { if (iTimeField) { int offset = getOffsetToAdd(instant); long localInstant = iField.add(instant + offset, value); return localInstant - offset; } else { long localInstant = iZone.convertUTCToLocal(instant); localInstant = iField.add(localInstant, value); return iZone.convertLocalToUTC(localInstant, false, instant); } } public long add(long instant, long value) { if (iTimeField) { int offset = getOffsetToAdd(instant); long localInstant = iField.add(instant + offset, value); return localInstant - offset; } else { long localInstant = iZone.convertUTCToLocal(instant); localInstant = iField.add(localInstant, value); return iZone.convertLocalToUTC(localInstant, false, instant); } } public long addWrapField(long instant, int value) { if (iTimeField) { int offset = getOffsetToAdd(instant); long localInstant = iField.addWrapField(instant + offset, value); return localInstant - offset; } else { long localInstant = iZone.convertUTCToLocal(instant); localInstant = iField.addWrapField(localInstant, value); return iZone.convertLocalToUTC(localInstant, false, instant); } } public long set(long instant, int value) { long localInstant = iZone.convertUTCToLocal(instant); localInstant = iField.set(localInstant, value); long result = iZone.convertLocalToUTC(localInstant, false, instant); if (get(result) != value) { IllegalInstantException cause = new IllegalInstantException(localInstant, iZone.getID()); IllegalFieldValueException ex = new IllegalFieldValueException(iField.getType(), Integer.valueOf(value), cause.getMessage()); ex.initCause(cause); throw ex; } return result; } public long set(long instant, String text, Locale locale) { // cannot verify that new value stuck because set may be lenient long localInstant = iZone.convertUTCToLocal(instant); localInstant = iField.set(localInstant, text, locale); return iZone.convertLocalToUTC(localInstant, false, instant); } public int getDifference(long minuendInstant, long subtrahendInstant) { int offset = getOffsetToAdd(subtrahendInstant); return iField.getDifference (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)), subtrahendInstant + offset); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { int offset = getOffsetToAdd(subtrahendInstant); return iField.getDifferenceAsLong (minuendInstant + (iTimeField ? offset : getOffsetToAdd(minuendInstant)), subtrahendInstant + offset); } public final DurationField getDurationField() { return iDurationField; } public final DurationField getRangeDurationField() { return iRangeDurationField; } public boolean isLeap(long instant) { long localInstant = iZone.convertUTCToLocal(instant); return iField.isLeap(localInstant); } public int getLeapAmount(long instant) { long localInstant = iZone.convertUTCToLocal(instant); return iField.getLeapAmount(localInstant); } public final DurationField getLeapDurationField() { return iLeapDurationField; } public long roundFloor(long instant) { if (iTimeField) { int offset = getOffsetToAdd(instant); instant = iField.roundFloor(instant + offset); return instant - offset; } else { long localInstant = iZone.convertUTCToLocal(instant); localInstant = iField.roundFloor(localInstant); return iZone.convertLocalToUTC(localInstant, false, instant); } } public long roundCeiling(long instant) { if (iTimeField) { int offset = getOffsetToAdd(instant); instant = iField.roundCeiling(instant + offset); return instant - offset; } else { long localInstant = iZone.convertUTCToLocal(instant); localInstant = iField.roundCeiling(localInstant); return iZone.convertLocalToUTC(localInstant, false, instant); } } public long remainder(long instant) { long localInstant = iZone.convertUTCToLocal(instant); return iField.remainder(localInstant); } public int getMinimumValue() { return iField.getMinimumValue(); } public int getMinimumValue(long instant) { long localInstant = iZone.convertUTCToLocal(instant); return iField.getMinimumValue(localInstant); } public int getMinimumValue(ReadablePartial instant) { return iField.getMinimumValue(instant); } public int getMinimumValue(ReadablePartial instant, int[] values) { return iField.getMinimumValue(instant, values); } public int getMaximumValue() { return iField.getMaximumValue(); } public int getMaximumValue(long instant) { long localInstant = iZone.convertUTCToLocal(instant); return iField.getMaximumValue(localInstant); } public int getMaximumValue(ReadablePartial instant) { return iField.getMaximumValue(instant); } public int getMaximumValue(ReadablePartial instant, int[] values) { return iField.getMaximumValue(instant, values); } public int getMaximumTextLength(Locale locale) { return iField.getMaximumTextLength(locale); } public int getMaximumShortTextLength(Locale locale) { return iField.getMaximumShortTextLength(locale); } private int getOffsetToAdd(long instant) { int offset = this.iZone.getOffset(instant); long sum = instant + offset; // If there is a sign change, but the two values have the same sign... if ((instant ^ sum) < 0 && (instant ^ offset) >= 0) { throw new ArithmeticException("Adding time zone offset caused overflow"); } return offset; } } } joda-time-2.3/src/main/java/org/joda/time/chrono/ISOChronology.java0000644000175000017500000001763112200501234024503 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.field.DividedDateTimeField; import org.joda.time.field.RemainderDateTimeField; /** * Implements a chronology that follows the rules of the ISO8601 standard, * which is compatible with Gregorian for all modern dates. * When ISO does not define a field, but it can be determined (such as AM/PM) * it is included. *

* With the exception of century related fields, ISOChronology is exactly the * same as {@link GregorianChronology}. In this chronology, centuries and year * of century are zero based. For all years, the century is determined by * dropping the last two digits of the year, ignoring sign. The year of century * is the value of the last two year digits. *

* ISOChronology is thread-safe and immutable. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public final class ISOChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = -6212696554273812441L; /** Singleton instance of a UTC ISOChronology */ private static final ISOChronology INSTANCE_UTC; private static final int FAST_CACHE_SIZE = 64; /** Fast cache of zone to chronology */ private static final ISOChronology[] cFastCache; /** Cache of zone to chronology */ private static final Map cCache = new HashMap(); static { cFastCache = new ISOChronology[FAST_CACHE_SIZE]; INSTANCE_UTC = new ISOChronology(GregorianChronology.getInstanceUTC()); cCache.put(DateTimeZone.UTC, INSTANCE_UTC); } /** * Gets an instance of the ISOChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ public static ISOChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the ISOChronology in the default time zone. * * @return a chronology in the default time zone */ public static ISOChronology getInstance() { return getInstance(DateTimeZone.getDefault()); } /** * Gets an instance of the ISOChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @return a chronology in the specified time zone */ public static ISOChronology getInstance(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } int index = System.identityHashCode(zone) & (FAST_CACHE_SIZE - 1); ISOChronology chrono = cFastCache[index]; if (chrono != null && chrono.getZone() == zone) { return chrono; } synchronized (cCache) { chrono = cCache.get(zone); if (chrono == null) { chrono = new ISOChronology(ZonedChronology.getInstance(INSTANCE_UTC, zone)); cCache.put(zone, chrono); } } cFastCache[index] = chrono; return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor */ private ISOChronology(Chronology base) { super(base, null); } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } // Output //----------------------------------------------------------------------- /** * Gets a debugging toString. * * @return a debugging string */ public String toString() { String str = "ISOChronology"; DateTimeZone zone = getZone(); if (zone != null) { str = str + '[' + zone.getID() + ']'; } return str; } protected void assemble(Fields fields) { if (getBase().getZone() == DateTimeZone.UTC) { // Use zero based century and year of century. fields.centuryOfEra = new DividedDateTimeField( ISOYearOfEraDateTimeField.INSTANCE, DateTimeFieldType.centuryOfEra(), 100); fields.yearOfCentury = new RemainderDateTimeField( (DividedDateTimeField) fields.centuryOfEra, DateTimeFieldType.yearOfCentury()); fields.weekyearOfCentury = new RemainderDateTimeField( (DividedDateTimeField) fields.centuryOfEra, DateTimeFieldType.weekyearOfCentury()); fields.centuries = fields.centuryOfEra.getDurationField(); } } //----------------------------------------------------------------------- /** * Checks if this chronology instance equals another. * * @param obj the object to compare to * @return true if equal * @since 1.6 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ISOChronology) { ISOChronology chrono = (ISOChronology) obj; return getZone().equals(chrono.getZone()); } return false; } /** * A suitable hash code for the chronology. * * @return the hash code * @since 1.6 */ public int hashCode() { return "ISO".hashCode() * 11 + getZone().hashCode(); } //----------------------------------------------------------------------- /** * Serialize ISOChronology instances using a small stub. This reduces the * serialized size, and deserialized instances come from the cache. */ private Object writeReplace() { return new Stub(getZone()); } private static final class Stub implements Serializable { private static final long serialVersionUID = -6212696554273812441L; private transient DateTimeZone iZone; Stub(DateTimeZone zone) { iZone = zone; } private Object readResolve() { return ISOChronology.getInstance(iZone); } private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(iZone); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { iZone = (DateTimeZone)in.readObject(); } } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicFixedMonthChronology.java0000644000175000017500000001340011564251363027067 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; /** * Abstract implementation of a calendar system based around fixed length months. *

* As the month length is fixed various calculations can be optimised. * This implementation assumes any additional days after twelve * months fall into a thirteenth month. *

* BasicFixedMonthChronology is thread-safe and immutable, and all * subclasses must be as well. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.2, refactored from CopticChronology */ abstract class BasicFixedMonthChronology extends BasicChronology { /** Serialization lock */ private static final long serialVersionUID = 261387371998L; /** The length of the month. */ static final int MONTH_LENGTH = 30; /** The typical millis per year. */ static final long MILLIS_PER_YEAR = (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY); /** The length of the month in millis. */ static final long MILLIS_PER_MONTH = ((long) MONTH_LENGTH) * DateTimeConstants.MILLIS_PER_DAY; //----------------------------------------------------------------------- /** * Restricted constructor. * * @param base the base chronology * @param param the init parameter * @param minDaysInFirstWeek the minimum days in the first week */ BasicFixedMonthChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } //----------------------------------------------------------------------- long setYear(long instant, int year) { // optimsed implementation of set, due to fixed months int thisYear = getYear(instant); int dayOfYear = getDayOfYear(instant, thisYear); int millisOfDay = getMillisOfDay(instant); if (dayOfYear > 365) { // Current year is leap, and day is leap. if (!isLeapYear(year)) { // Moving to a non-leap year, leap day doesn't exist. dayOfYear--; } } instant = getYearMonthDayMillis(year, 1, dayOfYear); instant += millisOfDay; return instant; } //----------------------------------------------------------------------- long getYearDifference(long minuendInstant, long subtrahendInstant) { // optimsed implementation of getDifference, due to fixed months int minuendYear = getYear(minuendInstant); int subtrahendYear = getYear(subtrahendInstant); // Inlined remainder method to avoid duplicate calls to get. long minuendRem = minuendInstant - getYearMillis(minuendYear); long subtrahendRem = subtrahendInstant - getYearMillis(subtrahendYear); int difference = minuendYear - subtrahendYear; if (minuendRem < subtrahendRem) { difference--; } return difference; } //----------------------------------------------------------------------- long getTotalMillisByYearMonth(int year, int month) { return ((month - 1) * MILLIS_PER_MONTH); } //----------------------------------------------------------------------- int getDayOfMonth(long millis) { // optimised for fixed months return (getDayOfYear(millis) - 1) % MONTH_LENGTH + 1; } //----------------------------------------------------------------------- boolean isLeapYear(int year) { return (year & 3) == 3; } //----------------------------------------------------------------------- int getDaysInYearMonth(int year, int month) { return (month != 13) ? MONTH_LENGTH : (isLeapYear(year) ? 6 : 5); } //----------------------------------------------------------------------- int getDaysInMonthMax() { return MONTH_LENGTH; } //----------------------------------------------------------------------- int getDaysInMonthMax(int month) { return (month != 13 ? MONTH_LENGTH : 6); } //----------------------------------------------------------------------- int getMonthOfYear(long millis) { return (getDayOfYear(millis) - 1) / MONTH_LENGTH + 1; } //----------------------------------------------------------------------- int getMonthOfYear(long millis, int year) { long monthZeroBased = (millis - getYearMillis(year)) / MILLIS_PER_MONTH; return ((int) monthZeroBased) + 1; } //----------------------------------------------------------------------- int getMaxMonth() { return 13; } //----------------------------------------------------------------------- long getAverageMillisPerYear() { return MILLIS_PER_YEAR; } //----------------------------------------------------------------------- long getAverageMillisPerYearDividedByTwo() { return MILLIS_PER_YEAR / 2; } //----------------------------------------------------------------------- long getAverageMillisPerMonth() { return MILLIS_PER_MONTH; } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicWeekyearDateTimeField.java0000644000175000017500000002114612203434767027123 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.field.FieldUtils; import org.joda.time.field.ImpreciseDateTimeField; /** * Provides time calculations for the week of the weekyear component of time. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.1, refactored from GJWeekyearDateTimeField */ final class BasicWeekyearDateTimeField extends ImpreciseDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 6215066916806820644L; private static final long WEEK_53 = (53L - 1) * DateTimeConstants.MILLIS_PER_WEEK; private final BasicChronology iChronology; /** * Restricted constructor */ BasicWeekyearDateTimeField(BasicChronology chronology) { super(DateTimeFieldType.weekyear(), chronology.getAverageMillisPerYear()); iChronology = chronology; } public boolean isLenient() { return false; } /** * Get the Year of a week based year component of the specified time instant. * * @see org.joda.time.DateTimeField#get * @param instant the time instant in millis to query. * @return the year extracted from the input. */ public int get(long instant) { return iChronology.getWeekyear(instant); } /** * Add the specified years to the specified time instant. * * @see org.joda.time.DateTimeField#add * @param instant the time instant in millis to update. * @param years the years to add (can be negative). * @return the updated time instant. */ public long add(long instant, int years) { if (years == 0) { return instant; } return set(instant, get(instant) + years); } public long add(long instant, long value) { return add(instant, FieldUtils.safeToInt(value)); } /** * Add to the year component of the specified time instant * wrapping around within that component if necessary. * * @see org.joda.time.DateTimeField#addWrapField * @param instant the time instant in millis to update. * @param years the years to add (can be negative). * @return the updated time instant. */ public long addWrapField(long instant, int years) { return add(instant, years); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant < subtrahendInstant) { return -getDifference(subtrahendInstant, minuendInstant); } int minuendWeekyear = get(minuendInstant); int subtrahendWeekyear = get(subtrahendInstant); long minuendRem = remainder(minuendInstant); long subtrahendRem = remainder(subtrahendInstant); // Balance leap weekyear differences on remainders. if (subtrahendRem >= WEEK_53 && iChronology.getWeeksInYear(minuendWeekyear) <= 52) { subtrahendRem -= DateTimeConstants.MILLIS_PER_WEEK; } int difference = minuendWeekyear - subtrahendWeekyear; if (minuendRem < subtrahendRem) { difference--; } return difference; } /** * Set the Year of a week based year component of the specified time instant. * * @see org.joda.time.DateTimeField#set * @param instant the time instant in millis to update. * @param year the year (-9999,9999) to set the date to. * @return the updated DateTime. * @throws IllegalArgumentException if year is invalid. */ public long set(long instant, int year) { FieldUtils.verifyValueBounds(this, Math.abs(year), iChronology.getMinYear(), iChronology.getMaxYear()); // // Do nothing if no real change is requested. // int thisWeekyear = get( instant ); if ( thisWeekyear == year ) { return instant; } // // Calculate the DayOfWeek (to be preserved). // int thisDow = iChronology.getDayOfWeek(instant); // // Calculate the maximum weeks in the target year. // int weeksInFromYear = iChronology.getWeeksInYear( thisWeekyear ); int weeksInToYear = iChronology.getWeeksInYear( year ); int maxOutWeeks = (weeksInToYear < weeksInFromYear) ? weeksInToYear : weeksInFromYear; // // Get the current week of the year. This will be preserved in // the output unless it is greater than the maximum possible // for the target weekyear. In that case it is adjusted // to the maximum possible. // int setToWeek = iChronology.getWeekOfWeekyear(instant); if ( setToWeek > maxOutWeeks ) { setToWeek = maxOutWeeks; } // // Get a wroking copy of the current date-time. // This can be a convenience for debugging. // long workInstant = instant; // Get a copy // // Attempt to get close to the proper weekyear. // Note - we cannot currently call ourself, so we just call // set for the year. This at least gets us close. // workInstant = iChronology.setYear( workInstant, year ); // // Calculate the weekyear number for the get close to value // (which might not be equal to the year just set). // int workWoyYear = get( workInstant ); // // At most we are off by one year, which can be "fixed" by // adding/subtracting a week. // if ( workWoyYear < year ) { workInstant += DateTimeConstants.MILLIS_PER_WEEK; } else if ( workWoyYear > year ) { workInstant -= DateTimeConstants.MILLIS_PER_WEEK; } // // Set the proper week in the current weekyear. // // BEGIN: possible set WeekOfWeekyear logic. int currentWoyWeek = iChronology.getWeekOfWeekyear(workInstant); // No range check required (we already know it is OK). workInstant = workInstant + (setToWeek - currentWoyWeek) * (long)DateTimeConstants.MILLIS_PER_WEEK; // END: possible set WeekOfWeekyear logic. // // Reset DayOfWeek to previous value. // // Note: This works fine, but it ideally shouldn't invoke other // fields from within a field. workInstant = iChronology.dayOfWeek().set( workInstant, thisDow ); // // Return result. // return workInstant; } public DurationField getRangeDurationField() { return null; } public boolean isLeap(long instant) { return iChronology.getWeeksInYear(iChronology.getWeekyear(instant)) > 52; } public int getLeapAmount(long instant) { return iChronology.getWeeksInYear(iChronology.getWeekyear(instant)) - 52; } public DurationField getLeapDurationField() { return iChronology.weeks(); } public int getMinimumValue() { return iChronology.getMinYear(); } public int getMaximumValue() { return iChronology.getMaxYear(); } public long roundFloor(long instant) { // Note: This works fine, but it ideally shouldn't invoke other // fields from within a field. instant = iChronology.weekOfWeekyear().roundFloor(instant); int wow = iChronology.getWeekOfWeekyear(instant); if (wow > 1) { instant -= ((long) DateTimeConstants.MILLIS_PER_WEEK) * (wow - 1); } return instant; } public long remainder(long instant) { return instant - roundFloor(instant); } /** * Serialization singleton */ private Object readResolve() { return iChronology.weekyear(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/StrictChronology.java0000644000175000017500000001233711564251363025340 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.field.StrictDateTimeField; /** * Wraps another Chronology, ensuring all the fields are strict. *

* StrictChronology is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 * @see StrictDateTimeField * @see LenientChronology */ public final class StrictChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = 6633006628097111960L; /** * Create a StrictChronology for any chronology. * * @param base the chronology to wrap * @throws IllegalArgumentException if chronology is null */ public static StrictChronology getInstance(Chronology base) { if (base == null) { throw new IllegalArgumentException("Must supply a chronology"); } return new StrictChronology(base); } private transient Chronology iWithUTC; /** * Create a StrictChronology for any chronology. * * @param base the chronology to wrap */ private StrictChronology(Chronology base) { super(base, null); } public Chronology withUTC() { if (iWithUTC == null) { if (getZone() == DateTimeZone.UTC) { iWithUTC = this; } else { iWithUTC = StrictChronology.getInstance(getBase().withUTC()); } } return iWithUTC; } public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == DateTimeZone.UTC) { return withUTC(); } if (zone == getZone()) { return this; } return StrictChronology.getInstance(getBase().withZone(zone)); } protected void assemble(Fields fields) { fields.year = convertField(fields.year); fields.yearOfEra = convertField(fields.yearOfEra); fields.yearOfCentury = convertField(fields.yearOfCentury); fields.centuryOfEra = convertField(fields.centuryOfEra); fields.era = convertField(fields.era); fields.dayOfWeek = convertField(fields.dayOfWeek); fields.dayOfMonth = convertField(fields.dayOfMonth); fields.dayOfYear = convertField(fields.dayOfYear); fields.monthOfYear = convertField(fields.monthOfYear); fields.weekOfWeekyear = convertField(fields.weekOfWeekyear); fields.weekyear = convertField(fields.weekyear); fields.weekyearOfCentury = convertField(fields.weekyearOfCentury); fields.millisOfSecond = convertField(fields.millisOfSecond); fields.millisOfDay = convertField(fields.millisOfDay); fields.secondOfMinute = convertField(fields.secondOfMinute); fields.secondOfDay = convertField(fields.secondOfDay); fields.minuteOfHour = convertField(fields.minuteOfHour); fields.minuteOfDay = convertField(fields.minuteOfDay); fields.hourOfDay = convertField(fields.hourOfDay); fields.hourOfHalfday = convertField(fields.hourOfHalfday); fields.clockhourOfDay = convertField(fields.clockhourOfDay); fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday); fields.halfdayOfDay = convertField(fields.halfdayOfDay); } private static final DateTimeField convertField(DateTimeField field) { return StrictDateTimeField.getInstance(field); } //----------------------------------------------------------------------- /** * A strict chronology is only equal to a strict chronology with the * same base chronology. * * @param obj the object to compare to * @return true if equal * @since 1.4 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof StrictChronology == false) { return false; } StrictChronology chrono = (StrictChronology) obj; return getBase().equals(chrono.getBase()); } /** * A suitable hashcode for the chronology. * * @return the hashcode * @since 1.4 */ public int hashCode() { return 352831696 + getBase().hashCode() * 7; } /** * A debugging string for the chronology. * * @return the debugging string */ public String toString() { return "StrictChronology[" + getBase().toString() + ']'; } } joda-time-2.3/src/main/java/org/joda/time/chrono/GJYearOfEraDateTimeField.java0000644000175000017500000000726712203435050026435 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.ReadablePartial; import org.joda.time.field.DecoratedDateTimeField; import org.joda.time.field.FieldUtils; /** * Provides time calculations for the year of era component of time. * * @author Brian S O'Neill * @since 1.0 */ final class GJYearOfEraDateTimeField extends DecoratedDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = -5961050944769862059L; private final BasicChronology iChronology; /** * Restricted constructor. */ GJYearOfEraDateTimeField(DateTimeField yearField, BasicChronology chronology) { super(yearField, DateTimeFieldType.yearOfEra()); iChronology = chronology; } public int get(long instant) { int year = getWrappedField().get(instant); if (year <= 0) { year = 1 - year; } return year; } public long add(long instant, int years) { return getWrappedField().add(instant, years); } public long add(long instant, long years) { return getWrappedField().add(instant, years); } public long addWrapField(long instant, int years) { return getWrappedField().addWrapField(instant, years); } public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int years) { return getWrappedField().addWrapField(instant, fieldIndex, values, years); } public int getDifference(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } /** * Set the year component of the specified time instant. * * @param instant the time instant in millis to update. * @param year the year (0,292278994) to update the time to. * @return the updated time instant. * @throws IllegalArgumentException if year is invalid. */ public long set(long instant, int year) { FieldUtils.verifyValueBounds(this, year, 1, getMaximumValue()); if (iChronology.getYear(instant) <= 0) { year = 1 - year; } return super.set(instant, year); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return getWrappedField().getMaximumValue(); } public long roundFloor(long instant) { return getWrappedField().roundFloor(instant); } public long roundCeiling(long instant) { return getWrappedField().roundCeiling(instant); } public long remainder(long instant) { return getWrappedField().remainder(instant); } /** * Serialization singleton */ private Object readResolve() { return iChronology.yearOfEra(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/GJEraDateTimeField.java0000644000175000017500000001102312203435004025307 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.field.BaseDateTimeField; import org.joda.time.field.FieldUtils; import org.joda.time.field.UnsupportedDurationField; /** * Provides time calculations for the era component of time. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ final class GJEraDateTimeField extends BaseDateTimeField { /** Serialization version */ @SuppressWarnings("unused") private static final long serialVersionUID = 4240986525305515528L; private final BasicChronology iChronology; /** * Restricted constructor */ GJEraDateTimeField(BasicChronology chronology) { super(DateTimeFieldType.era()); iChronology = chronology; } public boolean isLenient() { return false; } /** * Get the Era component of the specified time instant. * * @param instant the time instant in millis to query. */ public int get(long instant) { if (iChronology.getYear(instant) <= 0) { return DateTimeConstants.BCE; } else { return DateTimeConstants.CE; } } public String getAsText(int fieldValue, Locale locale) { return GJLocaleSymbols.forLocale(locale).eraValueToText(fieldValue); } /** * Set the Era component of the specified time instant. * * @param instant the time instant in millis to update. * @param era the era to update the time to. * @return the updated time instant. * @throws IllegalArgumentException if era is invalid. */ public long set(long instant, int era) { FieldUtils.verifyValueBounds(this, era, DateTimeConstants.BCE, DateTimeConstants.CE); int oldEra = get(instant); if (oldEra != era) { int year = iChronology.getYear(instant); return iChronology.setYear(instant, -year); } else { return instant; } } public long set(long instant, String text, Locale locale) { return set(instant, GJLocaleSymbols.forLocale(locale).eraTextToValue(text)); } public long roundFloor(long instant) { if (get(instant) == DateTimeConstants.CE) { return iChronology.setYear(0, 1); } else { return Long.MIN_VALUE; } } public long roundCeiling(long instant) { if (get(instant) == DateTimeConstants.BCE) { return iChronology.setYear(0, 1); } else { return Long.MAX_VALUE; } } public long roundHalfFloor(long instant) { // In reality, the era is infinite, so there is no halfway point. return roundFloor(instant); } public long roundHalfCeiling(long instant) { // In reality, the era is infinite, so there is no halfway point. return roundFloor(instant); } public long roundHalfEven(long instant) { // In reality, the era is infinite, so there is no halfway point. return roundFloor(instant); } public DurationField getDurationField() { return UnsupportedDurationField.getInstance(DurationFieldType.eras()); } public DurationField getRangeDurationField() { return null; } public int getMinimumValue() { return DateTimeConstants.BCE; } public int getMaximumValue() { return DateTimeConstants.CE; } public int getMaximumTextLength(Locale locale) { return GJLocaleSymbols.forLocale(locale).getEraMaxTextLength(); } /** * Serialization singleton */ private Object readResolve() { return iChronology.era(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/GJChronology.java0000644000175000017500000013360412203435020024352 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.IllegalFieldValueException; import org.joda.time.Instant; import org.joda.time.LocalDate; import org.joda.time.ReadableInstant; import org.joda.time.ReadablePartial; import org.joda.time.field.BaseDateTimeField; import org.joda.time.field.DecoratedDurationField; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Implements the Gregorian/Julian calendar system which is the calendar system * used in most of the world. Wherever possible, it is recommended to use the * {@link ISOChronology} instead. *

* The Gregorian calendar replaced the Julian calendar, and the point in time * when this chronology switches can be controlled using the second parameter * of the getInstance method. By default this cutover is set to the date the * Gregorian calendar was first instituted, October 15, 1582. *

* Before this date, this chronology uses the proleptic Julian calendar * (proleptic means extending indefinitely). The Julian calendar has leap years * every four years, whereas the Gregorian has special rules for 100 and 400 * years. A meaningful result will thus be obtained for all input values. * However before 8 CE, Julian leap years were irregular, and before 45 BCE * there was no Julian calendar. *

* This chronology differs from * {@link java.util.GregorianCalendar GregorianCalendar} in that years * in BCE are returned correctly. Thus year 1 BCE is returned as -1 instead of 1. * The yearOfEra field produces results compatible with GregorianCalendar. *

* The Julian calendar does not have a year zero, and so year -1 is followed by * year 1. If the Gregorian cutover date is specified at or before year -1 * (Julian), year zero is defined. In other words, the proleptic Gregorian * chronology used by this class has a year zero. *

* To create a pure proleptic Julian chronology, use {@link JulianChronology}, * and to create a pure proleptic Gregorian chronology, use * {@link GregorianChronology}. *

* GJChronology is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class GJChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = -2545574827706931671L; /** * Convert a datetime from one chronology to another. */ private static long convertByYear(long instant, Chronology from, Chronology to) { return to.getDateTimeMillis (from.year().get(instant), from.monthOfYear().get(instant), from.dayOfMonth().get(instant), from.millisOfDay().get(instant)); } /** * Convert a datetime from one chronology to another. */ private static long convertByWeekyear(final long instant, Chronology from, Chronology to) { long newInstant; newInstant = to.weekyear().set(0, from.weekyear().get(instant)); newInstant = to.weekOfWeekyear().set(newInstant, from.weekOfWeekyear().get(instant)); newInstant = to.dayOfWeek().set(newInstant, from.dayOfWeek().get(instant)); newInstant = to.millisOfDay().set(newInstant, from.millisOfDay().get(instant)); return newInstant; } /** * The default GregorianJulian cutover point. */ static final Instant DEFAULT_CUTOVER = new Instant(-12219292800000L); /** Cache of zone to chronology list */ private static final Map> cCache = new HashMap>(); /** * Factory method returns instances of the default GJ cutover * chronology. This uses a cutover date of October 15, 1582 (Gregorian) * 00:00:00 UTC. For this value, October 4, 1582 (Julian) is followed by * October 15, 1582 (Gregorian). * *

The first day of the week is designated to be * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, * and the minimum days in the first week of the year is 4. * *

The time zone of the returned instance is UTC. */ public static GJChronology getInstanceUTC() { return getInstance(DateTimeZone.UTC, DEFAULT_CUTOVER, 4); } /** * Factory method returns instances of the default GJ cutover * chronology. This uses a cutover date of October 15, 1582 (Gregorian) * 00:00:00 UTC. For this value, October 4, 1582 (Julian) is followed by * October 15, 1582 (Gregorian). * *

The first day of the week is designated to be * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, * and the minimum days in the first week of the year is 4. * *

The returned chronology is in the default time zone. */ public static GJChronology getInstance() { return getInstance(DateTimeZone.getDefault(), DEFAULT_CUTOVER, 4); } /** * Factory method returns instances of the GJ cutover chronology. This uses * a cutover date of October 15, 1582 (Gregorian) 00:00:00 UTC. For this * value, October 4, 1582 (Julian) is followed by October 15, 1582 * (Gregorian). * *

The first day of the week is designated to be * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, * and the minimum days in the first week of the year is 4. * * @param zone the time zone to use, null is default */ public static GJChronology getInstance(DateTimeZone zone) { return getInstance(zone, DEFAULT_CUTOVER, 4); } /** * Factory method returns instances of the GJ cutover chronology. Any * cutover date may be specified. * *

The first day of the week is designated to be * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, * and the minimum days in the first week of the year is 4. * * @param zone the time zone to use, null is default * @param gregorianCutover the cutover to use, null means default */ public static GJChronology getInstance( DateTimeZone zone, ReadableInstant gregorianCutover) { return getInstance(zone, gregorianCutover, 4); } /** * Factory method returns instances of the GJ cutover chronology. Any * cutover date may be specified. * * @param zone the time zone to use, null is default * @param gregorianCutover the cutover to use, null means default * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 */ public static synchronized GJChronology getInstance( DateTimeZone zone, ReadableInstant gregorianCutover, int minDaysInFirstWeek) { zone = DateTimeUtils.getZone(zone); Instant cutoverInstant; if (gregorianCutover == null) { cutoverInstant = DEFAULT_CUTOVER; } else { cutoverInstant = gregorianCutover.toInstant(); LocalDate cutoverDate = new LocalDate(cutoverInstant.getMillis(), GregorianChronology.getInstance(zone)); if (cutoverDate.getYear() <= 0) { throw new IllegalArgumentException("Cutover too early. Must be on or after 0001-01-01."); } } GJChronology chrono; synchronized (cCache) { ArrayList chronos = cCache.get(zone); if (chronos == null) { chronos = new ArrayList(2); cCache.put(zone, chronos); } else { for (int i = chronos.size(); --i >= 0;) { chrono = chronos.get(i); if (minDaysInFirstWeek == chrono.getMinimumDaysInFirstWeek() && cutoverInstant.equals(chrono.getGregorianCutover())) { return chrono; } } } if (zone == DateTimeZone.UTC) { chrono = new GJChronology (JulianChronology.getInstance(zone, minDaysInFirstWeek), GregorianChronology.getInstance(zone, minDaysInFirstWeek), cutoverInstant); } else { chrono = getInstance(DateTimeZone.UTC, cutoverInstant, minDaysInFirstWeek); chrono = new GJChronology (ZonedChronology.getInstance(chrono, zone), chrono.iJulianChronology, chrono.iGregorianChronology, chrono.iCutoverInstant); } chronos.add(chrono); } return chrono; } /** * Factory method returns instances of the GJ cutover chronology. Any * cutover date may be specified. * * @param zone the time zone to use, null is default * @param gregorianCutover the cutover to use * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 */ public static GJChronology getInstance( DateTimeZone zone, long gregorianCutover, int minDaysInFirstWeek) { Instant cutoverInstant; if (gregorianCutover == DEFAULT_CUTOVER.getMillis()) { cutoverInstant = null; } else { cutoverInstant = new Instant(gregorianCutover); } return getInstance(zone, cutoverInstant, minDaysInFirstWeek); } //----------------------------------------------------------------------- private JulianChronology iJulianChronology; private GregorianChronology iGregorianChronology; private Instant iCutoverInstant; private long iCutoverMillis; private long iGapDuration; /** * @param julian chronology used before the cutover instant * @param gregorian chronology used at and after the cutover instant * @param cutoverInstant instant when the gregorian chronology began */ private GJChronology(JulianChronology julian, GregorianChronology gregorian, Instant cutoverInstant) { super(null, new Object[] {julian, gregorian, cutoverInstant}); } /** * Called when applying a time zone. */ private GJChronology(Chronology base, JulianChronology julian, GregorianChronology gregorian, Instant cutoverInstant) { super(base, new Object[] {julian, gregorian, cutoverInstant}); } /** * Serialization singleton */ private Object readResolve() { return getInstance(getZone(), iCutoverInstant, getMinimumDaysInFirstWeek()); } public DateTimeZone getZone() { Chronology base; if ((base = getBase()) != null) { return base.getZone(); } return DateTimeZone.UTC; } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return withZone(DateTimeZone.UTC); } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone, iCutoverInstant, getMinimumDaysInFirstWeek()); } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); } // Assume date is Gregorian. long instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, millisOfDay); if (instant < iCutoverMillis) { // Maybe it's Julian. instant = iJulianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, millisOfDay); if (instant >= iCutoverMillis) { // Okay, it's in the illegal cutover gap. throw new IllegalArgumentException("Specified date does not exist"); } } return instant; } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } // Assume date is Gregorian. long instant; try { instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } catch (IllegalFieldValueException ex) { if (monthOfYear != 2 || dayOfMonth != 29) { throw ex; } instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, 28, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); if (instant >= iCutoverMillis) { throw ex; } } if (instant < iCutoverMillis) { // Maybe it's Julian. instant = iJulianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); if (instant >= iCutoverMillis) { // Okay, it's in the illegal cutover gap. throw new IllegalArgumentException("Specified date does not exist"); } } return instant; } /** * Gets the cutover instant between Gregorian and Julian chronologies. * @return the cutover instant */ public Instant getGregorianCutover() { return iCutoverInstant; } /** * Gets the minimum days needed for a week to be the first week in a year. * * @return the minimum days */ public int getMinimumDaysInFirstWeek() { return iGregorianChronology.getMinimumDaysInFirstWeek(); } //----------------------------------------------------------------------- /** * Checks if this chronology instance equals another. * * @param obj the object to compare to * @return true if equal * @since 1.6 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof GJChronology) { GJChronology chrono = (GJChronology) obj; return iCutoverMillis == chrono.iCutoverMillis && getMinimumDaysInFirstWeek() == chrono.getMinimumDaysInFirstWeek() && getZone().equals(chrono.getZone()); } return false; } /** * A suitable hash code for the chronology. * * @return the hash code * @since 1.6 */ public int hashCode() { return "GJ".hashCode() * 11 + getZone().hashCode() + getMinimumDaysInFirstWeek() + iCutoverInstant.hashCode(); } // Output //----------------------------------------------------------------------- /** * Gets a debugging toString. * * @return a debugging string */ public String toString() { StringBuffer sb = new StringBuffer(60); sb.append("GJChronology"); sb.append('['); sb.append(getZone().getID()); if (iCutoverMillis != DEFAULT_CUTOVER.getMillis()) { sb.append(",cutover="); DateTimeFormatter printer; if (withUTC().dayOfYear().remainder(iCutoverMillis) == 0) { printer = ISODateTimeFormat.date(); } else { printer = ISODateTimeFormat.dateTime(); } printer.withChronology(withUTC()).printTo(sb, iCutoverMillis); } if (getMinimumDaysInFirstWeek() != 4) { sb.append(",mdfw="); sb.append(getMinimumDaysInFirstWeek()); } sb.append(']'); return sb.toString(); } protected void assemble(Fields fields) { Object[] params = (Object[])getParam(); JulianChronology julian = (JulianChronology)params[0]; GregorianChronology gregorian = (GregorianChronology)params[1]; Instant cutoverInstant = (Instant)params[2]; iCutoverMillis = cutoverInstant.getMillis(); iJulianChronology = julian; iGregorianChronology = gregorian; iCutoverInstant = cutoverInstant; if (getBase() != null) { return; } if (julian.getMinimumDaysInFirstWeek() != gregorian.getMinimumDaysInFirstWeek()) { throw new IllegalArgumentException(); } // Compute difference between the chronologies at the cutover instant iGapDuration = iCutoverMillis - julianToGregorianByYear(iCutoverMillis); // Begin field definitions. // First just copy all the Gregorian fields and then override those // that need special attention. fields.copyFieldsFrom(gregorian); // Assuming cutover is at midnight, all time of day fields can be // gregorian since they are unaffected by cutover. // Verify assumption. if (gregorian.millisOfDay().get(iCutoverMillis) == 0) { // Cutover is sometime in the day, so cutover fields are required // for time of day. fields.millisOfSecond = new CutoverField(julian.millisOfSecond(), fields.millisOfSecond, iCutoverMillis); fields.millisOfDay = new CutoverField(julian.millisOfDay(), fields.millisOfDay, iCutoverMillis); fields.secondOfMinute = new CutoverField(julian.secondOfMinute(), fields.secondOfMinute, iCutoverMillis); fields.secondOfDay = new CutoverField(julian.secondOfDay(), fields.secondOfDay, iCutoverMillis); fields.minuteOfHour = new CutoverField(julian.minuteOfHour(), fields.minuteOfHour, iCutoverMillis); fields.minuteOfDay = new CutoverField(julian.minuteOfDay(), fields.minuteOfDay, iCutoverMillis); fields.hourOfDay = new CutoverField(julian.hourOfDay(), fields.hourOfDay, iCutoverMillis); fields.hourOfHalfday = new CutoverField(julian.hourOfHalfday(), fields.hourOfHalfday, iCutoverMillis); fields.clockhourOfDay = new CutoverField(julian.clockhourOfDay(), fields.clockhourOfDay, iCutoverMillis); fields.clockhourOfHalfday = new CutoverField(julian.clockhourOfHalfday(), fields.clockhourOfHalfday, iCutoverMillis); fields.halfdayOfDay = new CutoverField(julian.halfdayOfDay(), fields.halfdayOfDay, iCutoverMillis); } // These fields just require basic cutover support. { fields.era = new CutoverField(julian.era(), fields.era, iCutoverMillis); } // DayOfYear and weekOfWeekyear require special handling since cutover // year has fewer days and weeks. Extend the cutover to the start of // the next year or weekyear. This keeps the sequence unbroken during // the cutover year. { long cutover = gregorian.year().roundCeiling(iCutoverMillis); fields.dayOfYear = new CutoverField( julian.dayOfYear(), fields.dayOfYear, cutover); } { long cutover = gregorian.weekyear().roundCeiling(iCutoverMillis); fields.weekOfWeekyear = new CutoverField( julian.weekOfWeekyear(), fields.weekOfWeekyear, cutover, true); } // These fields are special because they have imprecise durations. The // family of addition methods need special attention. Override affected // duration fields as well. { fields.year = new ImpreciseCutoverField( julian.year(), fields.year, iCutoverMillis); fields.years = fields.year.getDurationField(); fields.yearOfEra = new ImpreciseCutoverField( julian.yearOfEra(), fields.yearOfEra, fields.years, iCutoverMillis); fields.yearOfCentury = new ImpreciseCutoverField( julian.yearOfCentury(), fields.yearOfCentury, fields.years, iCutoverMillis); fields.centuryOfEra = new ImpreciseCutoverField( julian.centuryOfEra(), fields.centuryOfEra, iCutoverMillis); fields.centuries = fields.centuryOfEra.getDurationField(); fields.monthOfYear = new ImpreciseCutoverField( julian.monthOfYear(), fields.monthOfYear, iCutoverMillis); fields.months = fields.monthOfYear.getDurationField(); fields.weekyear = new ImpreciseCutoverField( julian.weekyear(), fields.weekyear, null, iCutoverMillis, true); fields.weekyearOfCentury = new ImpreciseCutoverField( julian.weekyearOfCentury(), fields.weekyearOfCentury, fields.weekyears, iCutoverMillis); fields.weekyears = fields.weekyear.getDurationField(); } // These fields require basic cutover support, except they must link to // imprecise durations. { CutoverField cf = new CutoverField (julian.dayOfMonth(), fields.dayOfMonth, iCutoverMillis); cf.iRangeDurationField = fields.months; fields.dayOfMonth = cf; } } long julianToGregorianByYear(long instant) { return convertByYear(instant, iJulianChronology, iGregorianChronology); } long gregorianToJulianByYear(long instant) { return convertByYear(instant, iGregorianChronology, iJulianChronology); } long julianToGregorianByWeekyear(long instant) { return convertByWeekyear(instant, iJulianChronology, iGregorianChronology); } long gregorianToJulianByWeekyear(long instant) { return convertByWeekyear(instant, iGregorianChronology, iJulianChronology); } //----------------------------------------------------------------------- /** * This basic cutover field adjusts calls to 'get' and 'set' methods, and * assumes that calls to add and addWrapField are unaffected by the cutover. */ private class CutoverField extends BaseDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 3528501219481026402L; final DateTimeField iJulianField; final DateTimeField iGregorianField; final long iCutover; final boolean iConvertByWeekyear; protected DurationField iDurationField; protected DurationField iRangeDurationField; /** * @param julianField field from the chronology used before the cutover instant * @param gregorianField field from the chronology used at and after the cutover * @param cutoverMillis the millis of the cutover */ CutoverField(DateTimeField julianField, DateTimeField gregorianField, long cutoverMillis) { this(julianField, gregorianField, cutoverMillis, false); } /** * @param julianField field from the chronology used before the cutover instant * @param gregorianField field from the chronology used at and after the cutover * @param cutoverMillis the millis of the cutover * @param convertByWeekyear */ CutoverField(DateTimeField julianField, DateTimeField gregorianField, long cutoverMillis, boolean convertByWeekyear) { super(gregorianField.getType()); iJulianField = julianField; iGregorianField = gregorianField; iCutover = cutoverMillis; iConvertByWeekyear = convertByWeekyear; // Although average length of Julian and Gregorian years differ, // use the Gregorian duration field because it is more accurate. iDurationField = gregorianField.getDurationField(); DurationField rangeField = gregorianField.getRangeDurationField(); if (rangeField == null) { rangeField = julianField.getRangeDurationField(); } iRangeDurationField = rangeField; } public boolean isLenient() { return false; } public int get(long instant) { if (instant >= iCutover) { return iGregorianField.get(instant); } else { return iJulianField.get(instant); } } public String getAsText(long instant, Locale locale) { if (instant >= iCutover) { return iGregorianField.getAsText(instant, locale); } else { return iJulianField.getAsText(instant, locale); } } public String getAsText(int fieldValue, Locale locale) { return iGregorianField.getAsText(fieldValue, locale); } public String getAsShortText(long instant, Locale locale) { if (instant >= iCutover) { return iGregorianField.getAsShortText(instant, locale); } else { return iJulianField.getAsShortText(instant, locale); } } public String getAsShortText(int fieldValue, Locale locale) { return iGregorianField.getAsShortText(fieldValue, locale); } public long add(long instant, int value) { return iGregorianField.add(instant, value); } public long add(long instant, long value) { return iGregorianField.add(instant, value); } public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) { // overridden as superclass algorithm can't handle // 2004-02-29 + 48 months -> 2008-02-29 type dates if (valueToAdd == 0) { return values; } if (DateTimeUtils.isContiguous(partial)) { long instant = 0L; for (int i = 0, isize = partial.size(); i < isize; i++) { instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]); } instant = add(instant, valueToAdd); return GJChronology.this.get(partial, instant); } else { return super.add(partial, fieldIndex, values, valueToAdd); } } public int getDifference(long minuendInstant, long subtrahendInstant) { return iGregorianField.getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long set(long instant, int value) { if (instant >= iCutover) { instant = iGregorianField.set(instant, value); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } // Verify that new value stuck. if (get(instant) != value) { throw new IllegalFieldValueException (iGregorianField.getType(), Integer.valueOf(value), null, null); } } } else { instant = iJulianField.set(instant, value); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } // Verify that new value stuck. if (get(instant) != value) { throw new IllegalFieldValueException (iJulianField.getType(), Integer.valueOf(value), null, null); } } } return instant; } public long set(long instant, String text, Locale locale) { if (instant >= iCutover) { instant = iGregorianField.set(instant, text, locale); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } // Cannot verify that new value stuck because set may be lenient. } } else { instant = iJulianField.set(instant, text, locale); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } // Cannot verify that new value stuck because set may be lenient. } } return instant; } public DurationField getDurationField() { return iDurationField; } public DurationField getRangeDurationField() { return iRangeDurationField; } public boolean isLeap(long instant) { if (instant >= iCutover) { return iGregorianField.isLeap(instant); } else { return iJulianField.isLeap(instant); } } public int getLeapAmount(long instant) { if (instant >= iCutover) { return iGregorianField.getLeapAmount(instant); } else { return iJulianField.getLeapAmount(instant); } } public DurationField getLeapDurationField() { return iGregorianField.getLeapDurationField(); } public int getMinimumValue() { // For all precise fields, the Julian and Gregorian limits are // identical. Choose Julian to tighten up the year limits. return iJulianField.getMinimumValue(); } public int getMinimumValue(ReadablePartial partial) { return iJulianField.getMinimumValue(partial); } public int getMinimumValue(ReadablePartial partial, int[] values) { return iJulianField.getMinimumValue(partial, values); } public int getMinimumValue(long instant) { if (instant < iCutover) { return iJulianField.getMinimumValue(instant); } int min = iGregorianField.getMinimumValue(instant); // Because the cutover may reduce the length of this field, verify // the minimum by setting it. instant = iGregorianField.set(instant, min); if (instant < iCutover) { min = iGregorianField.get(iCutover); } return min; } public int getMaximumValue() { // For all precise fields, the Julian and Gregorian limits are // identical. return iGregorianField.getMaximumValue(); } public int getMaximumValue(long instant) { if (instant >= iCutover) { return iGregorianField.getMaximumValue(instant); } int max = iJulianField.getMaximumValue(instant); // Because the cutover may reduce the length of this field, verify // the maximum by setting it. instant = iJulianField.set(instant, max); if (instant >= iCutover) { max = iJulianField.get(iJulianField.add(iCutover, -1)); } return max; } public int getMaximumValue(ReadablePartial partial) { long instant = GJChronology.getInstanceUTC().set(partial, 0L); return getMaximumValue(instant); } public int getMaximumValue(ReadablePartial partial, int[] values) { Chronology chrono = GJChronology.getInstanceUTC(); long instant = 0L; for (int i = 0, isize = partial.size(); i < isize; i++) { DateTimeField field = partial.getFieldType(i).getField(chrono); if (values[i] <= field.getMaximumValue(instant)) { instant = field.set(instant, values[i]); } } return getMaximumValue(instant); } public long roundFloor(long instant) { if (instant >= iCutover) { instant = iGregorianField.roundFloor(instant); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } } } else { instant = iJulianField.roundFloor(instant); } return instant; } public long roundCeiling(long instant) { if (instant >= iCutover) { instant = iGregorianField.roundCeiling(instant); } else { instant = iJulianField.roundCeiling(instant); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } } } return instant; } public int getMaximumTextLength(Locale locale) { return Math.max(iJulianField.getMaximumTextLength(locale), iGregorianField.getMaximumTextLength(locale)); } public int getMaximumShortTextLength(Locale locale) { return Math.max(iJulianField.getMaximumShortTextLength(locale), iGregorianField.getMaximumShortTextLength(locale)); } protected long julianToGregorian(long instant) { if (iConvertByWeekyear) { return julianToGregorianByWeekyear(instant); } else { return julianToGregorianByYear(instant); } } protected long gregorianToJulian(long instant) { if (iConvertByWeekyear) { return gregorianToJulianByWeekyear(instant); } else { return gregorianToJulianByYear(instant); } } } //----------------------------------------------------------------------- /** * Cutover field for variable length fields. These fields internally call * set whenever add is called. As a result, the same correction applied to * set must be applied to add and addWrapField. Knowing when to use this * field requires specific knowledge of how the GJ fields are implemented. */ private final class ImpreciseCutoverField extends CutoverField { @SuppressWarnings("unused") private static final long serialVersionUID = 3410248757173576441L; /** * Creates a duration field that links back to this. */ ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, long cutoverMillis) { this(julianField, gregorianField, null, cutoverMillis, false); } /** * Uses a shared duration field rather than creating a new one. * * @param durationField shared duration field */ ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, DurationField durationField, long cutoverMillis) { this(julianField, gregorianField, durationField, cutoverMillis, false); } /** * Uses a shared duration field rather than creating a new one. * * @param durationField shared duration field */ ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, DurationField durationField, long cutoverMillis, boolean convertByWeekyear) { super(julianField, gregorianField, cutoverMillis, convertByWeekyear); if (durationField == null) { durationField = new LinkedDurationField(iDurationField, this); } iDurationField = durationField; } public long add(long instant, int value) { if (instant >= iCutover) { instant = iGregorianField.add(instant, value); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { if (iConvertByWeekyear) { int wyear = iGregorianChronology.weekyear().get(instant); if (wyear <= 0) { instant = iGregorianChronology.weekyear().add(instant, -1); } } else { int year = iGregorianChronology.year().get(instant); if (year <= 0) { instant = iGregorianChronology.year().add(instant, -1); } } instant = gregorianToJulian(instant); } } } else { instant = iJulianField.add(instant, value); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { // no special handling for year zero as cutover always after year zero instant = julianToGregorian(instant); } } } return instant; } public long add(long instant, long value) { if (instant >= iCutover) { instant = iGregorianField.add(instant, value); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { if (iConvertByWeekyear) { int wyear = iGregorianChronology.weekyear().get(instant); if (wyear <= 0) { instant = iGregorianChronology.weekyear().add(instant, -1); } } else { int year = iGregorianChronology.year().get(instant); if (year <= 0) { instant = iGregorianChronology.year().add(instant, -1); } } instant = gregorianToJulian(instant); } } } else { instant = iJulianField.add(instant, value); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { // no special handling for year zero as cutover always after year zero instant = julianToGregorian(instant); } } } return instant; } public int getDifference(long minuendInstant, long subtrahendInstant) { if (minuendInstant >= iCutover) { if (subtrahendInstant >= iCutover) { return iGregorianField.getDifference(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Julian, convert minuend to Julian to match. minuendInstant = gregorianToJulian(minuendInstant); return iJulianField.getDifference(minuendInstant, subtrahendInstant); } else { if (subtrahendInstant < iCutover) { return iJulianField.getDifference(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Gregorian, convert minuend to Gregorian to match. minuendInstant = julianToGregorian(minuendInstant); return iGregorianField.getDifference(minuendInstant, subtrahendInstant); } } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant >= iCutover) { if (subtrahendInstant >= iCutover) { return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Julian, convert minuend to Julian to match. minuendInstant = gregorianToJulian(minuendInstant); return iJulianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } else { if (subtrahendInstant < iCutover) { return iJulianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Gregorian, convert minuend to Gregorian to match. minuendInstant = julianToGregorian(minuendInstant); return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } } // Since the imprecise fields have durations longer than the gap // duration, keep these methods simple. The inherited implementations // produce incorrect results. // // Degenerate case: If this field is a month, and the cutover is set // far into the future, then the gap duration may be so large as to // reduce the number of months in a year. If the missing month(s) are // at the beginning or end of the year, then the minimum and maximum // values are not 1 and 12. I don't expect this case to ever occur. public int getMinimumValue(long instant) { if (instant >= iCutover) { return iGregorianField.getMinimumValue(instant); } else { return iJulianField.getMinimumValue(instant); } } public int getMaximumValue(long instant) { if (instant >= iCutover) { return iGregorianField.getMaximumValue(instant); } else { return iJulianField.getMaximumValue(instant); } } } //----------------------------------------------------------------------- /** * Links the duration back to a ImpreciseCutoverField. */ private static class LinkedDurationField extends DecoratedDurationField { private static final long serialVersionUID = 4097975388007713084L; private final ImpreciseCutoverField iField; LinkedDurationField(DurationField durationField, ImpreciseCutoverField dateTimeField) { super(durationField, durationField.getType()); iField = dateTimeField; } public long add(long instant, int value) { return iField.add(instant, value); } public long add(long instant, long value) { return iField.add(instant, value); } public int getDifference(long minuendInstant, long subtrahendInstant) { return iField.getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } } } joda-time-2.3/src/main/java/org/joda/time/chrono/AssembledChronology.java0000644000175000017500000005021111564251363025760 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.io.IOException; import java.io.ObjectInputStream; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; /** * Abstract Chronology that enables chronologies to be assembled from * a container of fields. *

* AssembledChronology is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public abstract class AssembledChronology extends BaseChronology { private static final long serialVersionUID = -6728465968995518215L; private final Chronology iBase; private final Object iParam; private transient DurationField iMillis; private transient DurationField iSeconds; private transient DurationField iMinutes; private transient DurationField iHours; private transient DurationField iHalfdays; private transient DurationField iDays; private transient DurationField iWeeks; private transient DurationField iWeekyears; private transient DurationField iMonths; private transient DurationField iYears; private transient DurationField iCenturies; private transient DurationField iEras; private transient DateTimeField iMillisOfSecond; private transient DateTimeField iMillisOfDay; private transient DateTimeField iSecondOfMinute; private transient DateTimeField iSecondOfDay; private transient DateTimeField iMinuteOfHour; private transient DateTimeField iMinuteOfDay; private transient DateTimeField iHourOfDay; private transient DateTimeField iClockhourOfDay; private transient DateTimeField iHourOfHalfday; private transient DateTimeField iClockhourOfHalfday; private transient DateTimeField iHalfdayOfDay; private transient DateTimeField iDayOfWeek; private transient DateTimeField iDayOfMonth; private transient DateTimeField iDayOfYear; private transient DateTimeField iWeekOfWeekyear; private transient DateTimeField iWeekyear; private transient DateTimeField iWeekyearOfCentury; private transient DateTimeField iMonthOfYear; private transient DateTimeField iYear; private transient DateTimeField iYearOfEra; private transient DateTimeField iYearOfCentury; private transient DateTimeField iCenturyOfEra; private transient DateTimeField iEra; // Bit set determines which base fields are used // bit 1 set: hourOfDay, minuteOfHour, secondOfMinute, and millisOfSecond fields // bit 2 set: millisOfDayField // bit 3 set: year, monthOfYear, and dayOfMonth fields private transient int iBaseFlags; /** * Constructor calls the assemble method, enabling subclasses to define its * supported fields. If a base chronology is supplied, the field set * initially contains references to each base chronology field. *

* Other methods in this class will delegate to the base chronology, if it * can be determined that the base chronology will produce the same results * as AbstractChronology. * * @param base optional base chronology to copy initial fields from * @param param optional param object avalable for assemble method */ protected AssembledChronology(Chronology base, Object param) { iBase = base; iParam = param; setFields(); } public DateTimeZone getZone() { Chronology base; if ((base = iBase) != null) { return base.getZone(); } return null; } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { Chronology base; if ((base = iBase) != null && (iBaseFlags & 6) == 6) { // Only call specialized implementation if applicable fields are the same. return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); } return super.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = iBase) != null && (iBaseFlags & 5) == 5) { // Only call specialized implementation if applicable fields are the same. return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } return super.getDateTimeMillis(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } public long getDateTimeMillis(long instant, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = iBase) != null && (iBaseFlags & 1) == 1) { // Only call specialized implementation if applicable fields are the same. return base.getDateTimeMillis (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } return super.getDateTimeMillis (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } public final DurationField millis() { return iMillis; } public final DateTimeField millisOfSecond() { return iMillisOfSecond; } public final DateTimeField millisOfDay() { return iMillisOfDay; } public final DurationField seconds() { return iSeconds; } public final DateTimeField secondOfMinute() { return iSecondOfMinute; } public final DateTimeField secondOfDay() { return iSecondOfDay; } public final DurationField minutes() { return iMinutes; } public final DateTimeField minuteOfHour() { return iMinuteOfHour; } public final DateTimeField minuteOfDay() { return iMinuteOfDay; } public final DurationField hours() { return iHours; } public final DateTimeField hourOfDay() { return iHourOfDay; } public final DateTimeField clockhourOfDay() { return iClockhourOfDay; } public final DurationField halfdays() { return iHalfdays; } public final DateTimeField hourOfHalfday() { return iHourOfHalfday; } public final DateTimeField clockhourOfHalfday() { return iClockhourOfHalfday; } public final DateTimeField halfdayOfDay() { return iHalfdayOfDay; } public final DurationField days() { return iDays; } public final DateTimeField dayOfWeek() { return iDayOfWeek; } public final DateTimeField dayOfMonth() { return iDayOfMonth; } public final DateTimeField dayOfYear() { return iDayOfYear; } public final DurationField weeks() { return iWeeks; } public final DateTimeField weekOfWeekyear() { return iWeekOfWeekyear; } public final DurationField weekyears() { return iWeekyears; } public final DateTimeField weekyear() { return iWeekyear; } public final DateTimeField weekyearOfCentury() { return iWeekyearOfCentury; } public final DurationField months() { return iMonths; } public final DateTimeField monthOfYear() { return iMonthOfYear; } public final DurationField years() { return iYears; } public final DateTimeField year() { return iYear; } public final DateTimeField yearOfEra() { return iYearOfEra; } public final DateTimeField yearOfCentury() { return iYearOfCentury; } public final DurationField centuries() { return iCenturies; } public final DateTimeField centuryOfEra() { return iCenturyOfEra; } public final DurationField eras() { return iEras; } public final DateTimeField era() { return iEra; } /** * Invoked by the constructor and after deserialization to allow subclasses * to define all of its supported fields. All unset fields default to * unsupported instances. * * @param fields container of fields */ protected abstract void assemble(Fields fields); /** * Returns the same base chronology as passed into the constructor. */ protected final Chronology getBase() { return iBase; } /** * Returns the same param object as passed into the constructor. */ protected final Object getParam() { return iParam; } private void setFields() { Fields fields = new Fields(); if (iBase != null) { fields.copyFieldsFrom(iBase); } assemble(fields); { DurationField f; iMillis = (f = fields.millis) != null ? f : super.millis(); iSeconds = (f = fields.seconds) != null ? f : super.seconds(); iMinutes = (f = fields.minutes) != null ? f : super.minutes(); iHours = (f = fields.hours) != null ? f : super.hours(); iHalfdays = (f = fields.halfdays) != null ? f : super.halfdays(); iDays = (f = fields.days) != null ? f : super.days(); iWeeks = (f = fields.weeks) != null ? f : super.weeks(); iWeekyears = (f = fields.weekyears) != null ? f : super.weekyears(); iMonths = (f = fields.months) != null ? f : super.months(); iYears = (f = fields.years) != null ? f : super.years(); iCenturies = (f = fields.centuries) != null ? f : super.centuries(); iEras = (f = fields.eras) != null ? f : super.eras(); } { DateTimeField f; iMillisOfSecond = (f = fields.millisOfSecond) != null ? f : super.millisOfSecond(); iMillisOfDay = (f = fields.millisOfDay) != null ? f : super.millisOfDay(); iSecondOfMinute = (f = fields.secondOfMinute) != null ? f : super.secondOfMinute(); iSecondOfDay = (f = fields.secondOfDay) != null ? f : super.secondOfDay(); iMinuteOfHour = (f = fields.minuteOfHour) != null ? f : super.minuteOfHour(); iMinuteOfDay = (f = fields.minuteOfDay) != null ? f : super.minuteOfDay(); iHourOfDay = (f = fields.hourOfDay) != null ? f : super.hourOfDay(); iClockhourOfDay = (f = fields.clockhourOfDay) != null ? f : super.clockhourOfDay(); iHourOfHalfday = (f = fields.hourOfHalfday) != null ? f : super.hourOfHalfday(); iClockhourOfHalfday = (f = fields.clockhourOfHalfday) != null ? f : super.clockhourOfHalfday(); iHalfdayOfDay = (f = fields.halfdayOfDay) != null ? f : super.halfdayOfDay(); iDayOfWeek = (f = fields.dayOfWeek) != null ? f : super.dayOfWeek(); iDayOfMonth = (f = fields.dayOfMonth) != null ? f : super.dayOfMonth(); iDayOfYear = (f = fields.dayOfYear) != null ? f : super.dayOfYear(); iWeekOfWeekyear = (f = fields.weekOfWeekyear) != null ? f : super.weekOfWeekyear(); iWeekyear = (f = fields.weekyear) != null ? f : super.weekyear(); iWeekyearOfCentury = (f = fields.weekyearOfCentury) != null ? f : super.weekyearOfCentury(); iMonthOfYear = (f = fields.monthOfYear) != null ? f : super.monthOfYear(); iYear = (f = fields.year) != null ? f : super.year(); iYearOfEra = (f = fields.yearOfEra) != null ? f : super.yearOfEra(); iYearOfCentury = (f = fields.yearOfCentury) != null ? f : super.yearOfCentury(); iCenturyOfEra = (f = fields.centuryOfEra) != null ? f : super.centuryOfEra(); iEra = (f = fields.era) != null ? f : super.era(); } int flags; if (iBase == null) { flags = 0; } else { flags = ((iHourOfDay == iBase.hourOfDay() && iMinuteOfHour == iBase.minuteOfHour() && iSecondOfMinute == iBase.secondOfMinute() && iMillisOfSecond == iBase.millisOfSecond() ) ? 1 : 0) | ((iMillisOfDay == iBase.millisOfDay()) ? 2 : 0) | ((iYear == iBase.year() && iMonthOfYear == iBase.monthOfYear() && iDayOfMonth == iBase.dayOfMonth() ) ? 4 : 0); } iBaseFlags = flags; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setFields(); } /** * A container of fields used for assembling a chronology. */ public static final class Fields { public DurationField millis; public DurationField seconds; public DurationField minutes; public DurationField hours; public DurationField halfdays; public DurationField days; public DurationField weeks; public DurationField weekyears; public DurationField months; public DurationField years; public DurationField centuries; public DurationField eras; public DateTimeField millisOfSecond; public DateTimeField millisOfDay; public DateTimeField secondOfMinute; public DateTimeField secondOfDay; public DateTimeField minuteOfHour; public DateTimeField minuteOfDay; public DateTimeField hourOfDay; public DateTimeField clockhourOfDay; public DateTimeField hourOfHalfday; public DateTimeField clockhourOfHalfday; public DateTimeField halfdayOfDay; public DateTimeField dayOfWeek; public DateTimeField dayOfMonth; public DateTimeField dayOfYear; public DateTimeField weekOfWeekyear; public DateTimeField weekyear; public DateTimeField weekyearOfCentury; public DateTimeField monthOfYear; public DateTimeField year; public DateTimeField yearOfEra; public DateTimeField yearOfCentury; public DateTimeField centuryOfEra; public DateTimeField era; Fields() { } /** * Copy the supported fields from a chronology into this container. */ public void copyFieldsFrom(Chronology chrono) { { DurationField f; if (isSupported(f = chrono.millis())) { millis = f; } if (isSupported(f = chrono.seconds())) { seconds = f; } if (isSupported(f = chrono.minutes())) { minutes = f; } if (isSupported(f = chrono.hours())) { hours = f; } if (isSupported(f = chrono.halfdays())) { halfdays = f; } if (isSupported(f = chrono.days())) { days = f; } if (isSupported(f = chrono.weeks())) { weeks = f; } if (isSupported(f = chrono.weekyears())) { weekyears = f; } if (isSupported(f = chrono.months())) { months = f; } if (isSupported(f = chrono.years())) { years = f; } if (isSupported(f = chrono.centuries())) { centuries = f; } if (isSupported(f = chrono.eras())) { eras = f; } } { DateTimeField f; if (isSupported(f = chrono.millisOfSecond())) { millisOfSecond = f; } if (isSupported(f = chrono.millisOfDay())) { millisOfDay = f; } if (isSupported(f = chrono.secondOfMinute())) { secondOfMinute = f; } if (isSupported(f = chrono.secondOfDay())) { secondOfDay = f; } if (isSupported(f = chrono.minuteOfHour())) { minuteOfHour = f; } if (isSupported(f = chrono.minuteOfDay())) { minuteOfDay = f; } if (isSupported(f = chrono.hourOfDay())) { hourOfDay = f; } if (isSupported(f = chrono.clockhourOfDay())) { clockhourOfDay = f; } if (isSupported(f = chrono.hourOfHalfday())) { hourOfHalfday = f; } if (isSupported(f = chrono.clockhourOfHalfday())) { clockhourOfHalfday = f; } if (isSupported(f = chrono.halfdayOfDay())) { halfdayOfDay = f; } if (isSupported(f = chrono.dayOfWeek())) { dayOfWeek = f; } if (isSupported(f = chrono.dayOfMonth())) { dayOfMonth = f; } if (isSupported(f = chrono.dayOfYear())) { dayOfYear = f; } if (isSupported(f = chrono.weekOfWeekyear())) { weekOfWeekyear = f; } if (isSupported(f = chrono.weekyear())) { weekyear = f; } if (isSupported(f = chrono.weekyearOfCentury())) { weekyearOfCentury = f; } if (isSupported(f = chrono.monthOfYear())) { monthOfYear = f; } if (isSupported(f = chrono.year())) { year = f; } if (isSupported(f = chrono.yearOfEra())) { yearOfEra = f; } if (isSupported(f = chrono.yearOfCentury())) { yearOfCentury = f; } if (isSupported(f = chrono.centuryOfEra())) { centuryOfEra = f; } if (isSupported(f = chrono.era())) { era = f; } } } private static boolean isSupported(DurationField field) { return field == null ? false : field.isSupported(); } private static boolean isSupported(DateTimeField field) { return field == null ? false : field.isSupported(); } } } joda-time-2.3/src/main/java/org/joda/time/chrono/JulianChronology.java0000644000175000017500000002206611616003375025306 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.IllegalFieldValueException; import org.joda.time.field.SkipDateTimeField; /** * Implements a pure proleptic Julian calendar system, which defines every * fourth year as leap. This implementation follows the leap year rule * strictly, even for dates before 8 CE, where leap years were actually * irregular. In the Julian calendar, year zero does not exist: 1 BCE is * followed by 1 CE. *

* Although the Julian calendar did not exist before 45 BCE, this chronology * assumes it did, thus it is proleptic. This implementation also fixes the * start of the year at January 1. *

* JulianChronology is thread-safe and immutable. * * @see Wikipedia * @see GregorianChronology * @see GJChronology * * @author Guy Allard * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class JulianChronology extends BasicGJChronology { /** Serialization lock */ private static final long serialVersionUID = -8731039522547897247L; private static final long MILLIS_PER_YEAR = (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY); private static final long MILLIS_PER_MONTH = (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY / 12); /** The lowest year that can be fully supported. */ private static final int MIN_YEAR = -292269054; /** The highest year that can be fully supported. */ private static final int MAX_YEAR = 292272992; /** Singleton instance of a UTC JulianChronology */ private static final JulianChronology INSTANCE_UTC; /** Cache of zone to chronology arrays */ private static final Map cCache = new HashMap(); static { INSTANCE_UTC = getInstance(DateTimeZone.UTC); } static int adjustYearForSet(int year) { if (year <= 0) { if (year == 0) { throw new IllegalFieldValueException (DateTimeFieldType.year(), Integer.valueOf(year), null, null); } year++; } return year; } /** * Gets an instance of the JulianChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ public static JulianChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the JulianChronology in the default time zone. * * @return a chronology in the default time zone */ public static JulianChronology getInstance() { return getInstance(DateTimeZone.getDefault(), 4); } /** * Gets an instance of the JulianChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @return a chronology in the specified time zone */ public static JulianChronology getInstance(DateTimeZone zone) { return getInstance(zone, 4); } /** * Gets an instance of the JulianChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 * @return a chronology in the specified time zone */ public static JulianChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { if (zone == null) { zone = DateTimeZone.getDefault(); } JulianChronology chrono; synchronized (cCache) { JulianChronology[] chronos = cCache.get(zone); if (chronos == null) { chronos = new JulianChronology[7]; cCache.put(zone, chronos); } try { chrono = chronos[minDaysInFirstWeek - 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException ("Invalid min days in first week: " + minDaysInFirstWeek); } if (chrono == null) { if (zone == DateTimeZone.UTC) { chrono = new JulianChronology(null, null, minDaysInFirstWeek); } else { chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); chrono = new JulianChronology (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); } chronos[minDaysInFirstWeek - 1] = chrono; } } return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor */ JulianChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } /** * Serialization singleton */ private Object readResolve() { Chronology base = getBase(); int minDays = getMinimumDaysInFirstWeek(); minDays = (minDays == 0 ? 4 : minDays); // handle rename of BaseGJChronology return base == null ? getInstance(DateTimeZone.UTC, minDays) : getInstance(base.getZone(), minDays); } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } long getDateMidnightMillis(int year, int monthOfYear, int dayOfMonth) throws IllegalArgumentException { return super.getDateMidnightMillis(adjustYearForSet(year), monthOfYear, dayOfMonth); } boolean isLeapYear(int year) { return (year & 3) == 0; } long calculateFirstDayOfYearMillis(int year) { // Java epoch is 1970-01-01 Gregorian which is 1969-12-19 Julian. // Calculate relative to the nearest leap year and account for the // difference later. int relativeYear = year - 1968; int leapYears; if (relativeYear <= 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. leapYears = (relativeYear + 3) >> 2; } else { leapYears = relativeYear >> 2; // For post 1968 an adjustment is needed as jan1st is before leap day if (!isLeapYear(year)) { leapYears++; } } long millis = (relativeYear * 365L + leapYears) * (long)DateTimeConstants.MILLIS_PER_DAY; // Adjust to account for difference between 1968-01-01 and 1969-12-19. return millis - (366L + 352) * DateTimeConstants.MILLIS_PER_DAY; } int getMinYear() { return MIN_YEAR; } int getMaxYear() { return MAX_YEAR; } long getAverageMillisPerYear() { return MILLIS_PER_YEAR; } long getAverageMillisPerYearDividedByTwo() { return MILLIS_PER_YEAR / 2; } long getAverageMillisPerMonth() { return MILLIS_PER_MONTH; } long getApproxMillisAtEpochDividedByTwo() { return (1969L * MILLIS_PER_YEAR + 352L * DateTimeConstants.MILLIS_PER_DAY) / 2; } protected void assemble(Fields fields) { if (getBase() == null) { super.assemble(fields); // Julian chronology has no year zero. fields.year = new SkipDateTimeField(this, fields.year); fields.weekyear = new SkipDateTimeField(this, fields.weekyear); } } } joda-time-2.3/src/main/java/org/joda/time/chrono/IslamicChronology.java0000644000175000017500000005216112200501234025427 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; /** * Implements the Islamic, or Hijri, calendar system using arithmetic rules. *

* This calendar is a lunar calendar with a shorter year than ISO. * Year 1 in the Islamic calendar began on July 16, 622 CE (Julian), thus * Islamic years do not begin at the same time as Julian years. This chronology * is not proleptic, as it does not allow dates before the first Islamic year. *

* There are two basic forms of the Islamic calendar, the tabular and the * observed. The observed form cannot easily be used by computers as it * relies on human observation of the new moon. * The tabular calendar, implemented here, is an arithmetical approximation * of the observed form that follows relatively simple rules. *

* The tabular form of the calendar defines 12 months of alternately * 30 and 29 days. The last month is extended to 30 days in a leap year. * Leap years occur according to a 30 year cycle. There are four recognised * patterns of leap years in the 30 year cycle: *

 * Years 2, 5, 7, 10, 13, 15, 18, 21, 24, 26 & 29 - 15-based, used by Microsoft
 * Years 2, 5, 7, 10, 13, 16, 18, 21, 24, 26 & 29 - 16-based, most commonly used
 * Years 2, 5, 8, 10, 13, 16, 19, 21, 24, 27 & 29 - Indian
 * Years 2, 5, 8, 11, 13, 16, 19, 21, 24, 27 & 30 - Habash al-Hasib
 * 
* You can select which pattern to use via the factory methods, or use the * default (16-based). *

* This implementation defines a day as midnight to midnight exactly as per * the ISO chronology. This correct start of day is at sunset on the previous * day, however this cannot readily be modelled and has been ignored. *

* IslamicChronology is thread-safe and immutable. * * @see Wikipedia * * @author Stephen Colebourne * @since 1.2 */ public final class IslamicChronology extends BasicChronology { /** Serialization lock */ private static final long serialVersionUID = -3663823829888L; /** * Constant value for 'Anno Hegirae', equivalent * to the value returned for AD/CE. */ public static final int AH = DateTimeConstants.CE; /** A singleton era field. */ private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("AH"); /** Leap year 15-based pattern. */ public static final LeapYearPatternType LEAP_YEAR_15_BASED = new LeapYearPatternType(0, 623158436); /** Leap year 16-based pattern. */ public static final LeapYearPatternType LEAP_YEAR_16_BASED = new LeapYearPatternType(1, 623191204); /** Leap year Indian pattern. */ public static final LeapYearPatternType LEAP_YEAR_INDIAN = new LeapYearPatternType(2, 690562340); /** Leap year Habash al-Hasib pattern. */ public static final LeapYearPatternType LEAP_YEAR_HABASH_AL_HASIB = new LeapYearPatternType(3, 153692453); /** The lowest year that can be fully supported. */ private static final int MIN_YEAR = -292269337; /** * The highest year that can be fully supported. * Although calculateFirstDayOfYearMillis can go higher without * overflowing, the getYear method overflows when it adds the * approximate millis at the epoch. */ private static final int MAX_YEAR = 292271022; /** The days in a pair of months. */ private static final int MONTH_PAIR_LENGTH = 59; /** The length of the long month. */ private static final int LONG_MONTH_LENGTH = 30; /** The length of the short month. */ private static final int SHORT_MONTH_LENGTH = 29; /** The length of the long month in millis. */ private static final long MILLIS_PER_MONTH_PAIR = 59L * DateTimeConstants.MILLIS_PER_DAY; /** The length of the long month in millis. */ private static final long MILLIS_PER_MONTH = (long) (29.53056 * DateTimeConstants.MILLIS_PER_DAY); /** The length of the long month in millis. */ private static final long MILLIS_PER_LONG_MONTH = 30L * DateTimeConstants.MILLIS_PER_DAY; /** The typical millis per year. */ private static final long MILLIS_PER_YEAR = (long) (354.36667 * DateTimeConstants.MILLIS_PER_DAY); /** The typical millis per year. */ private static final long MILLIS_PER_SHORT_YEAR = 354L * DateTimeConstants.MILLIS_PER_DAY; /** The typical millis per year. */ private static final long MILLIS_PER_LONG_YEAR = 355L * DateTimeConstants.MILLIS_PER_DAY; /** The millis of 0001-01-01. */ private static final long MILLIS_YEAR_1 = -42521587200000L; // -42520809600000L; // long start = 0L - 278L * DateTimeConstants.MILLIS_PER_DAY; // long cy = 46L * MILLIS_PER_CYCLE; // 1381-01-01 // long rem = 5L * MILLIS_PER_SHORT_YEAR + // 3L * MILLIS_PER_LONG_YEAR; // 1389-01-01 /** The length of the cycle of leap years. */ private static final int CYCLE = 30; /** The millis of a 30 year cycle. */ private static final long MILLIS_PER_CYCLE = ((19L * 354L + 11L * 355L) * DateTimeConstants.MILLIS_PER_DAY); /** Cache of zone to chronology arrays */ private static final Map cCache = new HashMap(); /** Singleton instance of a UTC IslamicChronology */ private static final IslamicChronology INSTANCE_UTC; static { // init after static fields INSTANCE_UTC = getInstance(DateTimeZone.UTC); } /** The leap years to use. */ private final LeapYearPatternType iLeapYears; //----------------------------------------------------------------------- /** * Gets an instance of the IslamicChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ public static IslamicChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the IslamicChronology in the default time zone. * * @return a chronology in the default time zone */ public static IslamicChronology getInstance() { return getInstance(DateTimeZone.getDefault(), LEAP_YEAR_16_BASED); } /** * Gets an instance of the IslamicChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @return a chronology in the specified time zone */ public static IslamicChronology getInstance(DateTimeZone zone) { return getInstance(zone, LEAP_YEAR_16_BASED); } /** * Gets an instance of the IslamicChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @param leapYears the type defining the leap year pattern * @return a chronology in the specified time zone */ public static IslamicChronology getInstance(DateTimeZone zone, LeapYearPatternType leapYears) { if (zone == null) { zone = DateTimeZone.getDefault(); } IslamicChronology chrono; synchronized (cCache) { IslamicChronology[] chronos = cCache.get(zone); if (chronos == null) { chronos = new IslamicChronology[4]; cCache.put(zone, chronos); } chrono = chronos[leapYears.index]; if (chrono == null) { if (zone == DateTimeZone.UTC) { // First create without a lower limit. chrono = new IslamicChronology(null, null, leapYears); // Impose lower limit and make another IslamicChronology. DateTime lowerLimit = new DateTime(1, 1, 1, 0, 0, 0, 0, chrono); chrono = new IslamicChronology( LimitChronology.getInstance(chrono, lowerLimit, null), null, leapYears); } else { chrono = getInstance(DateTimeZone.UTC, leapYears); chrono = new IslamicChronology (ZonedChronology.getInstance(chrono, zone), null, leapYears); } chronos[leapYears.index] = chrono; } } return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor. */ IslamicChronology(Chronology base, Object param, LeapYearPatternType leapYears) { super(base, param, 4); this.iLeapYears = leapYears; } /** * Serialization singleton. */ private Object readResolve() { Chronology base = getBase(); return base == null ? getInstanceUTC() : getInstance(base.getZone()); } //----------------------------------------------------------------------- /** * Gets the leap year pattern type. * * @return the pattern type */ public LeapYearPatternType getLeapYearPatternType() { return iLeapYears; } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } //----------------------------------------------------------------------- /** * Checks if this chronology instance equals another. * * @param obj the object to compare to * @return true if equal * @since 2.3 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof IslamicChronology) { IslamicChronology chrono = (IslamicChronology) obj; return getLeapYearPatternType().index == chrono.getLeapYearPatternType().index && super.equals(obj); } return false; } /** * A suitable hash code for the chronology. * * @return the hash code * @since 1.6 */ public int hashCode() { return super.hashCode() * 13 + getLeapYearPatternType().hashCode(); } //----------------------------------------------------------------------- int getYear(long instant) { long millisIslamic = instant - MILLIS_YEAR_1; long cycles = millisIslamic / MILLIS_PER_CYCLE; long cycleRemainder = millisIslamic % MILLIS_PER_CYCLE; int year = (int) ((cycles * CYCLE) + 1L); long yearMillis = (isLeapYear(year) ? MILLIS_PER_LONG_YEAR : MILLIS_PER_SHORT_YEAR); while (cycleRemainder >= yearMillis) { cycleRemainder -= yearMillis; yearMillis = (isLeapYear(++year) ? MILLIS_PER_LONG_YEAR : MILLIS_PER_SHORT_YEAR); } return year; } long setYear(long instant, int year) { // optimsed implementation of set, due to fixed months int thisYear = getYear(instant); int dayOfYear = getDayOfYear(instant, thisYear); int millisOfDay = getMillisOfDay(instant); if (dayOfYear > 354) { // Current year is leap, and day is leap. if (!isLeapYear(year)) { // Moving to a non-leap year, leap day doesn't exist. dayOfYear--; } } instant = getYearMonthDayMillis(year, 1, dayOfYear); instant += millisOfDay; return instant; } //----------------------------------------------------------------------- long getYearDifference(long minuendInstant, long subtrahendInstant) { // optimsed implementation of getDifference, due to fixed months int minuendYear = getYear(minuendInstant); int subtrahendYear = getYear(subtrahendInstant); // Inlined remainder method to avoid duplicate calls to get. long minuendRem = minuendInstant - getYearMillis(minuendYear); long subtrahendRem = subtrahendInstant - getYearMillis(subtrahendYear); int difference = minuendYear - subtrahendYear; if (minuendRem < subtrahendRem) { difference--; } return difference; } //----------------------------------------------------------------------- long getTotalMillisByYearMonth(int year, int month) { if (--month % 2 == 1) { month /= 2; return month * MILLIS_PER_MONTH_PAIR + MILLIS_PER_LONG_MONTH; } else { month /= 2; return month * MILLIS_PER_MONTH_PAIR; } } //----------------------------------------------------------------------- int getDayOfMonth(long millis) { // optimised for simple months int doy = getDayOfYear(millis) - 1; if (doy == 354) { return 30; } return (doy % MONTH_PAIR_LENGTH) % LONG_MONTH_LENGTH + 1; } //----------------------------------------------------------------------- boolean isLeapYear(int year) { return iLeapYears.isLeapYear(year); } //----------------------------------------------------------------------- int getDaysInYearMax() { return 355; } //----------------------------------------------------------------------- int getDaysInYear(int year) { return isLeapYear(year) ? 355 : 354; } //----------------------------------------------------------------------- int getDaysInYearMonth(int year, int month) { if (month == 12 && isLeapYear(year)) { return LONG_MONTH_LENGTH; } return (--month % 2 == 0 ? LONG_MONTH_LENGTH : SHORT_MONTH_LENGTH); } //----------------------------------------------------------------------- int getDaysInMonthMax() { return LONG_MONTH_LENGTH; } //----------------------------------------------------------------------- int getDaysInMonthMax(int month) { if (month == 12) { return LONG_MONTH_LENGTH; } return (--month % 2 == 0 ? LONG_MONTH_LENGTH : SHORT_MONTH_LENGTH); } //----------------------------------------------------------------------- int getMonthOfYear(long millis, int year) { int doyZeroBased = (int) ((millis - getYearMillis(year)) / DateTimeConstants.MILLIS_PER_DAY); if (doyZeroBased == 354) { return 12; } return ((doyZeroBased * 2) / MONTH_PAIR_LENGTH) + 1; // return (int) (doyZeroBased / 29.9f) + 1; // // int monthPairZeroBased = doyZeroBased / MONTH_PAIR_LENGTH; // int monthPairRemainder = doyZeroBased % MONTH_PAIR_LENGTH; // return (monthPairZeroBased * 2) + 1 + (monthPairRemainder >= LONG_MONTH_LENGTH ? 1 : 0); } //----------------------------------------------------------------------- long getAverageMillisPerYear() { return MILLIS_PER_YEAR; } //----------------------------------------------------------------------- long getAverageMillisPerYearDividedByTwo() { return MILLIS_PER_YEAR / 2; } //----------------------------------------------------------------------- long getAverageMillisPerMonth() { return MILLIS_PER_MONTH; } //----------------------------------------------------------------------- long calculateFirstDayOfYearMillis(int year) { if (year > MAX_YEAR) { throw new ArithmeticException("Year is too large: " + year + " > " + MAX_YEAR); } if (year < MIN_YEAR) { throw new ArithmeticException("Year is too small: " + year + " < " + MIN_YEAR); } // Java epoch is 1970-01-01 Gregorian which is 0622-07-16 Islamic. // 0001-01-01 Islamic is -42520809600000L // would prefer to calculate against year zero, but leap year // can be in that year so it doesn't work year--; long cycle = year / CYCLE; long millis = MILLIS_YEAR_1 + cycle * MILLIS_PER_CYCLE; int cycleRemainder = (year % CYCLE) + 1; for (int i = 1; i < cycleRemainder; i++) { millis += (isLeapYear(i) ? MILLIS_PER_LONG_YEAR : MILLIS_PER_SHORT_YEAR); } return millis; } //----------------------------------------------------------------------- int getMinYear() { return 1; //MIN_YEAR; } //----------------------------------------------------------------------- int getMaxYear() { return MAX_YEAR; } //----------------------------------------------------------------------- long getApproxMillisAtEpochDividedByTwo() { // Epoch 1970-01-01 ISO = 1389-10-22 Islamic return (-MILLIS_YEAR_1) / 2; } //----------------------------------------------------------------------- protected void assemble(Fields fields) { if (getBase() == null) { super.assemble(fields); fields.era = ERA_FIELD; fields.monthOfYear = new BasicMonthOfYearDateTimeField(this, 12); fields.months = fields.monthOfYear.getDurationField(); } } //----------------------------------------------------------------------- /** * Opaque object describing a leap year pattern for the Islamic Chronology. * * @since 1.2 */ public static class LeapYearPatternType implements Serializable { /** Serialization lock */ private static final long serialVersionUID = 26581275372698L; // /** Leap year raw data encoded into bits. */ // private static final int[][] LEAP_YEARS = { // {2, 5, 7, 10, 13, 15, 18, 21, 24, 26, 29}, // 623158436 // {2, 5, 7, 10, 13, 16, 18, 21, 24, 26, 29}, // 623191204 // {2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29}, // 690562340 // {0, 2, 5, 8, 11, 13, 16, 19, 21, 24, 27}, // 153692453 // }; /** The index. */ final byte index; /** The leap year pattern, a bit-based 1=true pattern. */ final int pattern; /** * Constructor. * This constructor takes a bit pattern where bits 0-29 correspond * to years 0-29 in the 30 year Islamic cycle of years. This allows * a highly efficient lookup by bit-matching. * * @param index the index * @param pattern the bit pattern */ LeapYearPatternType(int index, int pattern) { super(); this.index = (byte) index; this.pattern = pattern; } /** * Is the year a leap year. * @param year the year to query * @return true if leap */ boolean isLeapYear(int year) { int key = 1 << (year % 30); return ((pattern & key) > 0); } /** * Ensure a singleton is returned if possible. * @return the singleton instance */ private Object readResolve() { switch (index) { case 0: return LEAP_YEAR_15_BASED; case 1: return LEAP_YEAR_16_BASED; case 2: return LEAP_YEAR_INDIAN; case 3: return LEAP_YEAR_HABASH_AL_HASIB; default: return this; } } @Override public boolean equals(Object obj) { if (obj instanceof LeapYearPatternType) { return index == ((LeapYearPatternType) obj).index; } return false; } @Override public int hashCode() { return index; } } } joda-time-2.3/src/main/java/org/joda/time/chrono/GJLocaleSymbols.java0000644000175000017500000002046711616003375025014 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.lang.ref.WeakReference; import java.text.DateFormatSymbols; import java.util.Locale; import java.util.TreeMap; import java.util.WeakHashMap; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.IllegalFieldValueException; /** * Utility class used by a few of the GJDateTimeFields. * * @author Brian S O'Neill * @since 1.0 */ class GJLocaleSymbols { private static final int FAST_CACHE_SIZE = 64; private static final GJLocaleSymbols[] cFastCache = new GJLocaleSymbols[FAST_CACHE_SIZE]; private static WeakHashMap cCache = new WeakHashMap(); public static GJLocaleSymbols forLocale(Locale locale) { if (locale == null) { locale = Locale.getDefault(); } int index = System.identityHashCode(locale) & (FAST_CACHE_SIZE - 1); GJLocaleSymbols symbols = cFastCache[index]; if (symbols != null && symbols.iLocale.get() == locale) { return symbols; } synchronized (cCache) { symbols = cCache.get(locale); if (symbols == null) { symbols = new GJLocaleSymbols(locale); cCache.put(locale, symbols); } } cFastCache[index] = symbols; return symbols; } private static String[] realignMonths(String[] months) { String[] a = new String[13]; for (int i=1; i<13; i++) { a[i] = months[i - 1]; } return a; } private static String[] realignDaysOfWeek(String[] daysOfWeek) { String[] a = new String[8]; for (int i=1; i<8; i++) { a[i] = daysOfWeek[(i < 7) ? i + 1 : 1]; } return a; } private static void addSymbols(TreeMap map, String[] symbols, Integer[] integers) { for (int i=symbols.length; --i>=0; ) { String symbol = symbols[i]; if (symbol != null) { map.put(symbol, integers[i]); } } } private static void addNumerals(TreeMap map, int start, int end, Integer[] integers) { for (int i=start; i<=end; i++) { map.put(String.valueOf(i).intern(), integers[i]); } } private static int maxLength(String[] a) { int max = 0; for (int i=a.length; --i>=0; ) { String s = a[i]; if (s != null) { int len = s.length(); if (len > max) { max = len; } } } return max; } private final WeakReference iLocale; private final String[] iEras; private final String[] iDaysOfWeek; private final String[] iShortDaysOfWeek; private final String[] iMonths; private final String[] iShortMonths; private final String[] iHalfday; private final TreeMap iParseEras; private final TreeMap iParseDaysOfWeek; private final TreeMap iParseMonths; private final int iMaxEraLength; private final int iMaxDayOfWeekLength; private final int iMaxShortDayOfWeekLength; private final int iMaxMonthLength; private final int iMaxShortMonthLength; private final int iMaxHalfdayLength; /** * @param locale must not be null */ private GJLocaleSymbols(Locale locale) { iLocale = new WeakReference(locale); DateFormatSymbols dfs = DateTimeUtils.getDateFormatSymbols(locale); iEras = dfs.getEras(); iDaysOfWeek = realignDaysOfWeek(dfs.getWeekdays()); iShortDaysOfWeek = realignDaysOfWeek(dfs.getShortWeekdays()); iMonths = realignMonths(dfs.getMonths()); iShortMonths = realignMonths(dfs.getShortMonths()); iHalfday = dfs.getAmPmStrings(); Integer[] integers = new Integer[13]; for (int i=0; i<13; i++) { integers[i] = Integer.valueOf(i); } iParseEras = new TreeMap(String.CASE_INSENSITIVE_ORDER); addSymbols(iParseEras, iEras, integers); if ("en".equals(locale.getLanguage())) { // Include support for parsing "BCE" and "CE" if the language is // English. At some point Joda-Time will need an independent set of // localized symbols and not depend on java.text.DateFormatSymbols. iParseEras.put("BCE", integers[0]); iParseEras.put("CE", integers[1]); } iParseDaysOfWeek = new TreeMap(String.CASE_INSENSITIVE_ORDER); addSymbols(iParseDaysOfWeek, iDaysOfWeek, integers); addSymbols(iParseDaysOfWeek, iShortDaysOfWeek, integers); addNumerals(iParseDaysOfWeek, 1, 7, integers); iParseMonths = new TreeMap(String.CASE_INSENSITIVE_ORDER); addSymbols(iParseMonths, iMonths, integers); addSymbols(iParseMonths, iShortMonths, integers); addNumerals(iParseMonths, 1, 12, integers); iMaxEraLength = maxLength(iEras); iMaxDayOfWeekLength = maxLength(iDaysOfWeek); iMaxShortDayOfWeekLength = maxLength(iShortDaysOfWeek); iMaxMonthLength = maxLength(iMonths); iMaxShortMonthLength = maxLength(iShortMonths); iMaxHalfdayLength = maxLength(iHalfday); } public String eraValueToText(int value) { return iEras[value]; } public int eraTextToValue(String text) { Integer era = iParseEras.get(text); if (era != null) { return era.intValue(); } throw new IllegalFieldValueException(DateTimeFieldType.era(), text); } public int getEraMaxTextLength() { return iMaxEraLength; } public String monthOfYearValueToText(int value) { return iMonths[value]; } public String monthOfYearValueToShortText(int value) { return iShortMonths[value]; } public int monthOfYearTextToValue(String text) { Integer month = iParseMonths.get(text); if (month != null) { return month.intValue(); } throw new IllegalFieldValueException(DateTimeFieldType.monthOfYear(), text); } public int getMonthMaxTextLength() { return iMaxMonthLength; } public int getMonthMaxShortTextLength() { return iMaxShortMonthLength; } public String dayOfWeekValueToText(int value) { return iDaysOfWeek[value]; } public String dayOfWeekValueToShortText(int value) { return iShortDaysOfWeek[value]; } public int dayOfWeekTextToValue(String text) { Integer day = iParseDaysOfWeek.get(text); if (day != null) { return day.intValue(); } throw new IllegalFieldValueException(DateTimeFieldType.dayOfWeek(), text); } public int getDayOfWeekMaxTextLength() { return iMaxDayOfWeekLength; } public int getDayOfWeekMaxShortTextLength() { return iMaxShortDayOfWeekLength; } public String halfdayValueToText(int value) { return iHalfday[value]; } public int halfdayTextToValue(String text) { String[] halfday = iHalfday; for (int i = halfday.length; --i>=0; ) { if (halfday[i].equalsIgnoreCase(text)) { return i; } } throw new IllegalFieldValueException(DateTimeFieldType.halfdayOfDay(), text); } public int getHalfdayMaxTextLength() { return iMaxHalfdayLength; } } joda-time-2.3/src/main/java/org/joda/time/chrono/ISOYearOfEraDateTimeField.java0000644000175000017500000000672712203435052026571 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.ReadablePartial; import org.joda.time.field.DecoratedDateTimeField; import org.joda.time.field.FieldUtils; /** * This field is not publicy exposed by ISOChronology, but rather it is used to * build the yearOfCentury and centuryOfEra fields. It merely drops the sign of * the year. * * @author Brian S O'Neill * @see GJYearOfEraDateTimeField * @since 1.0 */ class ISOYearOfEraDateTimeField extends DecoratedDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 7037524068969447317L; /** * Singleton instance */ static final DateTimeField INSTANCE = new ISOYearOfEraDateTimeField(); /** * Restricted constructor. */ private ISOYearOfEraDateTimeField() { super(GregorianChronology.getInstanceUTC().year(), DateTimeFieldType.yearOfEra()); } public int get(long instant) { int year = getWrappedField().get(instant); return year < 0 ? -year : year; } public long add(long instant, int years) { return getWrappedField().add(instant, years); } public long add(long instant, long years) { return getWrappedField().add(instant, years); } public long addWrapField(long instant, int years) { return getWrappedField().addWrapField(instant, years); } public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int years) { return getWrappedField().addWrapField(instant, fieldIndex, values, years); } public int getDifference(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long set(long instant, int year) { FieldUtils.verifyValueBounds(this, year, 0, getMaximumValue()); if (getWrappedField().get(instant) < 0) { year = -year; } return super.set(instant, year); } public int getMinimumValue() { return 0; } public int getMaximumValue() { return getWrappedField().getMaximumValue(); } public long roundFloor(long instant) { return getWrappedField().roundFloor(instant); } public long roundCeiling(long instant) { return getWrappedField().roundCeiling(instant); } public long remainder(long instant) { return getWrappedField().remainder(instant); } /** * Serialization singleton */ private Object readResolve() { return INSTANCE; } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicChronology.java0000644000175000017500000006621212203434632025103 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.field.DividedDateTimeField; import org.joda.time.field.FieldUtils; import org.joda.time.field.MillisDurationField; import org.joda.time.field.OffsetDateTimeField; import org.joda.time.field.PreciseDateTimeField; import org.joda.time.field.PreciseDurationField; import org.joda.time.field.RemainderDateTimeField; import org.joda.time.field.ZeroIsMaxDateTimeField; /** * Abstract implementation for calendar systems that use a typical * day/month/year/leapYear model. * Most of the utility methods required by subclasses are package-private, * reflecting the intention that they be defined in the same package. *

* BasicChronology is thread-safe and immutable, and all subclasses must * be as well. * * @author Stephen Colebourne * @author Brian S O'Neill * @author Guy Allard * @since 1.2, renamed from BaseGJChronology */ abstract class BasicChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = 8283225332206808863L; private static final DurationField cMillisField; private static final DurationField cSecondsField; private static final DurationField cMinutesField; private static final DurationField cHoursField; private static final DurationField cHalfdaysField; private static final DurationField cDaysField; private static final DurationField cWeeksField; private static final DateTimeField cMillisOfSecondField; private static final DateTimeField cMillisOfDayField; private static final DateTimeField cSecondOfMinuteField; private static final DateTimeField cSecondOfDayField; private static final DateTimeField cMinuteOfHourField; private static final DateTimeField cMinuteOfDayField; private static final DateTimeField cHourOfDayField; private static final DateTimeField cHourOfHalfdayField; private static final DateTimeField cClockhourOfDayField; private static final DateTimeField cClockhourOfHalfdayField; private static final DateTimeField cHalfdayOfDayField; static { cMillisField = MillisDurationField.INSTANCE; cSecondsField = new PreciseDurationField (DurationFieldType.seconds(), DateTimeConstants.MILLIS_PER_SECOND); cMinutesField = new PreciseDurationField (DurationFieldType.minutes(), DateTimeConstants.MILLIS_PER_MINUTE); cHoursField = new PreciseDurationField (DurationFieldType.hours(), DateTimeConstants.MILLIS_PER_HOUR); cHalfdaysField = new PreciseDurationField (DurationFieldType.halfdays(), DateTimeConstants.MILLIS_PER_DAY / 2); cDaysField = new PreciseDurationField (DurationFieldType.days(), DateTimeConstants.MILLIS_PER_DAY); cWeeksField = new PreciseDurationField (DurationFieldType.weeks(), DateTimeConstants.MILLIS_PER_WEEK); cMillisOfSecondField = new PreciseDateTimeField (DateTimeFieldType.millisOfSecond(), cMillisField, cSecondsField); cMillisOfDayField = new PreciseDateTimeField (DateTimeFieldType.millisOfDay(), cMillisField, cDaysField); cSecondOfMinuteField = new PreciseDateTimeField (DateTimeFieldType.secondOfMinute(), cSecondsField, cMinutesField); cSecondOfDayField = new PreciseDateTimeField (DateTimeFieldType.secondOfDay(), cSecondsField, cDaysField); cMinuteOfHourField = new PreciseDateTimeField (DateTimeFieldType.minuteOfHour(), cMinutesField, cHoursField); cMinuteOfDayField = new PreciseDateTimeField (DateTimeFieldType.minuteOfDay(), cMinutesField, cDaysField); cHourOfDayField = new PreciseDateTimeField (DateTimeFieldType.hourOfDay(), cHoursField, cDaysField); cHourOfHalfdayField = new PreciseDateTimeField (DateTimeFieldType.hourOfHalfday(), cHoursField, cHalfdaysField); cClockhourOfDayField = new ZeroIsMaxDateTimeField (cHourOfDayField, DateTimeFieldType.clockhourOfDay()); cClockhourOfHalfdayField = new ZeroIsMaxDateTimeField (cHourOfHalfdayField, DateTimeFieldType.clockhourOfHalfday()); cHalfdayOfDayField = new HalfdayField(); } private static final int CACHE_SIZE = 1 << 10; private static final int CACHE_MASK = CACHE_SIZE - 1; private transient final YearInfo[] iYearInfoCache = new YearInfo[CACHE_SIZE]; private final int iMinDaysInFirstWeek; BasicChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param); if (minDaysInFirstWeek < 1 || minDaysInFirstWeek > 7) { throw new IllegalArgumentException ("Invalid min days in first week: " + minDaysInFirstWeek); } iMinDaysInFirstWeek = minDaysInFirstWeek; } public DateTimeZone getZone() { Chronology base; if ((base = getBase()) != null) { return base.getZone(); } return DateTimeZone.UTC; } public long getDateTimeMillis( int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); } FieldUtils.verifyValueBounds (DateTimeFieldType.millisOfDay(), millisOfDay, 0, DateTimeConstants.MILLIS_PER_DAY - 1); return getDateMidnightMillis(year, monthOfYear, dayOfMonth) + millisOfDay; } public long getDateTimeMillis( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } FieldUtils.verifyValueBounds(DateTimeFieldType.hourOfDay(), hourOfDay, 0, 23); FieldUtils.verifyValueBounds(DateTimeFieldType.minuteOfHour(), minuteOfHour, 0, 59); FieldUtils.verifyValueBounds(DateTimeFieldType.secondOfMinute(), secondOfMinute, 0, 59); FieldUtils.verifyValueBounds(DateTimeFieldType.millisOfSecond(), millisOfSecond, 0, 999); return getDateMidnightMillis(year, monthOfYear, dayOfMonth) + hourOfDay * DateTimeConstants.MILLIS_PER_HOUR + minuteOfHour * DateTimeConstants.MILLIS_PER_MINUTE + secondOfMinute * DateTimeConstants.MILLIS_PER_SECOND + millisOfSecond; } public int getMinimumDaysInFirstWeek() { return iMinDaysInFirstWeek; } //----------------------------------------------------------------------- /** * Checks if this chronology instance equals another. * * @param obj the object to compare to * @return true if equal * @since 1.6 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && getClass() == obj.getClass()) { BasicChronology chrono = (BasicChronology) obj; return getMinimumDaysInFirstWeek() == chrono.getMinimumDaysInFirstWeek() && getZone().equals(chrono.getZone()); } return false; } /** * A suitable hash code for the chronology. * * @return the hash code * @since 1.6 */ public int hashCode() { return getClass().getName().hashCode() * 11 + getZone().hashCode() + getMinimumDaysInFirstWeek(); } // Output //----------------------------------------------------------------------- /** * Gets a debugging toString. * * @return a debugging string */ public String toString() { StringBuilder sb = new StringBuilder(60); String name = getClass().getName(); int index = name.lastIndexOf('.'); if (index >= 0) { name = name.substring(index + 1); } sb.append(name); sb.append('['); DateTimeZone zone = getZone(); if (zone != null) { sb.append(zone.getID()); } if (getMinimumDaysInFirstWeek() != 4) { sb.append(",mdfw="); sb.append(getMinimumDaysInFirstWeek()); } sb.append(']'); return sb.toString(); } protected void assemble(Fields fields) { // First copy fields that are the same for all Gregorian and Julian // chronologies. fields.millis = cMillisField; fields.seconds = cSecondsField; fields.minutes = cMinutesField; fields.hours = cHoursField; fields.halfdays = cHalfdaysField; fields.days = cDaysField; fields.weeks = cWeeksField; fields.millisOfSecond = cMillisOfSecondField; fields.millisOfDay = cMillisOfDayField; fields.secondOfMinute = cSecondOfMinuteField; fields.secondOfDay = cSecondOfDayField; fields.minuteOfHour = cMinuteOfHourField; fields.minuteOfDay = cMinuteOfDayField; fields.hourOfDay = cHourOfDayField; fields.hourOfHalfday = cHourOfHalfdayField; fields.clockhourOfDay = cClockhourOfDayField; fields.clockhourOfHalfday = cClockhourOfHalfdayField; fields.halfdayOfDay = cHalfdayOfDayField; // Now create fields that have unique behavior for Gregorian and Julian // chronologies. fields.year = new BasicYearDateTimeField(this); fields.yearOfEra = new GJYearOfEraDateTimeField(fields.year, this); // Define one-based centuryOfEra and yearOfCentury. DateTimeField field = new OffsetDateTimeField( fields.yearOfEra, 99); fields.centuryOfEra = new DividedDateTimeField( field, DateTimeFieldType.centuryOfEra(), 100); field = new RemainderDateTimeField( (DividedDateTimeField) fields.centuryOfEra); fields.yearOfCentury = new OffsetDateTimeField( field, DateTimeFieldType.yearOfCentury(), 1); fields.era = new GJEraDateTimeField(this); fields.dayOfWeek = new GJDayOfWeekDateTimeField(this, fields.days); fields.dayOfMonth = new BasicDayOfMonthDateTimeField(this, fields.days); fields.dayOfYear = new BasicDayOfYearDateTimeField(this, fields.days); fields.monthOfYear = new GJMonthOfYearDateTimeField(this); fields.weekyear = new BasicWeekyearDateTimeField(this); fields.weekOfWeekyear = new BasicWeekOfWeekyearDateTimeField(this, fields.weeks); field = new RemainderDateTimeField( fields.weekyear, DateTimeFieldType.weekyearOfCentury(), 100); fields.weekyearOfCentury = new OffsetDateTimeField( field, DateTimeFieldType.weekyearOfCentury(), 1); // The remaining (imprecise) durations are available from the newly // created datetime fields. fields.years = fields.year.getDurationField(); fields.centuries = fields.centuryOfEra.getDurationField(); fields.months = fields.monthOfYear.getDurationField(); fields.weekyears = fields.weekyear.getDurationField(); } //----------------------------------------------------------------------- /** * Get the number of days in the year. * * @return 366 */ int getDaysInYearMax() { return 366; } /** * Get the number of days in the year. * * @param year the year to use * @return 366 if a leap year, otherwise 365 */ int getDaysInYear(int year) { return isLeapYear(year) ? 366 : 365; } /** * Get the number of weeks in the year. * * @param year the year to use * @return number of weeks in the year */ int getWeeksInYear(int year) { long firstWeekMillis1 = getFirstWeekOfYearMillis(year); long firstWeekMillis2 = getFirstWeekOfYearMillis(year + 1); return (int) ((firstWeekMillis2 - firstWeekMillis1) / DateTimeConstants.MILLIS_PER_WEEK); } /** * Get the millis for the first week of a year. * * @param year the year to use * @return millis */ long getFirstWeekOfYearMillis(int year) { long jan1millis = getYearMillis(year); int jan1dayOfWeek = getDayOfWeek(jan1millis); if (jan1dayOfWeek > (8 - iMinDaysInFirstWeek)) { // First week is end of previous year because it doesn't have enough days. return jan1millis + (8 - jan1dayOfWeek) * (long)DateTimeConstants.MILLIS_PER_DAY; } else { // First week is start of this year because it has enough days. return jan1millis - (jan1dayOfWeek - 1) * (long)DateTimeConstants.MILLIS_PER_DAY; } } /** * Get the milliseconds for the start of a year. * * @param year The year to use. * @return millis from 1970-01-01T00:00:00Z */ long getYearMillis(int year) { return getYearInfo(year).iFirstDayMillis; } /** * Get the milliseconds for the start of a month. * * @param year The year to use. * @param month The month to use * @return millis from 1970-01-01T00:00:00Z */ long getYearMonthMillis(int year, int month) { long millis = getYearMillis(year); millis += getTotalMillisByYearMonth(year, month); return millis; } /** * Get the milliseconds for a particular date. * * @param year The year to use. * @param month The month to use * @param dayOfMonth The day of the month to use * @return millis from 1970-01-01T00:00:00Z */ long getYearMonthDayMillis(int year, int month, int dayOfMonth) { long millis = getYearMillis(year); millis += getTotalMillisByYearMonth(year, month); return millis + (dayOfMonth - 1) * (long)DateTimeConstants.MILLIS_PER_DAY; } /** * @param instant millis from 1970-01-01T00:00:00Z */ int getYear(long instant) { // Get an initial estimate of the year, and the millis value that // represents the start of that year. Then verify estimate and fix if // necessary. // Initial estimate uses values divided by two to avoid overflow. long unitMillis = getAverageMillisPerYearDividedByTwo(); long i2 = (instant >> 1) + getApproxMillisAtEpochDividedByTwo(); if (i2 < 0) { i2 = i2 - unitMillis + 1; } int year = (int) (i2 / unitMillis); long yearStart = getYearMillis(year); long diff = instant - yearStart; if (diff < 0) { year--; } else if (diff >= DateTimeConstants.MILLIS_PER_DAY * 365L) { // One year may need to be added to fix estimate. long oneYear; if (isLeapYear(year)) { oneYear = DateTimeConstants.MILLIS_PER_DAY * 366L; } else { oneYear = DateTimeConstants.MILLIS_PER_DAY * 365L; } yearStart += oneYear; if (yearStart <= instant) { // Didn't go too far, so actually add one year. year++; } } return year; } /** * @param millis from 1970-01-01T00:00:00Z */ int getMonthOfYear(long millis) { return getMonthOfYear(millis, getYear(millis)); } /** * @param millis from 1970-01-01T00:00:00Z * @param year precalculated year of millis */ abstract int getMonthOfYear(long millis, int year); /** * @param millis from 1970-01-01T00:00:00Z */ int getDayOfMonth(long millis) { int year = getYear(millis); int month = getMonthOfYear(millis, year); return getDayOfMonth(millis, year, month); } /** * @param millis from 1970-01-01T00:00:00Z * @param year precalculated year of millis */ int getDayOfMonth(long millis, int year) { int month = getMonthOfYear(millis, year); return getDayOfMonth(millis, year, month); } /** * @param millis from 1970-01-01T00:00:00Z * @param year precalculated year of millis * @param month precalculated month of millis */ int getDayOfMonth(long millis, int year, int month) { long dateMillis = getYearMillis(year); dateMillis += getTotalMillisByYearMonth(year, month); return (int) ((millis - dateMillis) / DateTimeConstants.MILLIS_PER_DAY) + 1; } /** * @param instant millis from 1970-01-01T00:00:00Z */ int getDayOfYear(long instant) { return getDayOfYear(instant, getYear(instant)); } /** * @param instant millis from 1970-01-01T00:00:00Z * @param year precalculated year of millis */ int getDayOfYear(long instant, int year) { long yearStart = getYearMillis(year); return (int) ((instant - yearStart) / DateTimeConstants.MILLIS_PER_DAY) + 1; } /** * @param instant millis from 1970-01-01T00:00:00Z */ int getWeekyear(long instant) { int year = getYear(instant); int week = getWeekOfWeekyear(instant, year); if (week == 1) { return getYear(instant + DateTimeConstants.MILLIS_PER_WEEK); } else if (week > 51) { return getYear(instant - (2 * DateTimeConstants.MILLIS_PER_WEEK)); } else { return year; } } /** * @param instant millis from 1970-01-01T00:00:00Z */ int getWeekOfWeekyear(long instant) { return getWeekOfWeekyear(instant, getYear(instant)); } /** * @param instant millis from 1970-01-01T00:00:00Z * @param year precalculated year of millis */ int getWeekOfWeekyear(long instant, int year) { long firstWeekMillis1 = getFirstWeekOfYearMillis(year); if (instant < firstWeekMillis1) { return getWeeksInYear(year - 1); } long firstWeekMillis2 = getFirstWeekOfYearMillis(year + 1); if (instant >= firstWeekMillis2) { return 1; } return (int) ((instant - firstWeekMillis1) / DateTimeConstants.MILLIS_PER_WEEK) + 1; } /** * @param instant millis from 1970-01-01T00:00:00Z */ int getDayOfWeek(long instant) { // 1970-01-01 is day of week 4, Thursday. long daysSince19700101; if (instant >= 0) { daysSince19700101 = instant / DateTimeConstants.MILLIS_PER_DAY; } else { daysSince19700101 = (instant - (DateTimeConstants.MILLIS_PER_DAY - 1)) / DateTimeConstants.MILLIS_PER_DAY; if (daysSince19700101 < -3) { return 7 + (int) ((daysSince19700101 + 4) % 7); } } return 1 + (int) ((daysSince19700101 + 3) % 7); } /** * @param instant millis from 1970-01-01T00:00:00Z */ int getMillisOfDay(long instant) { if (instant >= 0) { return (int) (instant % DateTimeConstants.MILLIS_PER_DAY); } else { return (DateTimeConstants.MILLIS_PER_DAY - 1) + (int) ((instant + 1) % DateTimeConstants.MILLIS_PER_DAY); } } /** * Gets the maximum number of days in any month. * * @return 31 */ int getDaysInMonthMax() { return 31; } /** * Gets the maximum number of days in the month specified by the instant. * * @param instant millis from 1970-01-01T00:00:00Z * @return the maximum number of days in the month */ int getDaysInMonthMax(long instant) { int thisYear = getYear(instant); int thisMonth = getMonthOfYear(instant, thisYear); return getDaysInYearMonth(thisYear, thisMonth); } /** * Gets the maximum number of days in the month specified by the instant. * The value represents what the user is trying to set, and can be * used to optimise this method. * * @param instant millis from 1970-01-01T00:00:00Z * @param value the value being set * @return the maximum number of days in the month */ int getDaysInMonthMaxForSet(long instant, int value) { return getDaysInMonthMax(instant); } //----------------------------------------------------------------------- /** * Gets the milliseconds for a date at midnight. * * @param year the year * @param monthOfYear the month * @param dayOfMonth the day * @return the milliseconds */ long getDateMidnightMillis(int year, int monthOfYear, int dayOfMonth) { FieldUtils.verifyValueBounds(DateTimeFieldType.year(), year, getMinYear(), getMaxYear()); FieldUtils.verifyValueBounds(DateTimeFieldType.monthOfYear(), monthOfYear, 1, getMaxMonth(year)); FieldUtils.verifyValueBounds(DateTimeFieldType.dayOfMonth(), dayOfMonth, 1, getDaysInYearMonth(year, monthOfYear)); return getYearMonthDayMillis(year, monthOfYear, dayOfMonth); } /** * Gets the difference between the two instants in years. * * @param minuendInstant the first instant * @param subtrahendInstant the second instant * @return the difference */ abstract long getYearDifference(long minuendInstant, long subtrahendInstant); /** * Is the specified year a leap year? * * @param year the year to test * @return true if leap */ abstract boolean isLeapYear(int year); /** * Gets the number of days in the specified month and year. * * @param year the year * @param month the month * @return the number of days */ abstract int getDaysInYearMonth(int year, int month); /** * Gets the maximum days in the specified month. * * @param month the month * @return the max days */ abstract int getDaysInMonthMax(int month); /** * Gets the total number of millis elapsed in this year at the start * of the specified month, such as zero for month 1. * * @param year the year * @param month the month * @return the elapsed millis at the start of the month */ abstract long getTotalMillisByYearMonth(int year, int month); /** * Gets the millisecond value of the first day of the year. * * @return the milliseconds for the first of the year */ abstract long calculateFirstDayOfYearMillis(int year); /** * Gets the minimum supported year. * * @return the year */ abstract int getMinYear(); /** * Gets the maximum supported year. * * @return the year */ abstract int getMaxYear(); /** * Gets the maximum month for the specified year. * This implementation calls getMaxMonth(). * * @param year the year * @return the maximum month value */ int getMaxMonth(int year) { return getMaxMonth(); } /** * Gets the maximum number of months. * * @return 12 */ int getMaxMonth() { return 12; } /** * Gets an average value for the milliseconds per year. * * @return the millis per year */ abstract long getAverageMillisPerYear(); /** * Gets an average value for the milliseconds per year, divided by two. * * @return the millis per year divided by two */ abstract long getAverageMillisPerYearDividedByTwo(); /** * Gets an average value for the milliseconds per month. * * @return the millis per month */ abstract long getAverageMillisPerMonth(); /** * Returns a constant representing the approximate number of milliseconds * elapsed from year 0 of this chronology, divided by two. This constant * must be defined as: *

     *    (yearAtEpoch * averageMillisPerYear + millisOfYearAtEpoch) / 2
     * 
* where epoch is 1970-01-01 (Gregorian). */ abstract long getApproxMillisAtEpochDividedByTwo(); /** * Sets the year from an instant and year. * * @param instant millis from 1970-01-01T00:00:00Z * @param year the year to set * @return the updated millis */ abstract long setYear(long instant, int year); //----------------------------------------------------------------------- // Although accessed by multiple threads, this method doesn't need to be synchronized. private YearInfo getYearInfo(int year) { YearInfo info = iYearInfoCache[year & CACHE_MASK]; if (info == null || info.iYear != year) { info = new YearInfo(year, calculateFirstDayOfYearMillis(year)); iYearInfoCache[year & CACHE_MASK] = info; } return info; } private static class HalfdayField extends PreciseDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = 581601443656929254L; HalfdayField() { super(DateTimeFieldType.halfdayOfDay(), cHalfdaysField, cDaysField); } public String getAsText(int fieldValue, Locale locale) { return GJLocaleSymbols.forLocale(locale).halfdayValueToText(fieldValue); } public long set(long millis, String text, Locale locale) { return set(millis, GJLocaleSymbols.forLocale(locale).halfdayTextToValue(text)); } public int getMaximumTextLength(Locale locale) { return GJLocaleSymbols.forLocale(locale).getHalfdayMaxTextLength(); } } private static class YearInfo { public final int iYear; public final long iFirstDayMillis; YearInfo(int year, long firstDayMillis) { iYear = year; iFirstDayMillis = firstDayMillis; } } } joda-time-2.3/src/main/java/org/joda/time/chrono/EthiopicChronology.java0000644000175000017500000002305011564251363025626 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.field.SkipDateTimeField; /** * Implements the Ethiopic calendar system, which defines every fourth year as * leap, much like the Julian calendar. The year is broken down into 12 months, * each 30 days in length. An extra period at the end of the year is either 5 * or 6 days in length. In this implementation, it is considered a 13th month. *

* Year 1 in the Ethiopic calendar began on August 29, 8 CE (Julian), thus * Ethiopic years do not begin at the same time as Julian years. This chronology * is not proleptic, as it does not allow dates before the first Ethiopic year. *

* This implementation defines a day as midnight to midnight exactly as per * the ISO chronology. Some references indicate that a coptic day starts at * sunset on the previous ISO day, but this has not been confirmed and is not * implemented. *

* EthiopicChronology is thread-safe and immutable. * * @see Wikipedia * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.2 */ public final class EthiopicChronology extends BasicFixedMonthChronology { /** Serialization lock */ private static final long serialVersionUID = -5972804258688333942L; /** * Constant value for 'Ethiopean Era', equivalent * to the value returned for AD/CE. */ public static final int EE = DateTimeConstants.CE; /** A singleton era field. */ private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("EE"); /** The lowest year that can be fully supported. */ private static final int MIN_YEAR = -292269337; /** The highest year that can be fully supported. */ private static final int MAX_YEAR = 292272984; /** Cache of zone to chronology arrays */ private static final Map cCache = new HashMap(); /** Singleton instance of a UTC EthiopicChronology */ private static final EthiopicChronology INSTANCE_UTC; static { // init after static fields INSTANCE_UTC = getInstance(DateTimeZone.UTC); } //----------------------------------------------------------------------- /** * Gets an instance of the EthiopicChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ public static EthiopicChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the EthiopicChronology in the default time zone. * * @return a chronology in the default time zone */ public static EthiopicChronology getInstance() { return getInstance(DateTimeZone.getDefault(), 4); } /** * Gets an instance of the EthiopicChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @return a chronology in the specified time zone */ public static EthiopicChronology getInstance(DateTimeZone zone) { return getInstance(zone, 4); } /** * Gets an instance of the EthiopicChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 * @return a chronology in the specified time zone */ public static EthiopicChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { if (zone == null) { zone = DateTimeZone.getDefault(); } EthiopicChronology chrono; synchronized (cCache) { EthiopicChronology[] chronos = cCache.get(zone); if (chronos == null) { chronos = new EthiopicChronology[7]; cCache.put(zone, chronos); } try { chrono = chronos[minDaysInFirstWeek - 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException ("Invalid min days in first week: " + minDaysInFirstWeek); } if (chrono == null) { if (zone == DateTimeZone.UTC) { // First create without a lower limit. chrono = new EthiopicChronology(null, null, minDaysInFirstWeek); // Impose lower limit and make another EthiopicChronology. DateTime lowerLimit = new DateTime(1, 1, 1, 0, 0, 0, 0, chrono); chrono = new EthiopicChronology (LimitChronology.getInstance(chrono, lowerLimit, null), null, minDaysInFirstWeek); } else { chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); chrono = new EthiopicChronology (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); } chronos[minDaysInFirstWeek - 1] = chrono; } } return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor. */ EthiopicChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } /** * Serialization singleton. */ private Object readResolve() { Chronology base = getBase(); return base == null ? getInstance(DateTimeZone.UTC, getMinimumDaysInFirstWeek()) : getInstance(base.getZone(), getMinimumDaysInFirstWeek()); } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } //----------------------------------------------------------------------- long calculateFirstDayOfYearMillis(int year) { // Java epoch is 1970-01-01 Gregorian which is 1962-04-23 Ethiopic. // Calculate relative to the nearest leap year and account for the // difference later. int relativeYear = year - 1963; int leapYears; if (relativeYear <= 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. leapYears = (relativeYear + 3) >> 2; } else { leapYears = relativeYear >> 2; // For post 1963 an adjustment is needed as jan1st is before leap day if (!isLeapYear(year)) { leapYears++; } } long millis = (relativeYear * 365L + leapYears) * (long)DateTimeConstants.MILLIS_PER_DAY; // Adjust to account for difference between 1963-01-01 and 1962-04-23. return millis + (365L - 112) * DateTimeConstants.MILLIS_PER_DAY; } //----------------------------------------------------------------------- int getMinYear() { return MIN_YEAR; } //----------------------------------------------------------------------- int getMaxYear() { return MAX_YEAR; } //----------------------------------------------------------------------- long getApproxMillisAtEpochDividedByTwo() { return (1962L * MILLIS_PER_YEAR + 112L * DateTimeConstants.MILLIS_PER_DAY) / 2; } //----------------------------------------------------------------------- protected void assemble(Fields fields) { if (getBase() == null) { super.assemble(fields); // Ethiopic, like Julian, has no year zero. fields.year = new SkipDateTimeField(this, fields.year); fields.weekyear = new SkipDateTimeField(this, fields.weekyear); fields.era = ERA_FIELD; fields.monthOfYear = new BasicMonthOfYearDateTimeField(this, 13); fields.months = fields.monthOfYear.getDurationField(); } } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicSingleEraDateTimeField.java0000644000175000017500000000710211564251363027212 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.DurationFieldType; import org.joda.time.IllegalFieldValueException; import org.joda.time.field.BaseDateTimeField; import org.joda.time.field.FieldUtils; import org.joda.time.field.UnsupportedDurationField; /** * Provides time calculations for the coptic era component of time. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.2, refactored from CopticEraDateTimeField */ final class BasicSingleEraDateTimeField extends BaseDateTimeField { /** * Value of the era, which will be the same as DateTimeConstants.CE. */ private static final int ERA_VALUE = DateTimeConstants.CE; /** * Text value of the era. */ private final String iEraText; /** * Restricted constructor. */ BasicSingleEraDateTimeField(String text) { super(DateTimeFieldType.era()); iEraText = text; } /** @inheritDoc */ public boolean isLenient() { return false; } /** @inheritDoc */ public int get(long instant) { return ERA_VALUE; } /** @inheritDoc */ public long set(long instant, int era) { FieldUtils.verifyValueBounds(this, era, ERA_VALUE, ERA_VALUE); return instant; } /** @inheritDoc */ public long set(long instant, String text, Locale locale) { if (iEraText.equals(text) == false && "1".equals(text) == false) { throw new IllegalFieldValueException(DateTimeFieldType.era(), text); } return instant; } /** @inheritDoc */ public long roundFloor(long instant) { return Long.MIN_VALUE; } /** @inheritDoc */ public long roundCeiling(long instant) { return Long.MAX_VALUE; } /** @inheritDoc */ public long roundHalfFloor(long instant) { return Long.MIN_VALUE; } /** @inheritDoc */ public long roundHalfCeiling(long instant) { return Long.MIN_VALUE; } /** @inheritDoc */ public long roundHalfEven(long instant) { return Long.MIN_VALUE; } /** @inheritDoc */ public DurationField getDurationField() { return UnsupportedDurationField.getInstance(DurationFieldType.eras()); } /** @inheritDoc */ public DurationField getRangeDurationField() { return null; } /** @inheritDoc */ public int getMinimumValue() { return ERA_VALUE; } /** @inheritDoc */ public int getMaximumValue() { return ERA_VALUE; } /** @inheritDoc */ public String getAsText(int fieldValue, Locale locale) { return iEraText; } /** @inheritDoc */ public int getMaximumTextLength(Locale locale) { return iEraText.length(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicDayOfYearDateTimeField.java0000644000175000017500000000641612203434647027172 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.ReadablePartial; import org.joda.time.field.PreciseDurationDateTimeField; /** * Provides time calculations for the day of the year component of time. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.1, refactored from GJDayOfYearDateTimeField */ final class BasicDayOfYearDateTimeField extends PreciseDurationDateTimeField { @SuppressWarnings("unused") private static final long serialVersionUID = -6821236822336841037L; private final BasicChronology iChronology; /** * Restricted constructor */ BasicDayOfYearDateTimeField(BasicChronology chronology, DurationField days) { super(DateTimeFieldType.dayOfYear(), days); iChronology = chronology; } /** * Get the day of the year component of the specified time instant. * * @param instant the time instant in millis to query. * @return the day of the year extracted from the input. */ public int get(long instant) { return iChronology.getDayOfYear(instant); } public DurationField getRangeDurationField() { return iChronology.years(); } public int getMinimumValue() { return 1; } public int getMaximumValue() { return iChronology.getDaysInYearMax(); } public int getMaximumValue(long instant) { int year = iChronology.getYear(instant); return iChronology.getDaysInYear(year); } public int getMaximumValue(ReadablePartial partial) { if (partial.isSupported(DateTimeFieldType.year())) { int year = partial.get(DateTimeFieldType.year()); return iChronology.getDaysInYear(year); } return iChronology.getDaysInYearMax(); } public int getMaximumValue(ReadablePartial partial, int[] values) { int size = partial.size(); for (int i = 0; i < size; i++) { if (partial.getFieldType(i) == DateTimeFieldType.year()) { int year = values[i]; return iChronology.getDaysInYear(year); } } return iChronology.getDaysInYearMax(); } protected int getMaximumValueForSet(long instant, int value) { int maxLessOne = iChronology.getDaysInYearMax() - 1; return (value > maxLessOne || value < 1) ? getMaximumValue(instant) : maxLessOne; } /** * Serialization singleton */ private Object readResolve() { return iChronology.dayOfYear(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/GJMonthOfYearDateTimeField.java0000644000175000017500000000455512203435045027014 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.Locale; /** * Provides time calculations for the month of the year component of time. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ final class GJMonthOfYearDateTimeField extends BasicMonthOfYearDateTimeField { /** Serialization version */ @SuppressWarnings("unused") private static final long serialVersionUID = -4748157875845286249L; /** * Restricted constructor */ GJMonthOfYearDateTimeField(BasicChronology chronology) { super(chronology, 2); } //----------------------------------------------------------------------- public String getAsText(int fieldValue, Locale locale) { return GJLocaleSymbols.forLocale(locale).monthOfYearValueToText(fieldValue); } //----------------------------------------------------------------------- public String getAsShortText(int fieldValue, Locale locale) { return GJLocaleSymbols.forLocale(locale).monthOfYearValueToShortText(fieldValue); } //----------------------------------------------------------------------- protected int convertText(String text, Locale locale) { return GJLocaleSymbols.forLocale(locale).monthOfYearTextToValue(text); } //----------------------------------------------------------------------- public int getMaximumTextLength(Locale locale) { return GJLocaleSymbols.forLocale(locale).getMonthMaxTextLength(); } //----------------------------------------------------------------------- public int getMaximumShortTextLength(Locale locale) { return GJLocaleSymbols.forLocale(locale).getMonthMaxShortTextLength(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicGJChronology.java0000644000175000017500000001736512055134304025327 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; /** * Abstract Chronology for implementing chronologies based on Gregorian/Julian formulae. * Most of the utility methods required by subclasses are package-private, * reflecting the intention that they be defined in the same package. *

* BasicGJChronology is thread-safe and immutable, and all subclasses must * be as well. * * @author Stephen Colebourne * @author Brian S O'Neill * @author Guy Allard * @since 1.2, refactored from CommonGJChronology */ abstract class BasicGJChronology extends BasicChronology { /** Serialization lock */ private static final long serialVersionUID = 538276888268L; // These arrays are NOT public. We trust ourselves not to alter the array. // They use zero-based array indexes so the that valid range of months is // automatically checked. private static final int[] MIN_DAYS_PER_MONTH_ARRAY = { 31,28,31,30,31,30,31,31,30,31,30,31 }; private static final int[] MAX_DAYS_PER_MONTH_ARRAY = { 31,29,31,30,31,30,31,31,30,31,30,31 }; private static final long[] MIN_TOTAL_MILLIS_BY_MONTH_ARRAY; private static final long[] MAX_TOTAL_MILLIS_BY_MONTH_ARRAY; private static final long FEB_29 = (31L + 29 - 1) * DateTimeConstants.MILLIS_PER_DAY; static { MIN_TOTAL_MILLIS_BY_MONTH_ARRAY = new long[12]; MAX_TOTAL_MILLIS_BY_MONTH_ARRAY = new long[12]; long minSum = 0; long maxSum = 0; for (int i = 0; i < 11; i++) { long millis = MIN_DAYS_PER_MONTH_ARRAY[i] * (long)DateTimeConstants.MILLIS_PER_DAY; minSum += millis; MIN_TOTAL_MILLIS_BY_MONTH_ARRAY[i + 1] = minSum; millis = MAX_DAYS_PER_MONTH_ARRAY[i] * (long)DateTimeConstants.MILLIS_PER_DAY; maxSum += millis; MAX_TOTAL_MILLIS_BY_MONTH_ARRAY[i + 1] = maxSum; } } /** * Constructor. */ BasicGJChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } //----------------------------------------------------------------------- int getMonthOfYear(long millis, int year) { // Perform a binary search to get the month. To make it go even faster, // compare using ints instead of longs. The number of milliseconds per // year exceeds the limit of a 32-bit int's capacity, so divide by // 1024. No precision is lost (except time of day) since the number of // milliseconds per day contains 1024 as a factor. After the division, // the instant isn't measured in milliseconds, but in units of // (128/125)seconds. int i = (int)((millis - getYearMillis(year)) >> 10); // There are 86400000 milliseconds per day, but divided by 1024 is // 84375. There are 84375 (128/125)seconds per day. return (isLeapYear(year)) ? ((i < 182 * 84375) ? ((i < 91 * 84375) ? ((i < 31 * 84375) ? 1 : (i < 60 * 84375) ? 2 : 3) : ((i < 121 * 84375) ? 4 : (i < 152 * 84375) ? 5 : 6)) : ((i < 274 * 84375) ? ((i < 213 * 84375) ? 7 : (i < 244 * 84375) ? 8 : 9) : ((i < 305 * 84375) ? 10 : (i < 335 * 84375) ? 11 : 12))) : ((i < 181 * 84375) ? ((i < 90 * 84375) ? ((i < 31 * 84375) ? 1 : (i < 59 * 84375) ? 2 : 3) : ((i < 120 * 84375) ? 4 : (i < 151 * 84375) ? 5 : 6)) : ((i < 273 * 84375) ? ((i < 212 * 84375) ? 7 : (i < 243 * 84375) ? 8 : 9) : ((i < 304 * 84375) ? 10 : (i < 334 * 84375) ? 11 : 12))); } //----------------------------------------------------------------------- /** * Gets the number of days in the specified month and year. * * @param year the year * @param month the month * @return the number of days */ int getDaysInYearMonth(int year, int month) { if (isLeapYear(year)) { return MAX_DAYS_PER_MONTH_ARRAY[month - 1]; } else { return MIN_DAYS_PER_MONTH_ARRAY[month - 1]; } } //----------------------------------------------------------------------- int getDaysInMonthMax(int month) { return MAX_DAYS_PER_MONTH_ARRAY[month - 1]; } //----------------------------------------------------------------------- int getDaysInMonthMaxForSet(long instant, int value) { return ((value > 28 || value < 1) ? getDaysInMonthMax(instant) : 28); } //----------------------------------------------------------------------- long getTotalMillisByYearMonth(int year, int month) { if (isLeapYear(year)) { return MAX_TOTAL_MILLIS_BY_MONTH_ARRAY[month - 1]; } else { return MIN_TOTAL_MILLIS_BY_MONTH_ARRAY[month - 1]; } } //----------------------------------------------------------------------- long getYearDifference(long minuendInstant, long subtrahendInstant) { int minuendYear = getYear(minuendInstant); int subtrahendYear = getYear(subtrahendInstant); // Inlined remainder method to avoid duplicate calls to get. long minuendRem = minuendInstant - getYearMillis(minuendYear); long subtrahendRem = subtrahendInstant - getYearMillis(subtrahendYear); // Balance leap year differences on remainders. if (subtrahendRem >= FEB_29) { if (isLeapYear(subtrahendYear)) { if (!isLeapYear(minuendYear)) { subtrahendRem -= DateTimeConstants.MILLIS_PER_DAY; } } else if (minuendRem >= FEB_29 && isLeapYear(minuendYear)) { minuendRem -= DateTimeConstants.MILLIS_PER_DAY; } } int difference = minuendYear - subtrahendYear; if (minuendRem < subtrahendRem) { difference--; } return difference; } //----------------------------------------------------------------------- long setYear(long instant, int year) { int thisYear = getYear(instant); int dayOfYear = getDayOfYear(instant, thisYear); int millisOfDay = getMillisOfDay(instant); if (dayOfYear > (31 + 28)) { // after Feb 28 if (isLeapYear(thisYear)) { // Current date is Feb 29 or later. if (!isLeapYear(year)) { // Moving to a non-leap year, Feb 29 does not exist. dayOfYear--; } } else { // Current date is Mar 01 or later. if (isLeapYear(year)) { // Moving to a leap year, account for Feb 29. dayOfYear++; } } } instant = getYearMonthDayMillis(year, 1, dayOfYear); instant += millisOfDay; return instant; } } joda-time-2.3/src/main/java/org/joda/time/chrono/BuddhistChronology.java0000644000175000017500000002135112200501234025611 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.field.DelegatedDateTimeField; import org.joda.time.field.DividedDateTimeField; import org.joda.time.field.OffsetDateTimeField; import org.joda.time.field.RemainderDateTimeField; import org.joda.time.field.SkipUndoDateTimeField; /** * A chronology that matches the BuddhistCalendar class supplied by Sun. *

* The chronology is identical to the Gregorian/Julian, except that the * year is offset by +543 and the era is named 'BE' for Buddhist Era. *

* This class was intended by Sun to model the calendar used in Thailand. * However, the actual rules for Thailand are much more involved than * this class covers. (This class is accurate after 1941-01-01 ISO). *

* This chronlogy is being retained for those who want a same effect * replacement for the Sun class. It is hoped that community support will * enable a more accurate chronology for Thailand, to be developed. *

* BuddhistChronology is thread-safe and immutable. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public final class BuddhistChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = -3474595157769370126L; /** * Constant value for 'Buddhist Era', equivalent to the value returned * for AD/CE. Note that this differs from the constant in BuddhistCalendar. */ public static final int BE = DateTimeConstants.CE; /** A singleton era field. */ private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("BE"); /** Number of years difference in calendars. */ private static final int BUDDHIST_OFFSET = 543; /** Cache of zone to chronology */ private static final Map cCache = new HashMap(); /** UTC instance of the chronology */ private static final BuddhistChronology INSTANCE_UTC = getInstance(DateTimeZone.UTC); /** * Standard instance of a Buddhist Chronology, that matches * Sun's BuddhistCalendar class. This means that it follows the * GregorianJulian calendar rules with a cutover date. *

* The time zone of the returned instance is UTC. */ public static BuddhistChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Standard instance of a Buddhist Chronology, that matches * Sun's BuddhistCalendar class. This means that it follows the * GregorianJulian calendar rules with a cutover date. */ public static BuddhistChronology getInstance() { return getInstance(DateTimeZone.getDefault()); } /** * Standard instance of a Buddhist Chronology, that matches * Sun's BuddhistCalendar class. This means that it follows the * GregorianJulian calendar rules with a cutover date. * * @param zone the time zone to use, null is default */ public static synchronized BuddhistChronology getInstance(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } BuddhistChronology chrono; synchronized (cCache) { chrono = cCache.get(zone); if (chrono == null) { // First create without a lower limit. chrono = new BuddhistChronology(GJChronology.getInstance(zone, null), null); // Impose lower limit and make another BuddhistChronology. DateTime lowerLimit = new DateTime(1, 1, 1, 0, 0, 0, 0, chrono); chrono = new BuddhistChronology(LimitChronology.getInstance(chrono, lowerLimit, null), ""); cCache.put(zone, chrono); } } return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor. * * @param param if non-null, then don't change the field set */ private BuddhistChronology(Chronology base, Object param) { super(base, param); } /** * Serialization singleton */ private Object readResolve() { Chronology base = getBase(); return base == null ? getInstanceUTC() : getInstance(base.getZone()); } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } //----------------------------------------------------------------------- /** * Checks if this chronology instance equals another. * * @param obj the object to compare to * @return true if equal * @since 1.6 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof BuddhistChronology) { BuddhistChronology chrono = (BuddhistChronology) obj; return getZone().equals(chrono.getZone()); } return false; } /** * A suitable hash code for the chronology. * * @return the hash code * @since 1.6 */ public int hashCode() { return "Buddhist".hashCode() * 11 + getZone().hashCode(); } // Output //----------------------------------------------------------------------- /** * Gets a debugging toString. * * @return a debugging string */ public String toString() { String str = "BuddhistChronology"; DateTimeZone zone = getZone(); if (zone != null) { str = str + '[' + zone.getID() + ']'; } return str; } protected void assemble(Fields fields) { if (getParam() == null) { // julian chrono removed zero, but we need to put it back DateTimeField field = fields.year; fields.year = new OffsetDateTimeField( new SkipUndoDateTimeField(this, field), BUDDHIST_OFFSET); // one era, so yearOfEra is the same field = fields.yearOfEra; fields.yearOfEra = new DelegatedDateTimeField( fields.year, DateTimeFieldType.yearOfEra()); // julian chrono removed zero, but we need to put it back field = fields.weekyear; fields.weekyear = new OffsetDateTimeField( new SkipUndoDateTimeField(this, field), BUDDHIST_OFFSET); field = new OffsetDateTimeField(fields.yearOfEra, 99); fields.centuryOfEra = new DividedDateTimeField( field, DateTimeFieldType.centuryOfEra(), 100); field = new RemainderDateTimeField( (DividedDateTimeField) fields.centuryOfEra); fields.yearOfCentury = new OffsetDateTimeField( field, DateTimeFieldType.yearOfCentury(), 1); field = new RemainderDateTimeField( fields.weekyear, DateTimeFieldType.weekyearOfCentury(), 100); fields.weekyearOfCentury = new OffsetDateTimeField( field, DateTimeFieldType.weekyearOfCentury(), 1); fields.era = ERA_FIELD; } } } joda-time-2.3/src/main/java/org/joda/time/chrono/LenientChronology.java0000644000175000017500000001236611564251363025470 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.Chronology; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.field.LenientDateTimeField; /** * Wraps another Chronology, ensuring all the fields are lenient. *

* LenientChronology is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 * @see LenientDateTimeField * @see StrictChronology */ public final class LenientChronology extends AssembledChronology { /** Serialization lock */ private static final long serialVersionUID = -3148237568046877177L; /** * Create a LenientChronology for any chronology. * * @param base the chronology to wrap * @throws IllegalArgumentException if chronology is null */ public static LenientChronology getInstance(Chronology base) { if (base == null) { throw new IllegalArgumentException("Must supply a chronology"); } return new LenientChronology(base); } private transient Chronology iWithUTC; /** * Create a LenientChronology for any chronology. * * @param base the chronology to wrap */ private LenientChronology(Chronology base) { super(base, null); } public Chronology withUTC() { if (iWithUTC == null) { if (getZone() == DateTimeZone.UTC) { iWithUTC = this; } else { iWithUTC = LenientChronology.getInstance(getBase().withUTC()); } } return iWithUTC; } public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == DateTimeZone.UTC) { return withUTC(); } if (zone == getZone()) { return this; } return LenientChronology.getInstance(getBase().withZone(zone)); } protected void assemble(Fields fields) { fields.year = convertField(fields.year); fields.yearOfEra = convertField(fields.yearOfEra); fields.yearOfCentury = convertField(fields.yearOfCentury); fields.centuryOfEra = convertField(fields.centuryOfEra); fields.era = convertField(fields.era); fields.dayOfWeek = convertField(fields.dayOfWeek); fields.dayOfMonth = convertField(fields.dayOfMonth); fields.dayOfYear = convertField(fields.dayOfYear); fields.monthOfYear = convertField(fields.monthOfYear); fields.weekOfWeekyear = convertField(fields.weekOfWeekyear); fields.weekyear = convertField(fields.weekyear); fields.weekyearOfCentury = convertField(fields.weekyearOfCentury); fields.millisOfSecond = convertField(fields.millisOfSecond); fields.millisOfDay = convertField(fields.millisOfDay); fields.secondOfMinute = convertField(fields.secondOfMinute); fields.secondOfDay = convertField(fields.secondOfDay); fields.minuteOfHour = convertField(fields.minuteOfHour); fields.minuteOfDay = convertField(fields.minuteOfDay); fields.hourOfDay = convertField(fields.hourOfDay); fields.hourOfHalfday = convertField(fields.hourOfHalfday); fields.clockhourOfDay = convertField(fields.clockhourOfDay); fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday); fields.halfdayOfDay = convertField(fields.halfdayOfDay); } private final DateTimeField convertField(DateTimeField field) { return LenientDateTimeField.getInstance(field, getBase()); } //----------------------------------------------------------------------- /** * A lenient chronology is only equal to a lenient chronology with the * same base chronology. * * @param obj the object to compare to * @return true if equal * @since 1.4 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof LenientChronology == false) { return false; } LenientChronology chrono = (LenientChronology) obj; return getBase().equals(chrono.getBase()); } /** * A suitable hashcode for the chronology. * * @return the hashcode * @since 1.4 */ public int hashCode() { return 236548278 + getBase().hashCode() * 7; } /** * A debugging string for the chronology. * * @return the debugging string */ public String toString() { return "LenientChronology[" + getBase().toString() + ']'; } } joda-time-2.3/src/main/java/org/joda/time/chrono/BasicYearDateTimeField.java0000644000175000017500000001055312203434762026242 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import org.joda.time.DateTimeFieldType; import org.joda.time.DurationField; import org.joda.time.field.FieldUtils; import org.joda.time.field.ImpreciseDateTimeField; /** * A year field suitable for many calendars. * * @author Guy Allard * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.1, refactored from GJYearDateTimeField */ class BasicYearDateTimeField extends ImpreciseDateTimeField { /** Serialization version. */ @SuppressWarnings("unused") private static final long serialVersionUID = -98628754872287L; /** The underlying basic chronology. */ protected final BasicChronology iChronology; /** * Restricted constructor. * * @param chronology the chronology this field belogs to */ BasicYearDateTimeField(BasicChronology chronology) { super(DateTimeFieldType.year(), chronology.getAverageMillisPerYear()); iChronology = chronology; } public boolean isLenient() { return false; } public int get(long instant) { return iChronology.getYear(instant); } public long add(long instant, int years) { if (years == 0) { return instant; } int thisYear = get(instant); int newYear = FieldUtils.safeAdd(thisYear, years); return set(instant, newYear); } public long add(long instant, long years) { return add(instant, FieldUtils.safeToInt(years)); } public long addWrapField(long instant, int years) { if (years == 0) { return instant; } // Return newly calculated millis value int thisYear = iChronology.getYear(instant); int wrappedYear = FieldUtils.getWrappedValue (thisYear, years, iChronology.getMinYear(), iChronology.getMaxYear()); return set(instant, wrappedYear); } public long set(long instant, int year) { FieldUtils.verifyValueBounds (this, year, iChronology.getMinYear(), iChronology.getMaxYear()); return iChronology.setYear(instant, year); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant < subtrahendInstant) { return -iChronology.getYearDifference(subtrahendInstant, minuendInstant); } return iChronology.getYearDifference(minuendInstant, subtrahendInstant); } public DurationField getRangeDurationField() { return null; } public boolean isLeap(long instant) { return iChronology.isLeapYear(get(instant)); } public int getLeapAmount(long instant) { if (iChronology.isLeapYear(get(instant))) { return 1; } else { return 0; } } public DurationField getLeapDurationField() { return iChronology.days(); } public int getMinimumValue() { return iChronology.getMinYear(); } public int getMaximumValue() { return iChronology.getMaxYear(); } public long roundFloor(long instant) { return iChronology.getYearMillis(get(instant)); } public long roundCeiling(long instant) { int year = get(instant); long yearStartMillis = iChronology.getYearMillis(year); if (instant != yearStartMillis) { // Bump up to start of next year. instant = iChronology.getYearMillis(year + 1); } return instant; } public long remainder(long instant) { return instant - roundFloor(instant); } /** * Serialization singleton */ private Object readResolve() { return iChronology.year(); } } joda-time-2.3/src/main/java/org/joda/time/chrono/package.html0000644000175000017500000000325411564251363023440 0ustar ebourgebourg org.joda.time.chrono package

Package containing the chronology classes which define the calendar systems.

This package contains all of the chronology implementations within the library. A chronology represents all the rules of a calendar system. Applications will create chronologies using the static factory methods on each specific Chronology class - getInstance. The currently provided chronology implementations are:

  • ISO
  • GJ (GregorianJulian)
  • Gregorian
  • Julian
  • Buddhist
  • Coptic
  • Ethiopic
  • Islamic

The package also contains all of the specialised field implementations. These classes are package scoped, along with various other chronology helper classes. The package scoped classes (which are not shown in the javadoc) do not form part of the public API of Joda-Time and may change at any time.

joda-time-2.3/src/main/java/org/joda/time/chrono/CopticChronology.java0000644000175000017500000002314511564251363025310 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.chrono; import java.util.HashMap; import java.util.Map; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.field.SkipDateTimeField; /** * Implements the Coptic calendar system, which defines every fourth year as * leap, much like the Julian calendar. The year is broken down into 12 months, * each 30 days in length. An extra period at the end of the year is either 5 * or 6 days in length. In this implementation, it is considered a 13th month. *

* Year 1 in the Coptic calendar began on August 29, 284 CE (Julian), thus * Coptic years do not begin at the same time as Julian years. This chronology * is not proleptic, as it does not allow dates before the first Coptic year. *

* This implementation defines a day as midnight to midnight exactly as per * the ISO chronology. Some references indicate that a coptic day starts at * sunset on the previous ISO day, but this has not been confirmed and is not * implemented. *

* CopticChronology is thread-safe and immutable. * * @see Wikipedia * @see JulianChronology * * @author Brian S O'Neill * @since 1.0 */ public final class CopticChronology extends BasicFixedMonthChronology { /** Serialization lock */ private static final long serialVersionUID = -5972804258688333942L; /** * Constant value for 'Anno Martyrum' or 'Era of the Martyrs', equivalent * to the value returned for AD/CE. */ public static final int AM = DateTimeConstants.CE; /** A singleton era field. */ private static final DateTimeField ERA_FIELD = new BasicSingleEraDateTimeField("AM"); /** The lowest year that can be fully supported. */ private static final int MIN_YEAR = -292269337; /** The highest year that can be fully supported. */ private static final int MAX_YEAR = 292272708; /** Cache of zone to chronology arrays */ private static final Map cCache = new HashMap(); /** Singleton instance of a UTC CopticChronology */ private static final CopticChronology INSTANCE_UTC; static { // init after static fields INSTANCE_UTC = getInstance(DateTimeZone.UTC); } //----------------------------------------------------------------------- /** * Gets an instance of the CopticChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ public static CopticChronology getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the CopticChronology in the default time zone. * * @return a chronology in the default time zone */ public static CopticChronology getInstance() { return getInstance(DateTimeZone.getDefault(), 4); } /** * Gets an instance of the CopticChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @return a chronology in the specified time zone */ public static CopticChronology getInstance(DateTimeZone zone) { return getInstance(zone, 4); } /** * Gets an instance of the CopticChronology in the given time zone. * * @param zone the time zone to get the chronology in, null is default * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 * @return a chronology in the specified time zone */ public static CopticChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { if (zone == null) { zone = DateTimeZone.getDefault(); } CopticChronology chrono; synchronized (cCache) { CopticChronology[] chronos = cCache.get(zone); if (chronos == null) { chronos = new CopticChronology[7]; cCache.put(zone, chronos); } try { chrono = chronos[minDaysInFirstWeek - 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException ("Invalid min days in first week: " + minDaysInFirstWeek); } if (chrono == null) { if (zone == DateTimeZone.UTC) { // First create without a lower limit. chrono = new CopticChronology(null, null, minDaysInFirstWeek); // Impose lower limit and make another CopticChronology. DateTime lowerLimit = new DateTime(1, 1, 1, 0, 0, 0, 0, chrono); chrono = new CopticChronology (LimitChronology.getInstance(chrono, lowerLimit, null), null, minDaysInFirstWeek); } else { chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); chrono = new CopticChronology (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); } chronos[minDaysInFirstWeek - 1] = chrono; } } return chrono; } // Constructors and instance variables //----------------------------------------------------------------------- /** * Restricted constructor. */ CopticChronology(Chronology base, Object param, int minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } /** * Serialization singleton. */ private Object readResolve() { Chronology base = getBase(); int minDays = getMinimumDaysInFirstWeek(); minDays = (minDays == 0 ? 4 : minDays); // handle rename of BaseGJChronology return base == null ? getInstance(DateTimeZone.UTC, minDays) : getInstance(base.getZone(), minDays); } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return INSTANCE_UTC; } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } //----------------------------------------------------------------------- long calculateFirstDayOfYearMillis(int year) { // Java epoch is 1970-01-01 Gregorian which is 1686-04-23 Coptic. // Calculate relative to the nearest leap year and account for the // difference later. int relativeYear = year - 1687; int leapYears; if (relativeYear <= 0) { // Add 3 before shifting right since /4 and >>2 behave differently // on negative numbers. leapYears = (relativeYear + 3) >> 2; } else { leapYears = relativeYear >> 2; // For post 1687 an adjustment is needed as jan1st is before leap day if (!isLeapYear(year)) { leapYears++; } } long millis = (relativeYear * 365L + leapYears) * (long)DateTimeConstants.MILLIS_PER_DAY; // Adjust to account for difference between 1687-01-01 and 1686-04-23. return millis + (365L - 112) * DateTimeConstants.MILLIS_PER_DAY; } //----------------------------------------------------------------------- int getMinYear() { return MIN_YEAR; } //----------------------------------------------------------------------- int getMaxYear() { return MAX_YEAR; } //----------------------------------------------------------------------- long getApproxMillisAtEpochDividedByTwo() { return (1686L * MILLIS_PER_YEAR + 112L * DateTimeConstants.MILLIS_PER_DAY) / 2; } //----------------------------------------------------------------------- protected void assemble(Fields fields) { if (getBase() == null) { super.assemble(fields); // Coptic, like Julian, has no year zero. fields.year = new SkipDateTimeField(this, fields.year); fields.weekyear = new SkipDateTimeField(this, fields.weekyear); fields.era = ERA_FIELD; fields.monthOfYear = new BasicMonthOfYearDateTimeField(this, 13); fields.months = fields.monthOfYear.getDurationField(); } } } joda-time-2.3/src/main/java/org/joda/time/convert/0000755000175000017500000000000012205344143021333 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/convert/StringConverter.java0000644000175000017500000002356612203434112025342 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.ReadWritableInterval; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadablePartial; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * StringConverter converts from a String to an instant, partial, * duration, period or interval.. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ class StringConverter extends AbstractConverter implements InstantConverter, PartialConverter, DurationConverter, PeriodConverter, IntervalConverter { /** * Singleton instance. */ static final StringConverter INSTANCE = new StringConverter(); /** * Restricted constructor. */ protected StringConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the millis, which is the ISO parsed string value. * * @param object the String to convert, must not be null * @param chrono the chronology to use, non-null result of getChronology * @return the millisecond value * @throws IllegalArgumentException if the value if invalid */ public long getInstantMillis(Object object, Chronology chrono) { String str = (String) object; DateTimeFormatter p = ISODateTimeFormat.dateTimeParser(); return p.withChronology(chrono).parseMillis(str); } /** * Extracts the values of the partial from an object of this converter's type. * This method checks if the parser has a zone, and uses it if present. * This is most useful for parsing local times with UTC. * * @param fieldSource a partial that provides access to the fields. * This partial may be incomplete and only getFieldType(int) should be used * @param object the object to convert * @param chrono the chronology to use, which is the non-null result of getChronology() * @param parser the parser to use, may be null * @return the array of field values that match the fieldSource, must be non-null valid * @throws ClassCastException if the object is invalid * @throws IllegalArgumentException if the value if invalid * @since 1.3 */ public int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono, DateTimeFormatter parser) { if (parser.getZone() != null) { chrono = chrono.withZone(parser.getZone()); } long millis = parser.withChronology(chrono).parseMillis((String) object); return chrono.get(fieldSource, millis); } //----------------------------------------------------------------------- /** * Gets the duration of the string using the standard type. * This matches the toString() method of ReadableDuration. * * @param object the String to convert, must not be null * @throws ClassCastException if the object is invalid */ public long getDurationMillis(Object object) { // parse here because duration could be bigger than the int supported // by the period parser String original = (String) object; String str = original; int len = str.length(); if (len >= 4 && (str.charAt(0) == 'P' || str.charAt(0) == 'p') && (str.charAt(1) == 'T' || str.charAt(1) == 't') && (str.charAt(len - 1) == 'S' || str.charAt(len - 1) == 's')) { // ok } else { throw new IllegalArgumentException("Invalid format: \"" + original + '"'); } str = str.substring(2, len - 1); int dot = -1; boolean negative = false; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { // ok } else if (i == 0 && str.charAt(0) == '-') { // ok negative = true; } else if (i > (negative ? 1 : 0) && str.charAt(i) == '.' && dot == -1) { // ok dot = i; } else { throw new IllegalArgumentException("Invalid format: \"" + original + '"'); } } long millis = 0, seconds = 0; int firstDigit = negative ? 1 : 0; if (dot > 0) { seconds = Long.parseLong(str.substring(firstDigit, dot)); str = str.substring(dot + 1); if (str.length() != 3) { str = (str + "000").substring(0, 3); } millis = Integer.parseInt(str); } else if (negative) { seconds = Long.parseLong(str.substring(firstDigit, str.length())); } else { seconds = Long.parseLong(str); } if (negative) { return FieldUtils.safeAdd(FieldUtils.safeMultiply(-seconds, 1000), -millis); } else { return FieldUtils.safeAdd(FieldUtils.safeMultiply(seconds, 1000), millis); } } //----------------------------------------------------------------------- /** * Extracts duration values from an object of this converter's type, and * sets them into the given ReadWritableDuration. * * @param period period to get modified * @param object the String to convert, must not be null * @param chrono the chronology to use * @return the millisecond duration * @throws ClassCastException if the object is invalid */ public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) { String str = (String) object; PeriodFormatter parser = ISOPeriodFormat.standard(); period.clear(); int pos = parser.parseInto(period, str, 0); if (pos < str.length()) { if (pos < 0) { // Parse again to get a better exception thrown. parser.withParseType(period.getPeriodType()).parseMutablePeriod(str); } throw new IllegalArgumentException("Invalid format: \"" + str + '"'); } } //----------------------------------------------------------------------- /** * Sets the value of the mutable interval from the string. * * @param writableInterval the interval to set * @param object the String to convert, must not be null * @param chrono the chronology to use, may be null */ public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) { String str = (String) object; int separator = str.indexOf('/'); if (separator < 0) { throw new IllegalArgumentException("Format requires a '/' separator: " + str); } String leftStr = str.substring(0, separator); if (leftStr.length() <= 0) { throw new IllegalArgumentException("Format invalid: " + str); } String rightStr = str.substring(separator + 1); if (rightStr.length() <= 0) { throw new IllegalArgumentException("Format invalid: " + str); } DateTimeFormatter dateTimeParser = ISODateTimeFormat.dateTimeParser(); dateTimeParser = dateTimeParser.withChronology(chrono); PeriodFormatter periodParser = ISOPeriodFormat.standard(); long startInstant = 0, endInstant = 0; Period period = null; Chronology parsedChrono = null; // before slash char c = leftStr.charAt(0); if (c == 'P' || c == 'p') { period = periodParser.withParseType(getPeriodType(leftStr)).parsePeriod(leftStr); } else { DateTime start = dateTimeParser.parseDateTime(leftStr); startInstant = start.getMillis(); parsedChrono = start.getChronology(); } // after slash c = rightStr.charAt(0); if (c == 'P' || c == 'p') { if (period != null) { throw new IllegalArgumentException("Interval composed of two durations: " + str); } period = periodParser.withParseType(getPeriodType(rightStr)).parsePeriod(rightStr); chrono = (chrono != null ? chrono : parsedChrono); endInstant = chrono.add(period, startInstant, 1); } else { DateTime end = dateTimeParser.parseDateTime(rightStr); endInstant = end.getMillis(); parsedChrono = (parsedChrono != null ? parsedChrono : end.getChronology()); chrono = (chrono != null ? chrono : parsedChrono); if (period != null) { startInstant = chrono.add(period, endInstant, -1); } } writableInterval.setInterval(startInstant, endInstant); writableInterval.setChronology(chrono); } //----------------------------------------------------------------------- /** * Returns String.class. * * @return String.class */ public Class getSupportedType() { return String.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/DateConverter.java0000644000175000017500000000406011564251363024753 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.util.Date; import org.joda.time.Chronology; /** * DateConverter converts a java util Date to an instant or partial. * The Date is converted to milliseconds in the ISO chronology. * * @author Stephen Colebourne * @since 1.0 */ final class DateConverter extends AbstractConverter implements InstantConverter, PartialConverter { /** * Singleton instance. */ static final DateConverter INSTANCE = new DateConverter(); /** * Restricted constructor. */ protected DateConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the millis, which is the Date millis value. * * @param object the Date to convert, must not be null * @param chrono the non-null result of getChronology * @return the millisecond value * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public long getInstantMillis(Object object, Chronology chrono) { Date date = (Date) object; return date.getTime(); } //----------------------------------------------------------------------- /** * Returns Date.class. * * @return Date.class */ public Class getSupportedType() { return Date.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/ReadableDurationConverter.java0000644000175000017500000000634711564251363027315 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadableDuration; /** * ReadableDurationConverter extracts milliseconds and chronology from a ReadableDuration. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ class ReadableDurationConverter extends AbstractConverter implements DurationConverter, PeriodConverter { /** * Singleton instance. */ static final ReadableDurationConverter INSTANCE = new ReadableDurationConverter(); /** * Restricted constructor. */ protected ReadableDurationConverter() { super(); } //----------------------------------------------------------------------- /** * Extracts the millis from an object of this convertor's type. * * @param object the object to convert, must not be null * @return the millisecond value * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type * @throws IllegalArgumentException if the object is invalid */ public long getDurationMillis(Object object) { return ((ReadableDuration) object).getMillis(); } //----------------------------------------------------------------------- /** * Extracts duration values from an object of this converter's type, and * sets them into the given ReadWritableDuration. * * @param writablePeriod period to get modified * @param object the object to convert, must not be null * @param chrono the chronology to use, must not be null * @throws NullPointerException if the duration or object is null * @throws ClassCastException if the object is an invalid type * @throws IllegalArgumentException if the object is invalid */ public void setInto(ReadWritablePeriod writablePeriod, Object object, Chronology chrono) { ReadableDuration dur = (ReadableDuration) object; chrono = DateTimeUtils.getChronology(chrono); long duration = dur.getMillis(); int[] values = chrono.get(writablePeriod, duration); for (int i = 0; i < values.length; i++) { writablePeriod.setValue(i, values[i]); } } //----------------------------------------------------------------------- /** * Returns ReadableDuration.class. * * @return ReadableDuration.class */ public Class getSupportedType() { return ReadableDuration.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/ReadablePeriodConverter.java0000644000175000017500000000545611564251363026752 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.PeriodType; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadablePeriod; /** * ReadablePeriodConverter extracts milliseconds and chronology from a ReadablePeriod. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ class ReadablePeriodConverter extends AbstractConverter implements PeriodConverter { /** * Singleton instance. */ static final ReadablePeriodConverter INSTANCE = new ReadablePeriodConverter(); /** * Restricted constructor. */ protected ReadablePeriodConverter() { super(); } //----------------------------------------------------------------------- /** * Extracts duration values from an object of this converter's type, and * sets them into the given ReadWritablePeriod. * * @param duration duration to get modified * @param object the object to convert, must not be null * @param chrono the chronology to use * @throws NullPointerException if the duration or object is null * @throws ClassCastException if the object is an invalid type * @throws IllegalArgumentException if the object is invalid */ public void setInto(ReadWritablePeriod duration, Object object, Chronology chrono) { duration.setPeriod((ReadablePeriod) object); } /** * Selects a suitable period type for the given object. * * @param object the object to examine, must not be null * @return the period type from the readable duration * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public PeriodType getPeriodType(Object object) { ReadablePeriod period = (ReadablePeriod) object; return period.getPeriodType(); } //----------------------------------------------------------------------- /** * Returns ReadablePeriod class. * * @return ReadablePeriod.class */ public Class getSupportedType() { return ReadablePeriod.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/Converter.java0000644000175000017500000000213011564251363024151 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; /** * Basic converter interface for specifying what object type can be converted. * * @author Brian S O'Neill * @since 1.0 */ public interface Converter { /** * Returns the object type that this converter supports, which may * specified by a class, superclass, abstract class, interface, or null. * * @return the object type that this converter supports */ Class getSupportedType(); } joda-time-2.3/src/main/java/org/joda/time/convert/InstantConverter.java0000644000175000017500000000541611564251363025524 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; /** * InstantConverter defines how an object is converted to milliseconds/chronology. *

* The two methods in this interface must be called in order, as the * getInstantMillis method relies on the result of the * getChronology method being passed in. * * @author Stephen Colebourne * @since 1.0 */ public interface InstantConverter extends Converter { /** * Extracts the chronology from an object of this converter's type * where the time zone is specified. * * @param object the object to convert * @param zone the specified zone to use, null means default zone * @return the chronology, never null * @throws ClassCastException if the object is invalid */ Chronology getChronology(Object object, DateTimeZone zone); /** * Extracts the chronology from an object of this converter's type * where the chronology may be specified. *

* If the chronology is non-null it should be used. If it is null, then the * object should be queried, and if it has no chronology then ISO default is used. * * @param object the object to convert * @param chrono the chronology to use, null means use object * @return the chronology, never null * @throws ClassCastException if the object is invalid */ Chronology getChronology(Object object, Chronology chrono); //----------------------------------------------------------------------- /** * Extracts the millis from an object of this converter's type. *

* The chronology passed in is the result of the call to getChronology. * * @param object the object to convert * @param chrono the chronology to use, which is the non-null result of getChronology() * @return the millisecond instant * @throws ClassCastException if the object is invalid * @throws IllegalArgumentException if object conversion fails */ long getInstantMillis(Object object, Chronology chrono); } joda-time-2.3/src/main/java/org/joda/time/convert/IntervalConverter.java0000644000175000017500000000364411564251363025671 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.ReadWritableInterval; /** * IntervalConverter defines how an object is converted to an interval. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public interface IntervalConverter extends Converter { /** * Checks if the input is a ReadableInterval. *

* If it is, then the calling code should cast and copy the fields directly. * * @param object the object to convert, must not be null * @param chrono the chronology to use, may be null * @return true if the input is a ReadableInterval * @throws ClassCastException if the object is invalid */ boolean isReadableInterval(Object object, Chronology chrono); /** * Extracts interval endpoint values from an object of this converter's * type, and sets them into the given ReadWritableInterval. * * @param writableInterval interval to get modified, not null * @param object the object to convert, must not be null * @param chrono the chronology to use, may be null * @throws ClassCastException if the object is invalid */ void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono); } joda-time-2.3/src/main/java/org/joda/time/convert/CalendarConverter.java0000644000175000017500000001171211564251363025611 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import java.util.Calendar; import java.util.GregorianCalendar; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.GregorianChronology; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.JulianChronology; /** * CalendarConverter converts a java util Calendar to an instant or partial. * The Calendar is converted to milliseconds and the chronology that best * matches the calendar. * * @author Stephen Colebourne * @since 1.0 */ final class CalendarConverter extends AbstractConverter implements InstantConverter, PartialConverter { /** * Singleton instance. */ static final CalendarConverter INSTANCE = new CalendarConverter(); /** * Restricted constructor. */ protected CalendarConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the chronology. *

* If a chronology is specified then it is used. * Otherwise, it is the GJChronology if a GregorianCalendar is used, * BuddhistChronology if a BuddhistCalendar is used or ISOChronology otherwise. * The time zone is extracted from the calendar if possible, default used if not. * * @param object the Calendar to convert, must not be null * @param chrono the chronology to use, null means use Calendar * @return the chronology, never null * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public Chronology getChronology(Object object, Chronology chrono) { if (chrono != null) { return chrono; } Calendar cal = (Calendar) object; DateTimeZone zone = null; try { zone = DateTimeZone.forTimeZone(cal.getTimeZone()); } catch (IllegalArgumentException ex) { zone = DateTimeZone.getDefault(); } return getChronology(cal, zone); } /** * Gets the chronology, which is the GJChronology if a GregorianCalendar is used, * BuddhistChronology if a BuddhistCalendar is used or ISOChronology otherwise. * The time zone specified is used in preference to that on the calendar. * * @param object the Calendar to convert, must not be null * @param zone the specified zone to use, null means default zone * @return the chronology, never null * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public Chronology getChronology(Object object, DateTimeZone zone) { if (object.getClass().getName().endsWith(".BuddhistCalendar")) { return BuddhistChronology.getInstance(zone); } else if (object instanceof GregorianCalendar) { GregorianCalendar gc = (GregorianCalendar) object; long cutover = gc.getGregorianChange().getTime(); if (cutover == Long.MIN_VALUE) { return GregorianChronology.getInstance(zone); } else if (cutover == Long.MAX_VALUE) { return JulianChronology.getInstance(zone); } else { return GJChronology.getInstance(zone, cutover, 4); } } else { return ISOChronology.getInstance(zone); } } /** * Gets the millis, which is the Calendar millis value. * * @param object the Calendar to convert, must not be null * @param chrono the chronology result from getChronology, non-null * @return the millisecond value * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public long getInstantMillis(Object object, Chronology chrono) { Calendar calendar = (Calendar) object; return calendar.getTime().getTime(); } //----------------------------------------------------------------------- /** * Returns Calendar.class. * * @return Calendar.class */ public Class getSupportedType() { return Calendar.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/NullConverter.java0000644000175000017500000000644611564251363025022 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.Period; import org.joda.time.ReadWritableInterval; import org.joda.time.ReadWritablePeriod; /** * NullConverter converts null to an instant, partial, duration, period * or interval. Null means now for instant/partial, zero for duration/period * and from now to now for interval. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ class NullConverter extends AbstractConverter implements InstantConverter, PartialConverter, DurationConverter, PeriodConverter, IntervalConverter { /** * Singleton instance. */ static final NullConverter INSTANCE = new NullConverter(); /** * Restricted constructor. */ protected NullConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the millisecond duration, which is zero. * * @param object the object to convert, which is null * @return the millisecond duration */ public long getDurationMillis(Object object) { return 0L; } //----------------------------------------------------------------------- /** * Sets the given ReadWritableDuration to zero milliseconds. * * @param duration duration to get modified * @param object the object to convert, which is null * @param chrono the chronology to use * @throws NullPointerException if the duration is null */ public void setInto(ReadWritablePeriod duration, Object object, Chronology chrono) { duration.setPeriod((Period) null); } //----------------------------------------------------------------------- /** * Extracts interval endpoint values from an object of this converter's * type, and sets them into the given ReadWritableInterval. * * @param writableInterval interval to get modified, not null * @param object the object to convert, which is null * @param chrono the chronology to use, may be null * @throws NullPointerException if the interval is null */ public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) { writableInterval.setChronology(chrono); long now = DateTimeUtils.currentTimeMillis(); writableInterval.setInterval(now, now); } //----------------------------------------------------------------------- /** * Returns null. * * @return null */ public Class getSupportedType() { return null; } } joda-time-2.3/src/main/java/org/joda/time/convert/ReadablePartialConverter.java0000644000175000017500000000752211564251363027120 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.ReadablePartial; /** * ReadablePartialConverter extracts partial fields and chronology from a ReadablePartial. * * @author Stephen Colebourne * @since 1.0 */ class ReadablePartialConverter extends AbstractConverter implements PartialConverter { /** * Singleton instance. */ static final ReadablePartialConverter INSTANCE = new ReadablePartialConverter(); /** * Restricted constructor. */ protected ReadablePartialConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the chronology, which is taken from the ReadablePartial. * * @param object the ReadablePartial to convert, must not be null * @param zone the specified zone to use, null means default zone * @return the chronology, never null */ public Chronology getChronology(Object object, DateTimeZone zone) { return getChronology(object, (Chronology) null).withZone(zone); } /** * Gets the chronology, which is taken from the ReadableInstant. *

* If the passed in chronology is non-null, it is used. * Otherwise the chronology from the instant is used. * * @param object the ReadablePartial to convert, must not be null * @param chrono the chronology to use, null means use that from object * @return the chronology, never null */ public Chronology getChronology(Object object, Chronology chrono) { if (chrono == null) { chrono = ((ReadablePartial) object).getChronology(); chrono = DateTimeUtils.getChronology(chrono); } return chrono; } /** * Extracts the values of the partial from an object of this converter's type. * The chrono parameter is a hint to the converter, should it require a * chronology to aid in conversion. * * @param fieldSource a partial that provides access to the fields. * This partial may be incomplete and only getFieldType(int) should be used * @param object the object to convert * @param chrono the chronology to use, which is the non-null result of getChronology() * @return the array of field values that match the fieldSource, must be non-null valid * @throws ClassCastException if the object is invalid */ public int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono) { ReadablePartial input = (ReadablePartial) object; int size = fieldSource.size(); int[] values = new int[size]; for (int i = 0; i < size; i++) { values[i] = input.get(fieldSource.getFieldType(i)); } chrono.validate(fieldSource, values); return values; } //----------------------------------------------------------------------- /** * Returns ReadableInstant.class. * * @return ReadableInstant.class */ public Class getSupportedType() { return ReadablePartial.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/PartialConverter.java0000644000175000017500000000740511564251363025500 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.ReadablePartial; import org.joda.time.format.DateTimeFormatter; /** * PartialConverter defines how an object is converted to a ReadablePartial. *

* The two methods in this interface must be called in order, as the * getPartialValues method relies on the result of the * getChronology method being passed in. * * @author Stephen Colebourne * @since 1.0 */ public interface PartialConverter extends Converter { /** * Extracts the chronology from an object of this converter's type * where the time zone is specified. * * @param object the object to convert * @param zone the specified zone to use, null means default zone * @return the chronology, never null * @throws ClassCastException if the object is invalid * @since 1.3 */ Chronology getChronology(Object object, DateTimeZone zone); /** * Extracts the chronology from an object of this converter's type * where the chronology is specified. * * @param object the object to convert * @param chrono the chronology to use, null usually means ISO * @return the chronology, not converted to UTC/local time zone, must be non-null valid * @throws ClassCastException if the object is invalid */ Chronology getChronology(Object object, Chronology chrono); /** * Extracts the values of the partial from an object of this converter's type. * The chrono parameter is a hint to the converter, should it require a * chronology to aid in conversion. * * @param fieldSource a partial that provides access to the fields. * This partial may be incomplete and only getFieldType(int) should be used * @param object the object to convert * @param chrono the chronology to use, which is the non-null result of getChronology() * @return the array of field values that match the fieldSource, must be non-null valid * @throws ClassCastException if the object is invalid */ int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono); /** * Extracts the values of the partial from an object of this converter's type. * The chrono parameter is a hint to the converter, should it require a * chronology to aid in conversion. * * @param fieldSource a partial that provides access to the fields. * This partial may be incomplete and only getFieldType(int) should be used * @param object the object to convert * @param chrono the chronology to use, which is the non-null result of getChronology() * @param parser if converting from a String, the given parser is preferred * @return the array of field values that match the fieldSource, must be non-null valid * @throws ClassCastException if the object is invalid * @since 1.3 */ int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono, DateTimeFormatter parser); } joda-time-2.3/src/main/java/org/joda/time/convert/LongConverter.java0000644000175000017500000000506311564251363025001 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; /** * LongConverter converts a Long to an instant, partial or duration. * The Long value represents milliseconds in the ISO chronology. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ class LongConverter extends AbstractConverter implements InstantConverter, PartialConverter, DurationConverter { /** * Singleton instance. */ static final LongConverter INSTANCE = new LongConverter(); /** * Restricted constructor. */ protected LongConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the millisecond instant, which is the Long value. * * @param object the Long to convert, must not be null * @param chrono the chronology to use, which is always non-null * @return the millisecond value * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public long getInstantMillis(Object object, Chronology chrono) { return ((Long) object).longValue(); } //----------------------------------------------------------------------- /** * Gets the millisecond duration, which is the Long value. * * @param object the Long to convert, must not be null * @return the millisecond duration * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public long getDurationMillis(Object object) { return ((Long) object).longValue(); } //----------------------------------------------------------------------- /** * Returns Long.class. * * @return Long.class */ public Class getSupportedType() { return Long.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/PeriodConverter.java0000644000175000017500000000335311564251363025324 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.PeriodType; import org.joda.time.ReadWritablePeriod; /** * PeriodConverter defines how an object is converted to a time period. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public interface PeriodConverter extends Converter { /** * Extracts duration values from an object of this converter's type, and * sets them into the given ReadWritableDuration. * * @param period the period to modify * @param object the object to convert, must not be null * @param chrono the chronology to use, must not be null * @throws ClassCastException if the object is invalid */ void setInto(ReadWritablePeriod period, Object object, Chronology chrono); /** * Selects a suitable period type for the given object. * * @param object the object to examine, must not be null * @return the period type, never null * @throws ClassCastException if the object is invalid */ PeriodType getPeriodType(Object object); } joda-time-2.3/src/main/java/org/joda/time/convert/AbstractConverter.java0000644000175000017500000001426411564251363025650 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.PeriodType; import org.joda.time.ReadablePartial; import org.joda.time.chrono.ISOChronology; import org.joda.time.format.DateTimeFormatter; /** * AbstractConverter simplifies the process of implementing a converter. * * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractConverter implements Converter { /** * Restricted constructor. */ protected AbstractConverter() { super(); } //----------------------------------------------------------------------- /** * Extracts the millis from an object of this convertor's type. *

* This implementation returns the current time. * * @param object the object to convert * @param chrono the chronology to use, which is always non-null * @return the millisecond value */ public long getInstantMillis(Object object, Chronology chrono) { return DateTimeUtils.currentTimeMillis(); } //----------------------------------------------------------------------- /** * Extracts the chronology from an object of this convertor's type * where the time zone is specified. *

* This implementation returns the ISO chronology. * * @param object the object to convert * @param zone the specified zone to use, null means default zone * @return the chronology, never null */ public Chronology getChronology(Object object, DateTimeZone zone) { return ISOChronology.getInstance(zone); } /** * Extracts the chronology from an object of this convertor's type * where the chronology is specified. *

* This implementation returns the chronology specified, or the * ISO chronology in the default zone if null passed in. * * @param object the object to convert * @param chrono the chronology to use, null means ISO default * @return the chronology, never null */ public Chronology getChronology(Object object, Chronology chrono) { return DateTimeUtils.getChronology(chrono); } //----------------------------------------------------------------------- /** * Extracts the values of the partial from an object of this converter's type. * The chrono parameter is a hint to the converter, should it require a * chronology to aid in conversion. *

* This implementation calls {@link #getInstantMillis(Object, Chronology)}. * * @param fieldSource a partial that provides access to the fields. * This partial may be incomplete and only getFieldType(int) should be used * @param object the object to convert * @param chrono the chronology to use, which is the non-null result of getChronology() * @return the array of field values that match the fieldSource, must be non-null valid * @throws ClassCastException if the object is invalid */ public int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono) { long instant = getInstantMillis(object, chrono); return chrono.get(fieldSource, instant); } /** * Extracts the values of the partial from an object of this converter's type. * The chrono parameter is a hint to the converter, should it require a * chronology to aid in conversion. *

* This implementation calls {@link #getPartialValues(ReadablePartial, Object, Chronology)}. * * @param fieldSource a partial that provides access to the fields. * This partial may be incomplete and only getFieldType(int) should be used * @param object the object to convert * @param chrono the chronology to use, which is the non-null result of getChronology() * @param parser if converting from a String, the given parser is preferred * @return the array of field values that match the fieldSource, must be non-null valid * @throws ClassCastException if the object is invalid * @since 1.3 */ public int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono, DateTimeFormatter parser) { return getPartialValues(fieldSource, object, chrono); } //----------------------------------------------------------------------- /** * Selects a suitable period type for the given object. * * @param object the object to examine * @return the period type, never null */ public PeriodType getPeriodType(Object object) { return PeriodType.standard(); } //----------------------------------------------------------------------- /** * Checks if the input is a ReadableInterval. *

* If it is, then the calling code should cast and copy the fields directly. * * @param object the object to convert * @param chrono the chronology to use, may be null * @return true if the input is a ReadableInterval */ public boolean isReadableInterval(Object object, Chronology chrono) { return false; } //----------------------------------------------------------------------- /** * Gets a debugging string version of this converter. * * @return a debugging string */ public String toString() { return "Converter[" + (getSupportedType() == null ? "null" : getSupportedType().getName()) + "]"; } } joda-time-2.3/src/main/java/org/joda/time/convert/ConverterManager.java0000644000175000017500000005305311564251363025456 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.JodaTimePermission; /** * ConverterManager controls the date and time converters. *

* This class enables additional conversion classes to be added via * {@link #addInstantConverter(InstantConverter)}, which may replace an * existing converter. Similar methods exist for duration, time period and * interval converters. *

* This class is threadsafe, so adding/removing converters can be done at any * time. Updating the set of convertors is relatively expensive, and so should * not be performed often. *

* The default instant converters are: *

    *
  • ReadableInstant *
  • String *
  • Calendar *
  • Date (includes sql package subclasses) *
  • Long (milliseconds) *
  • null (now) *
* * The default partial converters are: *
    *
  • ReadablePartial *
  • ReadableInstant *
  • String *
  • Calendar *
  • Date (includes sql package subclasses) *
  • Long (milliseconds) *
  • null (now) *
* * The default duration converters are: *
    *
  • ReadableDuration *
  • ReadableInterval *
  • String *
  • Long (milliseconds) *
  • null (zero ms) *
* * The default time period converters are: *
    *
  • ReadablePeriod *
  • ReadableInterval *
  • String *
  • null (zero) *
* * The default interval converters are: *
    *
  • ReadableInterval *
  • String *
  • null (zero-length from now to now) *
* * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public final class ConverterManager { /** * Singleton instance, lazily loaded to avoid class loading. */ private static ConverterManager INSTANCE; public static ConverterManager getInstance() { if (INSTANCE == null) { INSTANCE = new ConverterManager(); } return INSTANCE; } private ConverterSet iInstantConverters; private ConverterSet iPartialConverters; private ConverterSet iDurationConverters; private ConverterSet iPeriodConverters; private ConverterSet iIntervalConverters; /** * Restricted constructor. */ protected ConverterManager() { super(); iInstantConverters = new ConverterSet(new Converter[] { ReadableInstantConverter.INSTANCE, StringConverter.INSTANCE, CalendarConverter.INSTANCE, DateConverter.INSTANCE, LongConverter.INSTANCE, NullConverter.INSTANCE, }); iPartialConverters = new ConverterSet(new Converter[] { ReadablePartialConverter.INSTANCE, ReadableInstantConverter.INSTANCE, StringConverter.INSTANCE, CalendarConverter.INSTANCE, DateConverter.INSTANCE, LongConverter.INSTANCE, NullConverter.INSTANCE, }); iDurationConverters = new ConverterSet(new Converter[] { ReadableDurationConverter.INSTANCE, ReadableIntervalConverter.INSTANCE, StringConverter.INSTANCE, LongConverter.INSTANCE, NullConverter.INSTANCE, }); iPeriodConverters = new ConverterSet(new Converter[] { ReadableDurationConverter.INSTANCE, ReadablePeriodConverter.INSTANCE, ReadableIntervalConverter.INSTANCE, StringConverter.INSTANCE, NullConverter.INSTANCE, }); iIntervalConverters = new ConverterSet(new Converter[] { ReadableIntervalConverter.INSTANCE, StringConverter.INSTANCE, NullConverter.INSTANCE, }); } //----------------------------------------------------------------------- /** * Gets the best converter for the object specified. * * @param object the object to convert * @return the converter to use * @throws IllegalArgumentException if no suitable converter * @throws IllegalStateException if multiple converters match the type * equally well */ public InstantConverter getInstantConverter(Object object) { InstantConverter converter = (InstantConverter)iInstantConverters.select(object == null ? null : object.getClass()); if (converter != null) { return converter; } throw new IllegalArgumentException("No instant converter found for type: " + (object == null ? "null" : object.getClass().getName())); } //----------------------------------------------------------------------- /** * Gets a copy of the set of converters. * * @return the converters, a copy of the real data, never null */ public InstantConverter[] getInstantConverters() { ConverterSet set = iInstantConverters; InstantConverter[] converters = new InstantConverter[set.size()]; set.copyInto(converters); return converters; } /** * Adds a converter to the set of converters. If a matching converter is * already in the set, the given converter replaces it. If the converter is * exactly the same as one already in the set, no changes are made. *

* The order in which converters are added is not relevent. The best * converter is selected by examining the object hierarchy. * * @param converter the converter to add, null ignored * @return replaced converter, or null */ public InstantConverter addInstantConverter(InstantConverter converter) throws SecurityException { checkAlterInstantConverters(); if (converter == null) { return null; } InstantConverter[] removed = new InstantConverter[1]; iInstantConverters = iInstantConverters.add(converter, removed); return removed[0]; } /** * Removes a converter from the set of converters. If the converter was * not in the set, no changes are made. * * @param converter the converter to remove, null ignored * @return replaced converter, or null */ public InstantConverter removeInstantConverter(InstantConverter converter) throws SecurityException { checkAlterInstantConverters(); if (converter == null) { return null; } InstantConverter[] removed = new InstantConverter[1]; iInstantConverters = iInstantConverters.remove(converter, removed); return removed[0]; } /** * Checks whether the user has permission 'ConverterManager.alterInstantConverters'. * * @throws SecurityException if the user does not have the permission */ private void checkAlterInstantConverters() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("ConverterManager.alterInstantConverters")); } } //----------------------------------------------------------------------- /** * Gets the best converter for the object specified. * * @param object the object to convert * @return the converter to use * @throws IllegalArgumentException if no suitable converter * @throws IllegalStateException if multiple converters match the type * equally well */ public PartialConverter getPartialConverter(Object object) { PartialConverter converter = (PartialConverter)iPartialConverters.select(object == null ? null : object.getClass()); if (converter != null) { return converter; } throw new IllegalArgumentException("No partial converter found for type: " + (object == null ? "null" : object.getClass().getName())); } //----------------------------------------------------------------------- /** * Gets a copy of the set of converters. * * @return the converters, a copy of the real data, never null */ public PartialConverter[] getPartialConverters() { ConverterSet set = iPartialConverters; PartialConverter[] converters = new PartialConverter[set.size()]; set.copyInto(converters); return converters; } /** * Adds a converter to the set of converters. If a matching converter is * already in the set, the given converter replaces it. If the converter is * exactly the same as one already in the set, no changes are made. *

* The order in which converters are added is not relevent. The best * converter is selected by examining the object hierarchy. * * @param converter the converter to add, null ignored * @return replaced converter, or null */ public PartialConverter addPartialConverter(PartialConverter converter) throws SecurityException { checkAlterPartialConverters(); if (converter == null) { return null; } PartialConverter[] removed = new PartialConverter[1]; iPartialConverters = iPartialConverters.add(converter, removed); return removed[0]; } /** * Removes a converter from the set of converters. If the converter was * not in the set, no changes are made. * * @param converter the converter to remove, null ignored * @return replaced converter, or null */ public PartialConverter removePartialConverter(PartialConverter converter) throws SecurityException { checkAlterPartialConverters(); if (converter == null) { return null; } PartialConverter[] removed = new PartialConverter[1]; iPartialConverters = iPartialConverters.remove(converter, removed); return removed[0]; } /** * Checks whether the user has permission 'ConverterManager.alterPartialConverters'. * * @throws SecurityException if the user does not have the permission */ private void checkAlterPartialConverters() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("ConverterManager.alterPartialConverters")); } } //----------------------------------------------------------------------- /** * Gets the best converter for the object specified. * * @param object the object to convert * @return the converter to use * @throws IllegalArgumentException if no suitable converter * @throws IllegalStateException if multiple converters match the type * equally well */ public DurationConverter getDurationConverter(Object object) { DurationConverter converter = (DurationConverter)iDurationConverters.select(object == null ? null : object.getClass()); if (converter != null) { return converter; } throw new IllegalArgumentException("No duration converter found for type: " + (object == null ? "null" : object.getClass().getName())); } //----------------------------------------------------------------------- /** * Gets a copy of the list of converters. * * @return the converters, a copy of the real data, never null */ public DurationConverter[] getDurationConverters() { ConverterSet set = iDurationConverters; DurationConverter[] converters = new DurationConverter[set.size()]; set.copyInto(converters); return converters; } /** * Adds a converter to the set of converters. If a matching converter is * already in the set, the given converter replaces it. If the converter is * exactly the same as one already in the set, no changes are made. *

* The order in which converters are added is not relevent. The best * converter is selected by examining the object hierarchy. * * @param converter the converter to add, null ignored * @return replaced converter, or null */ public DurationConverter addDurationConverter(DurationConverter converter) throws SecurityException { checkAlterDurationConverters(); if (converter == null) { return null; } DurationConverter[] removed = new DurationConverter[1]; iDurationConverters = iDurationConverters.add(converter, removed); return removed[0]; } /** * Removes a converter from the set of converters. If the converter was * not in the set, no changes are made. * * @param converter the converter to remove, null ignored * @return replaced converter, or null */ public DurationConverter removeDurationConverter(DurationConverter converter) throws SecurityException { checkAlterDurationConverters(); if (converter == null) { return null; } DurationConverter[] removed = new DurationConverter[1]; iDurationConverters = iDurationConverters.remove(converter, removed); return removed[0]; } /** * Checks whether the user has permission 'ConverterManager.alterDurationConverters'. * * @throws SecurityException if the user does not have the permission */ private void checkAlterDurationConverters() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("ConverterManager.alterDurationConverters")); } } //----------------------------------------------------------------------- /** * Gets the best converter for the object specified. * * @param object the object to convert * @return the converter to use * @throws IllegalArgumentException if no suitable converter * @throws IllegalStateException if multiple converters match the type * equally well */ public PeriodConverter getPeriodConverter(Object object) { PeriodConverter converter = (PeriodConverter)iPeriodConverters.select(object == null ? null : object.getClass()); if (converter != null) { return converter; } throw new IllegalArgumentException("No period converter found for type: " + (object == null ? "null" : object.getClass().getName())); } //----------------------------------------------------------------------- /** * Gets a copy of the list of converters. * * @return the converters, a copy of the real data, never null */ public PeriodConverter[] getPeriodConverters() { ConverterSet set = iPeriodConverters; PeriodConverter[] converters = new PeriodConverter[set.size()]; set.copyInto(converters); return converters; } /** * Adds a converter to the set of converters. If a matching converter is * already in the set, the given converter replaces it. If the converter is * exactly the same as one already in the set, no changes are made. *

* The order in which converters are added is not relevent. The best * converter is selected by examining the object hierarchy. * * @param converter the converter to add, null ignored * @return replaced converter, or null */ public PeriodConverter addPeriodConverter(PeriodConverter converter) throws SecurityException { checkAlterPeriodConverters(); if (converter == null) { return null; } PeriodConverter[] removed = new PeriodConverter[1]; iPeriodConverters = iPeriodConverters.add(converter, removed); return removed[0]; } /** * Removes a converter from the set of converters. If the converter was * not in the set, no changes are made. * * @param converter the converter to remove, null ignored * @return replaced converter, or null */ public PeriodConverter removePeriodConverter(PeriodConverter converter) throws SecurityException { checkAlterPeriodConverters(); if (converter == null) { return null; } PeriodConverter[] removed = new PeriodConverter[1]; iPeriodConverters = iPeriodConverters.remove(converter, removed); return removed[0]; } /** * Checks whether the user has permission 'ConverterManager.alterPeriodConverters'. * * @throws SecurityException if the user does not have the permission */ private void checkAlterPeriodConverters() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("ConverterManager.alterPeriodConverters")); } } //----------------------------------------------------------------------- /** * Gets the best converter for the object specified. * * @param object the object to convert * @return the converter to use * @throws IllegalArgumentException if no suitable converter * @throws IllegalStateException if multiple converters match the type * equally well */ public IntervalConverter getIntervalConverter(Object object) { IntervalConverter converter = (IntervalConverter)iIntervalConverters.select(object == null ? null : object.getClass()); if (converter != null) { return converter; } throw new IllegalArgumentException("No interval converter found for type: " + (object == null ? "null" : object.getClass().getName())); } //----------------------------------------------------------------------- /** * Gets a copy of the list of converters. * * @return the converters, a copy of the real data, never null */ public IntervalConverter[] getIntervalConverters() { ConverterSet set = iIntervalConverters; IntervalConverter[] converters = new IntervalConverter[set.size()]; set.copyInto(converters); return converters; } /** * Adds a converter to the set of converters. If a matching converter is * already in the set, the given converter replaces it. If the converter is * exactly the same as one already in the set, no changes are made. *

* The order in which converters are added is not relevent. The best * converter is selected by examining the object hierarchy. * * @param converter the converter to add, null ignored * @return replaced converter, or null */ public IntervalConverter addIntervalConverter(IntervalConverter converter) throws SecurityException { checkAlterIntervalConverters(); if (converter == null) { return null; } IntervalConverter[] removed = new IntervalConverter[1]; iIntervalConverters = iIntervalConverters.add(converter, removed); return removed[0]; } /** * Removes a converter from the set of converters. If the converter was * not in the set, no changes are made. * * @param converter the converter to remove, null ignored * @return replaced converter, or null */ public IntervalConverter removeIntervalConverter(IntervalConverter converter) throws SecurityException { checkAlterIntervalConverters(); if (converter == null) { return null; } IntervalConverter[] removed = new IntervalConverter[1]; iIntervalConverters = iIntervalConverters.remove(converter, removed); return removed[0]; } /** * Checks whether the user has permission 'ConverterManager.alterIntervalConverters'. * * @throws SecurityException if the user does not have the permission */ private void checkAlterIntervalConverters() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("ConverterManager.alterIntervalConverters")); } } //----------------------------------------------------------------------- /** * Gets a debug representation of the object. */ public String toString() { return "ConverterManager[" + iInstantConverters.size() + " instant," + iPartialConverters.size() + " partial," + iDurationConverters.size() + " duration," + iPeriodConverters.size() + " period," + iIntervalConverters.size() + " interval]"; } } joda-time-2.3/src/main/java/org/joda/time/convert/DurationConverter.java0000644000175000017500000000226511564251363025670 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; /** * DurationConverter defines how an object is converted to a millisecond duration. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public interface DurationConverter extends Converter { /** * Extracts the millis from an object of this convertor's type. * * @param object the object to convert, must not be null * @return the millisecond duration * @throws ClassCastException if the object is invalid */ long getDurationMillis(Object object); } joda-time-2.3/src/main/java/org/joda/time/convert/ReadableInstantConverter.java0000644000175000017500000000760511564251363027146 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.ReadableInstant; import org.joda.time.chrono.ISOChronology; /** * ReadableInstantConverter extracts milliseconds and chronology from a ReadableInstant. * * @author Stephen Colebourne * @since 1.0 */ class ReadableInstantConverter extends AbstractConverter implements InstantConverter, PartialConverter { /** * Singleton instance. */ static final ReadableInstantConverter INSTANCE = new ReadableInstantConverter(); /** * Restricted constructor. */ protected ReadableInstantConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the chronology, which is taken from the ReadableInstant. * If the chronology on the instant is null, the ISOChronology in the * specified time zone is used. * If the chronology on the instant is not in the specified zone, it is * adapted. * * @param object the ReadableInstant to convert, must not be null * @param zone the specified zone to use, null means default zone * @return the chronology, never null */ public Chronology getChronology(Object object, DateTimeZone zone) { Chronology chrono = ((ReadableInstant) object).getChronology(); if (chrono == null) { return ISOChronology.getInstance(zone); } DateTimeZone chronoZone = chrono.getZone(); if (chronoZone != zone) { chrono = chrono.withZone(zone); if (chrono == null) { return ISOChronology.getInstance(zone); } } return chrono; } /** * Gets the chronology, which is taken from the ReadableInstant. *

* If the passed in chronology is non-null, it is used. * Otherwise the chronology from the instant is used. * * @param object the ReadableInstant to convert, must not be null * @param chrono the chronology to use, null means use that from object * @return the chronology, never null */ public Chronology getChronology(Object object, Chronology chrono) { if (chrono == null) { chrono = ((ReadableInstant) object).getChronology(); chrono = DateTimeUtils.getChronology(chrono); } return chrono; } /** * Extracts the millis from an object of this convertor's type. * * @param object the ReadableInstant to convert, must not be null * @param chrono the non-null result of getChronology * @return the millisecond value * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public long getInstantMillis(Object object, Chronology chrono) { return ((ReadableInstant) object).getMillis(); } //----------------------------------------------------------------------- /** * Returns ReadableInstant.class. * * @return ReadableInstant.class */ public Class getSupportedType() { return ReadableInstant.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/ReadableIntervalConverter.java0000644000175000017500000001015611564251363027305 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; import org.joda.time.Chronology; import org.joda.time.DateTimeUtils; import org.joda.time.ReadWritableInterval; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadableInterval; /** * Converts intervals into durations of any requested period type. * * @author Brian S O'Neill * @since 1.0 */ class ReadableIntervalConverter extends AbstractConverter implements IntervalConverter, DurationConverter, PeriodConverter { /** * Singleton instance. */ static final ReadableIntervalConverter INSTANCE = new ReadableIntervalConverter(); /** * Restricted constructor. */ protected ReadableIntervalConverter() { super(); } //----------------------------------------------------------------------- /** * Gets the millisecond length of the interval. * * @param object the interval */ public long getDurationMillis(Object object) { return (((ReadableInterval) object)).toDurationMillis(); } //----------------------------------------------------------------------- /** * Sets the values of the mutable duration from the specified interval. * * @param writablePeriod the period to modify * @param object the interval to set from * @param chrono the chronology to use */ public void setInto(ReadWritablePeriod writablePeriod, Object object, Chronology chrono) { ReadableInterval interval = (ReadableInterval) object; chrono = (chrono != null ? chrono : DateTimeUtils.getIntervalChronology(interval)); long start = interval.getStartMillis(); long end = interval.getEndMillis(); int[] values = chrono.get(writablePeriod, start, end); for (int i = 0; i < values.length; i++) { writablePeriod.setValue(i, values[i]); } } //----------------------------------------------------------------------- /** * Checks if the input is a ReadableInterval. *

* If it is, then the calling code should cast and copy the fields directly. * * @param object the object to convert, must not be null * @param chrono the chronology to use, may be null * @return true if the input is a ReadableInterval * @throws ClassCastException if the object is invalid */ public boolean isReadableInterval(Object object, Chronology chrono) { return true; } /** * Extracts interval endpoint values from an object of this converter's * type, and sets them into the given ReadWritableInterval. * * @param writableInterval interval to get modified, not null * @param object the object to convert, must not be null * @param chrono the chronology to use, may be null * @throws ClassCastException if the object is invalid */ public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) { ReadableInterval input = (ReadableInterval) object; writableInterval.setInterval(input); if (chrono != null) { writableInterval.setChronology(chrono); } else { writableInterval.setChronology(input.getChronology()); } } //----------------------------------------------------------------------- /** * Returns ReadableInterval.class. */ public Class getSupportedType() { return ReadableInterval.class; } } joda-time-2.3/src/main/java/org/joda/time/convert/ConverterSet.java0000644000175000017500000002552611763630722024644 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.convert; /** * A set of converters, which allows exact converters to be quickly * selected. This class is threadsafe because it is (essentially) immutable. * * @author Brian S O'Neill * @since 1.0 */ class ConverterSet { private final Converter[] iConverters; // A simple immutable hashtable: closed hashing, linear probing, sized // power of 2, at least one null slot. private Entry[] iSelectEntries; ConverterSet(Converter[] converters) { // Since this is a package private constructor, we trust ourselves not // to alter the array outside this class. iConverters = converters; iSelectEntries = new Entry[1 << 4]; // 16 } /** * Returns the closest matching converter for the given type, or null if * none found. * * @param type type to select, which may be null * @throws IllegalStateException if multiple converters match the type * equally well */ Converter select(Class type) throws IllegalStateException { // Check the hashtable first. Entry[] entries = iSelectEntries; int length = entries.length; int index = type == null ? 0 : type.hashCode() & (length - 1); Entry e; // This loop depends on there being at least one null slot. while ((e = entries[index]) != null) { if (e.iType == type) { return e.iConverter; } if (++index >= length) { index = 0; } } // Not found in the hashtable, so do actual work. Converter converter = selectSlow(this, type); e = new Entry(type, converter); // Save the entry for future selects. This class must be threadsafe, // but there is no synchronization. Since the hashtable is being used // as a cache, it is okay to destroy existing entries. This isn't // likely to occur unless there is a high amount of concurrency. As // time goes on, cache updates will occur less often, and the cache // will fill with all the necessary entries. // Do all updates on a copy: slots in iSelectEntries must not be // updated by multiple threads as this can allow all null slots to be // consumed. entries = (Entry[])entries.clone(); // Add new entry. entries[index] = e; // Verify that at least one null slot exists! for (int i=0; i= newLength) { index = 0; } } newEntries[index] = e; } // Swap in new hashtable. iSelectEntries = newEntries; return converter; } /** * Returns the amount of converters in the set. */ int size() { return iConverters.length; } /** * Copies all the converters in the set to the given array. */ void copyInto(Converter[] converters) { System.arraycopy(iConverters, 0, converters, 0, iConverters.length); } /** * Returns a copy of this set, with the given converter added. If a * matching converter is already in the set, the given converter replaces * it. If the converter is exactly the same as one already in the set, the * original set is returned. * * @param converter converter to add, must not be null * @param removed if not null, element 0 is set to the removed converter * @throws NullPointerException if converter is null */ ConverterSet add(Converter converter, Converter[] removed) { Converter[] converters = iConverters; int length = converters.length; for (int i=0; i= length) { throw new IndexOutOfBoundsException(); } if (removed != null) { removed[0] = converters[index]; } Converter[] copy = new Converter[length - 1]; int j = 0; for (int i=0; i type) { Converter[] converters = set.iConverters; int length = converters.length; Converter converter; for (int i=length; --i>=0; ) { converter = converters[i]; Class supportedType = converter.getSupportedType(); if (supportedType == type) { // Exact match. return converter; } if (supportedType == null || (type != null && !supportedType.isAssignableFrom(type))) { // Eliminate the impossible. set = set.remove(i, null); converters = set.iConverters; length = converters.length; } } // Haven't found exact match, so check what remains in the set. if (type == null || length == 0) { return null; } if (length == 1) { // Found the one best match. return converters[0]; } // At this point, there exist multiple potential converters. // Eliminate supertypes. for (int i=length; --i>=0; ) { converter = converters[i]; Class supportedType = converter.getSupportedType(); for (int j=length; --j>=0; ) { if (j != i && converters[j].getSupportedType().isAssignableFrom(supportedType)) { // Eliminate supertype. set = set.remove(j, null); converters = set.iConverters; length = converters.length; i = length - 1; } } } // Check what remains in the set. if (length == 1) { // Found the one best match. return converters[0]; } // Class c implements a, b {} // Converters exist only for a and b. Which is better? Neither. StringBuilder msg = new StringBuilder(); msg.append("Unable to find best converter for type \""); msg.append(type.getName()); msg.append("\" from remaining set: "); for (int i=0; i supportedType = converter.getSupportedType(); msg.append(converter.getClass().getName()); msg.append('['); msg.append(supportedType == null ? null : supportedType.getName()); msg.append("], "); } throw new IllegalStateException(msg.toString()); } static class Entry { final Class iType; final Converter iConverter; Entry(Class type, Converter converter) { iType = type; iConverter = converter; } } } joda-time-2.3/src/main/java/org/joda/time/convert/package.html0000644000175000017500000000211711564251363023625 0ustar ebourgebourg org.joda.time.convert package

Implementation package providing conversion between date and time objects.

Provides support for converting objects into instants and durations. Converters are used internally by many of the standard classes, like DateTime. Most applications have no need to use these classes directly.

joda-time-2.3/src/main/java/org/joda/time/MutableDateTime.java0000644000175000017500000014620412035525452023540 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Locale; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseDateTime; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * MutableDateTime is the standard implementation of a modifiable datetime class. * It holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. *

* This class uses a Chronology internally. The Chronology determines how the * millisecond instant value is converted into the date time fields. * The default Chronology is ISOChronology which is the agreed * international standard and compatible with the modern Gregorian calendar. *

* Each individual field can be accessed in two ways: *

    *
  • getHourOfDay() *
  • hourOfDay().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • get numeric value *
  • set numeric value *
  • add to numeric value *
  • add to numeric value wrapping with the field *
  • get text value *
  • get short text value *
  • set text value *
  • field maximum value *
  • field minimum value *
* *

* MutableDateTime is mutable and not thread-safe, unless concurrent threads * are not invoking mutator methods. * * @author Guy Allard * @author Brian S O'Neill * @author Stephen Colebourne * @author Mike Schrag * @since 1.0 * @see DateTime */ public class MutableDateTime extends BaseDateTime implements ReadWritableDateTime, Cloneable, Serializable { /** Serialization version */ private static final long serialVersionUID = 2852608688135209575L; /** Rounding is disabled */ public static final int ROUND_NONE = 0; /** Rounding mode as described by {@link DateTimeField#roundFloor} */ public static final int ROUND_FLOOR = 1; /** Rounding mode as described by {@link DateTimeField#roundCeiling} */ public static final int ROUND_CEILING = 2; /** Rounding mode as described by {@link DateTimeField#roundHalfFloor} */ public static final int ROUND_HALF_FLOOR = 3; /** Rounding mode as described by {@link DateTimeField#roundHalfCeiling} */ public static final int ROUND_HALF_CEILING = 4; /** Rounding mode as described by {@link DateTimeField#roundHalfEven} */ public static final int ROUND_HALF_EVEN = 5; /** The field to round on */ private DateTimeField iRoundingField; /** The mode of rounding */ private int iRoundingMode; //----------------------------------------------------------------------- /** * Obtains a {@code MutableDateTime} set to the current system millisecond time * using ISOChronology in the default time zone. * * @return the current date-time, not null * @since 2.0 */ public static MutableDateTime now() { return new MutableDateTime(); } /** * Obtains a {@code MutableDateTime} set to the current system millisecond time * using ISOChronology in the specified time zone. * * @param zone the time zone, not null * @return the current date-time, not null * @since 2.0 */ public static MutableDateTime now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new MutableDateTime(zone); } /** * Obtains a {@code MutableDateTime} set to the current system millisecond time * using the specified chronology. * * @param chronology the chronology, not null * @return the current date-time, not null * @since 2.0 */ public static MutableDateTime now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new MutableDateTime(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code MutableDateTime} from the specified string. *

* This uses {@link ISODateTimeFormat#dateTimeParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static MutableDateTime parse(String str) { return parse(str, ISODateTimeFormat.dateTimeParser().withOffsetParsed()); } /** * Parses a {@code MutableDateTime} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static MutableDateTime parse(String str, DateTimeFormatter formatter) { return formatter.parseDateTime(str).toMutableDateTime(); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the default time zone. * * @see #now() */ public MutableDateTime() { super(); } /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param zone the time zone, null means default zone * @see #now(DateTimeZone) */ public MutableDateTime(DateTimeZone zone) { super(zone); } /** * Constructs an instance set to the current system millisecond time * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param chronology the chronology, null means ISOChronology in default zone * @see #now(Chronology) */ public MutableDateTime(Chronology chronology) { super(chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the default time zone. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public MutableDateTime(long instant) { super(instant); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public MutableDateTime(long instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public MutableDateTime(long instant, Chronology chronology) { super(instant, chronology); } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime. *

* If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used. Otherwise, ISO default is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object, null means now * @throws IllegalArgumentException if the instant is invalid */ public MutableDateTime(Object instant) { super(instant, (Chronology) null); } /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. *

* If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used, but with the time zone adjusted. * Otherwise, ISO is used in the specified time zone. * If the specified time zone is null, the default zone is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object, null means now * @param zone the time zone, null means default time zone * @throws IllegalArgumentException if the instant is invalid */ public MutableDateTime(Object instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. *

* If the chronology is null, ISO in the default time zone is used. * Any chronology implied by the object (such as GregorianCalendar does) * is ignored. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object, null means now * @param chronology the chronology, null means ISOChronology in default zone * @throws IllegalArgumentException if the instant is invalid */ public MutableDateTime(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology)); } //----------------------------------------------------------------------- /** * Constructs an instance from datetime field values * using ISOChronology in the default time zone. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } /** * Constructs an instance from datetime field values * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param zone the time zone, null means default time zone */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, DateTimeZone zone) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, zone); } /** * Constructs an instance from datetime field values * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param chronology the chronology, null means ISOChronology in default zone */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, chronology); } //----------------------------------------------------------------------- /** * Gets the field used for rounding this instant, returning null if rounding * is not enabled. * * @return the rounding field */ public DateTimeField getRoundingField() { return iRoundingField; } /** * Gets the rounding mode for this instant, returning ROUND_NONE if rounding * is not enabled. * * @return the rounding mode constant */ public int getRoundingMode() { return iRoundingMode; } /** * Sets the status of rounding to use the specified field and ROUND_FLOOR mode. * A null field will disable rounding. * Once set, the instant is then rounded using the new field and mode. *

* Enabling rounding will cause all subsequent calls to {@link #setMillis(long)} * to be rounded. This can be used to control the precision of the instant, * for example by setting a rounding field of minuteOfDay, the seconds and * milliseconds will always be zero. * * @param field rounding field or null to disable */ public void setRounding(DateTimeField field) { setRounding(field, MutableDateTime.ROUND_FLOOR); } /** * Sets the status of rounding to use the specified field and mode. * A null field or mode of ROUND_NONE will disable rounding. * Once set, the instant is then rounded using the new field and mode. *

* Enabling rounding will cause all subsequent calls to {@link #setMillis(long)} * to be rounded. This can be used to control the precision of the instant, * for example by setting a rounding field of minuteOfDay, the seconds and * milliseconds will always be zero. * * @param field rounding field or null to disable * @param mode rounding mode or ROUND_NONE to disable * @throws IllegalArgumentException if mode is unknown, no exception if field is null */ public void setRounding(DateTimeField field, int mode) { if (field != null && (mode < ROUND_NONE || mode > ROUND_HALF_EVEN)) { throw new IllegalArgumentException("Illegal rounding mode: " + mode); } iRoundingField = (mode == ROUND_NONE ? null : field); iRoundingMode = (field == null ? ROUND_NONE : mode); setMillis(getMillis()); } //----------------------------------------------------------------------- /** * Set the milliseconds of the datetime. *

* All changes to the millisecond field occurs via this method. * * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the * datetime to */ public void setMillis(long instant) { switch (iRoundingMode) { case ROUND_NONE: break; case ROUND_FLOOR: instant = iRoundingField.roundFloor(instant); break; case ROUND_CEILING: instant = iRoundingField.roundCeiling(instant); break; case ROUND_HALF_FLOOR: instant = iRoundingField.roundHalfFloor(instant); break; case ROUND_HALF_CEILING: instant = iRoundingField.roundHalfCeiling(instant); break; case ROUND_HALF_EVEN: instant = iRoundingField.roundHalfEven(instant); break; } super.setMillis(instant); } /** * Sets the millisecond instant of this instant from another. *

* This method does not change the chronology of this instant, just the * millisecond instant. * * @param instant the instant to use, null means now */ public void setMillis(ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); setMillis(instantMillis); // set via this class not super } //----------------------------------------------------------------------- /** * Add an amount of time to the datetime. * * @param duration the millis to add * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(long duration) { setMillis(FieldUtils.safeAdd(getMillis(), duration)); // set via this class not super } /** * Adds a duration to this instant. *

* This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadableDuration duration) { add(duration, 1); } /** * Adds a duration to this instant specifying how many times to add. *

* This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadableDuration duration, int scalar) { if (duration != null) { add(FieldUtils.safeMultiply(duration.getMillis(), scalar)); } } /** * Adds a period to this instant. *

* This will typically change the value of most fields. * * @param period the period to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadablePeriod period) { add(period, 1); } /** * Adds a period to this instant specifying how many times to add. *

* This will typically change the value of most fields. * * @param period the period to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadablePeriod period, int scalar) { if (period != null) { setMillis(getChronology().add(period, getMillis(), scalar)); // set via this class not super } } //----------------------------------------------------------------------- /** * Set the chronology of the datetime. *

* All changes to the chronology occur via this method. * * @param chronology the chronology to use, null means ISOChronology in default zone */ public void setChronology(Chronology chronology) { super.setChronology(chronology); } //----------------------------------------------------------------------- /** * Sets the time zone of the datetime, changing the chronology and field values. *

* Changing the zone using this method retains the millisecond instant. * The millisecond instant is adjusted in the new zone to compensate. * * chronology. Setting the time zone does not affect the millisecond value * of this instant. *

* If the chronology already has this time zone, no change occurs. * * @param newZone the time zone to use, null means default zone * @see #setZoneRetainFields */ public void setZone(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); Chronology chrono = getChronology(); if (chrono.getZone() != newZone) { setChronology(chrono.withZone(newZone)); // set via this class not super } } /** * Sets the time zone of the datetime, changing the chronology and millisecond. *

* Changing the zone using this method retains the field values. * The millisecond instant is adjusted in the new zone to compensate. *

* If the chronology already has this time zone, no change occurs. * * @param newZone the time zone to use, null means default zone * @see #setZone */ public void setZoneRetainFields(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); if (newZone == originalZone) { return; } long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); setChronology(getChronology().withZone(newZone)); // set via this class not super setMillis(millis); } //----------------------------------------------------------------------- /** * Sets the value of one of the fields of the instant, such as hourOfDay. * * @param type a field type, usually obtained from DateTimeFieldType, not null * @param value the value to set the field to * @throws IllegalArgumentException if the value is null or invalid */ public void set(DateTimeFieldType type, int value) { if (type == null) { throw new IllegalArgumentException("Field must not be null"); } setMillis(type.getField(getChronology()).set(getMillis(), value)); } /** * Adds to the instant specifying the duration and multiple to add. * * @param type a field type, usually obtained from DateTimeFieldType, not null * @param amount the amount to add of this duration * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(DurationFieldType type, int amount) { if (type == null) { throw new IllegalArgumentException("Field must not be null"); } setMillis(type.getField(getChronology()).add(getMillis(), amount)); } //----------------------------------------------------------------------- /** * Set the year to the specified value. * * @param year the year * @throws IllegalArgumentException if the value is invalid */ public void setYear(final int year) { setMillis(getChronology().year().set(getMillis(), year)); } /** * Add a number of years to the date. * * @param years the years to add * @throws IllegalArgumentException if the value is invalid */ public void addYears(final int years) { setMillis(getChronology().years().add(getMillis(), years)); } //----------------------------------------------------------------------- /** * Set the weekyear to the specified value. * * @param weekyear the weekyear * @throws IllegalArgumentException if the value is invalid */ public void setWeekyear(final int weekyear) { setMillis(getChronology().weekyear().set(getMillis(), weekyear)); } /** * Add a number of weekyears to the date. * * @param weekyears the weekyears to add * @throws IllegalArgumentException if the value is invalid */ public void addWeekyears(final int weekyears) { setMillis(getChronology().weekyears().add(getMillis(), weekyears)); } //----------------------------------------------------------------------- /** * Set the month of the year to the specified value. * * @param monthOfYear the month of the year * @throws IllegalArgumentException if the value is invalid */ public void setMonthOfYear(final int monthOfYear) { setMillis(getChronology().monthOfYear().set(getMillis(), monthOfYear)); } /** * Add a number of months to the date. * * @param months the months to add * @throws IllegalArgumentException if the value is invalid */ public void addMonths(final int months) { setMillis(getChronology().months().add(getMillis(), months)); } //----------------------------------------------------------------------- /** * Set the week of weekyear to the specified value. * * @param weekOfWeekyear the week of the weekyear * @throws IllegalArgumentException if the value is invalid */ public void setWeekOfWeekyear(final int weekOfWeekyear) { setMillis(getChronology().weekOfWeekyear().set(getMillis(), weekOfWeekyear)); } /** * Add a number of weeks to the date. * * @param weeks the weeks to add * @throws IllegalArgumentException if the value is invalid */ public void addWeeks(final int weeks) { setMillis(getChronology().weeks().add(getMillis(), weeks)); } //----------------------------------------------------------------------- /** * Set the day of year to the specified value. * * @param dayOfYear the day of the year * @throws IllegalArgumentException if the value is invalid */ public void setDayOfYear(final int dayOfYear) { setMillis(getChronology().dayOfYear().set(getMillis(), dayOfYear)); } /** * Set the day of the month to the specified value. * * @param dayOfMonth the day of the month * @throws IllegalArgumentException if the value is invalid */ public void setDayOfMonth(final int dayOfMonth) { setMillis(getChronology().dayOfMonth().set(getMillis(), dayOfMonth)); } /** * Set the day of week to the specified value. * * @param dayOfWeek the day of the week * @throws IllegalArgumentException if the value is invalid */ public void setDayOfWeek(final int dayOfWeek) { setMillis(getChronology().dayOfWeek().set(getMillis(), dayOfWeek)); } /** * Add a number of days to the date. * * @param days the days to add * @throws IllegalArgumentException if the value is invalid */ public void addDays(final int days) { setMillis(getChronology().days().add(getMillis(), days)); } //----------------------------------------------------------------------- /** * Set the hour of the day to the specified value. * * @param hourOfDay the hour of day * @throws IllegalArgumentException if the value is invalid */ public void setHourOfDay(final int hourOfDay) { setMillis(getChronology().hourOfDay().set(getMillis(), hourOfDay)); } /** * Add a number of hours to the date. * * @param hours the hours to add * @throws IllegalArgumentException if the value is invalid */ public void addHours(final int hours) { setMillis(getChronology().hours().add(getMillis(), hours)); } //----------------------------------------------------------------------- /** * Set the minute of the day to the specified value. * * @param minuteOfDay the minute of day * @throws IllegalArgumentException if the value is invalid */ public void setMinuteOfDay(final int minuteOfDay) { setMillis(getChronology().minuteOfDay().set(getMillis(), minuteOfDay)); } /** * Set the minute of the hour to the specified value. * * @param minuteOfHour the minute of hour * @throws IllegalArgumentException if the value is invalid */ public void setMinuteOfHour(final int minuteOfHour) { setMillis(getChronology().minuteOfHour().set(getMillis(), minuteOfHour)); } /** * Add a number of minutes to the date. * * @param minutes the minutes to add * @throws IllegalArgumentException if the value is invalid */ public void addMinutes(final int minutes) { setMillis(getChronology().minutes().add(getMillis(), minutes)); } //----------------------------------------------------------------------- /** * Set the second of the day to the specified value. * * @param secondOfDay the second of day * @throws IllegalArgumentException if the value is invalid */ public void setSecondOfDay(final int secondOfDay) { setMillis(getChronology().secondOfDay().set(getMillis(), secondOfDay)); } /** * Set the second of the minute to the specified value. * * @param secondOfMinute the second of minute * @throws IllegalArgumentException if the value is invalid */ public void setSecondOfMinute(final int secondOfMinute) { setMillis(getChronology().secondOfMinute().set(getMillis(), secondOfMinute)); } /** * Add a number of seconds to the date. * * @param seconds the seconds to add * @throws IllegalArgumentException if the value is invalid */ public void addSeconds(final int seconds) { setMillis(getChronology().seconds().add(getMillis(), seconds)); } //----------------------------------------------------------------------- /** * Set the millis of the day to the specified value. * * @param millisOfDay the millis of day * @throws IllegalArgumentException if the value is invalid */ public void setMillisOfDay(final int millisOfDay) { setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); } /** * Set the millis of the second to the specified value. * * @param millisOfSecond the millis of second * @throws IllegalArgumentException if the value is invalid */ public void setMillisOfSecond(final int millisOfSecond) { setMillis(getChronology().millisOfSecond().set(getMillis(), millisOfSecond)); } /** * Add a number of milliseconds to the date. The implementation of this * method differs from the {@link #add(long)} method in that a * DateTimeField performs the addition. * * @param millis the milliseconds to add * @throws IllegalArgumentException if the value is invalid */ public void addMillis(final int millis) { setMillis(getChronology().millis().add(getMillis(), millis)); } //----------------------------------------------------------------------- /** * Set the date from milliseconds. * The time part of this object will be unaffected. * * @param instant an instant to copy the date from, time part ignored * @throws IllegalArgumentException if the value is invalid */ public void setDate(final long instant) { setMillis(getChronology().millisOfDay().set(instant, getMillisOfDay())); } /** * Set the date from another instant. * The time part of this object will be unaffected. *

* If the input is a {@code ReadableDateTime} then it is converted to the * same time-zone as this object before using the instant millis. * * @param instant an instant to copy the date from, time part ignored * @throws IllegalArgumentException if the object is invalid */ public void setDate(final ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); if (instant instanceof ReadableDateTime) { ReadableDateTime rdt = (ReadableDateTime) instant; Chronology instantChrono = DateTimeUtils.getChronology(rdt.getChronology()); DateTimeZone zone = instantChrono.getZone(); if (zone != null) { instantMillis = zone.getMillisKeepLocal(getZone(), instantMillis); } } setDate(instantMillis); } /** * Set the date from fields. * The time part of this object will be unaffected. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @throws IllegalArgumentException if the value is invalid */ public void setDate( final int year, final int monthOfYear, final int dayOfMonth) { Chronology c = getChronology(); long instantMidnight = c.getDateTimeMillis(year, monthOfYear, dayOfMonth, 0); setDate(instantMidnight); } //----------------------------------------------------------------------- /** * Set the time from milliseconds. * The date part of this object will be unaffected. * * @param millis an instant to copy the time from, date part ignored * @throws IllegalArgumentException if the value is invalid */ public void setTime(final long millis) { int millisOfDay = ISOChronology.getInstanceUTC().millisOfDay().get(millis); setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); } /** * Set the time from another instant. * The date part of this object will be unaffected. * * @param instant an instant to copy the time from, date part ignored * @throws IllegalArgumentException if the object is invalid */ public void setTime(final ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); Chronology instantChrono = DateTimeUtils.getInstantChronology(instant); DateTimeZone zone = instantChrono.getZone(); if (zone != null) { instantMillis = zone.getMillisKeepLocal(DateTimeZone.UTC, instantMillis); } setTime(instantMillis); } /** * Set the time from fields. * The date part of this object will be unaffected. * * @param hour the hour * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @throws IllegalArgumentException if the value is invalid */ public void setTime( final int hour, final int minuteOfHour, final int secondOfMinute, final int millisOfSecond) { long instant = getChronology().getDateTimeMillis( getMillis(), hour, minuteOfHour, secondOfMinute, millisOfSecond); setMillis(instant); } /** * Set the date and time from fields. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @throws IllegalArgumentException if the value is invalid */ public void setDateTime( final int year, final int monthOfYear, final int dayOfMonth, final int hourOfDay, final int minuteOfHour, final int secondOfMinute, final int millisOfSecond) { long instant = getChronology().getDateTimeMillis( year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); setMillis(instant); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains many useful methods. * * @param type the field type to get the chronology for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported * @since 1.2 */ public Property property(DateTimeFieldType type) { if (type == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } DateTimeField field = type.getField(getChronology()); if (field.isSupported() == false) { throw new IllegalArgumentException("Field '" + type + "' is not supported"); } return new Property(this, field); } /** * Get the era property. * * @return the era property */ public Property era() { return new Property(this, getChronology().era()); } /** * Get the century of era property. * * @return the year of era property */ public Property centuryOfEra() { return new Property(this, getChronology().centuryOfEra()); } /** * Get the year of century property. * * @return the year of era property */ public Property yearOfCentury() { return new Property(this, getChronology().yearOfCentury()); } /** * Get the year of era property. * * @return the year of era property */ public Property yearOfEra() { return new Property(this, getChronology().yearOfEra()); } /** * Get the year property. * * @return the year property */ public Property year() { return new Property(this, getChronology().year()); } /** * Get the year of a week based year property. * * @return the year of a week based year property */ public Property weekyear() { return new Property(this, getChronology().weekyear()); } /** * Get the month of year property. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, getChronology().monthOfYear()); } /** * Get the week of a week based year property. * * @return the week of a week based year property */ public Property weekOfWeekyear() { return new Property(this, getChronology().weekOfWeekyear()); } /** * Get the day of year property. * * @return the day of year property */ public Property dayOfYear() { return new Property(this, getChronology().dayOfYear()); } /** * Get the day of month property. *

* The values for day of month are defined in {@link DateTimeConstants}. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, getChronology().dayOfMonth()); } /** * Get the day of week property. *

* The values for day of week are defined in {@link DateTimeConstants}. * * @return the day of week property */ public Property dayOfWeek() { return new Property(this, getChronology().dayOfWeek()); } //----------------------------------------------------------------------- /** * Get the hour of day field property * * @return the hour of day property */ public Property hourOfDay() { return new Property(this, getChronology().hourOfDay()); } /** * Get the minute of day property * * @return the minute of day property */ public Property minuteOfDay() { return new Property(this, getChronology().minuteOfDay()); } /** * Get the minute of hour field property * * @return the minute of hour property */ public Property minuteOfHour() { return new Property(this, getChronology().minuteOfHour()); } /** * Get the second of day property * * @return the second of day property */ public Property secondOfDay() { return new Property(this, getChronology().secondOfDay()); } /** * Get the second of minute field property * * @return the second of minute property */ public Property secondOfMinute() { return new Property(this, getChronology().secondOfMinute()); } /** * Get the millis of day property * * @return the millis of day property */ public Property millisOfDay() { return new Property(this, getChronology().millisOfDay()); } /** * Get the millis of second property * * @return the millis of second property */ public Property millisOfSecond() { return new Property(this, getChronology().millisOfSecond()); } //----------------------------------------------------------------------- /** * Clone this object without having to cast the returned object. * * @return a clone of the this object. */ public MutableDateTime copy() { return (MutableDateTime) clone(); } //----------------------------------------------------------------------- /** * Clone this object. * * @return a clone of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError("Clone error"); } } /** * Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ). * * @return ISO8601 time formatted string. */ @ToString public String toString() { return ISODateTimeFormat.dateTime().print(this); } /** * MutableDateTime.Property binds a MutableDateTime to a * DateTimeField allowing powerful datetime functionality to be easily * accessed. *

* The example below shows how to use the property to change the value of a * MutableDateTime object. *

     * MutableDateTime dt = new MutableDateTime(1972, 12, 3, 13, 32, 19, 123);
     * dt.year().add(20);
     * dt.second().roundFloor().minute().set(10);
     * 
*

* MutableDateTime.Propery itself is thread-safe and immutable, but the * MutableDateTime being operated on is not. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization version */ private static final long serialVersionUID = -4481126543819298617L; /** The instant this property is working against */ private MutableDateTime iInstant; /** The field this property is working against */ private DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(MutableDateTime instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Writes the property in a safe serialization format. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(iInstant); oos.writeObject(iField.getType()); } /** * Reads the property from a safe serialization format. */ private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException { iInstant = (MutableDateTime) oos.readObject(); DateTimeFieldType type = (DateTimeFieldType) oos.readObject(); iField = type.getField(iInstant.getChronology()); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the milliseconds of the datetime that this property is linked to. * * @return the milliseconds */ protected long getMillis() { return iInstant.getMillis(); } /** * Gets the chronology of the datetime that this property is linked to. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { return iInstant.getChronology(); } /** * Gets the mutable datetime being used. * * @return the mutable datetime */ public MutableDateTime getMutableDateTime() { return iInstant; } //----------------------------------------------------------------------- /** * Adds a value to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#add(long,int) */ public MutableDateTime add(int value) { iInstant.setMillis(getField().add(iInstant.getMillis(), value)); return iInstant; } /** * Adds a value to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#add(long,long) */ public MutableDateTime add(long value) { iInstant.setMillis(getField().add(iInstant.getMillis(), value)); return iInstant; } /** * Adds a value, possibly wrapped, to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#addWrapField */ public MutableDateTime addWrapField(int value) { iInstant.setMillis(getField().addWrapField(iInstant.getMillis(), value)); return iInstant; } //----------------------------------------------------------------------- /** * Sets a value. * * @param value the value to set. * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#set(long,int) */ public MutableDateTime set(int value) { iInstant.setMillis(getField().set(iInstant.getMillis(), value)); return iInstant; } /** * Sets a text value. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return the mutable datetime being used, so calls can be chained * @throws IllegalArgumentException if the text value isn't valid * @see DateTimeField#set(long,java.lang.String,java.util.Locale) */ public MutableDateTime set(String text, Locale locale) { iInstant.setMillis(getField().set(iInstant.getMillis(), text, locale)); return iInstant; } /** * Sets a text value. * * @param text the text value to set * @return the mutable datetime being used, so calls can be chained * @throws IllegalArgumentException if the text value isn't valid * @see DateTimeField#set(long,java.lang.String) */ public MutableDateTime set(String text) { set(text, null); return iInstant; } //----------------------------------------------------------------------- /** * Round to the lowest whole unit of this field. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundFloor */ public MutableDateTime roundFloor() { iInstant.setMillis(getField().roundFloor(iInstant.getMillis())); return iInstant; } /** * Round to the highest whole unit of this field. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundCeiling */ public MutableDateTime roundCeiling() { iInstant.setMillis(getField().roundCeiling(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field, favoring the floor if * halfway. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfFloor */ public MutableDateTime roundHalfFloor() { iInstant.setMillis(getField().roundHalfFloor(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field, favoring the ceiling if * halfway. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfCeiling */ public MutableDateTime roundHalfCeiling() { iInstant.setMillis(getField().roundHalfCeiling(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field. If halfway, the ceiling * is favored over the floor only if it makes this field's value even. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfEven */ public MutableDateTime roundHalfEven() { iInstant.setMillis(getField().roundHalfEven(iInstant.getMillis())); return iInstant; } } } joda-time-2.3/src/main/java/org/joda/time/LocalDate.java0000644000175000017500000024321412200501234022343 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.TimeZone; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseLocal; import org.joda.time.chrono.ISOChronology; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.PartialConverter; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * LocalDate is an immutable datetime class representing a date * without a time zone. *

* LocalDate implements the {@link ReadablePartial} interface. * To do this, the interface methods focus on the key fields - * Year, MonthOfYear and DayOfMonth. * However, all date fields may in fact be queried. *

* LocalDate differs from DateMidnight in that this class does not * have a time zone and does not represent a single instant in time. *

* Calculations on LocalDate are performed using a {@link Chronology}. * This chronology will be set internally to be in the UTC time zone * for all calculations. * *

Each individual field can be queried in two ways: *

    *
  • getMonthOfYear() *
  • monthOfYear().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value *
  • text value *
  • short text value *
  • maximum/minimum values *
  • add/subtract *
  • set *
  • rounding *
* *

* LocalDate is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @since 1.3 */ public final class LocalDate extends BaseLocal implements ReadablePartial, Serializable { /** Serialization lock */ private static final long serialVersionUID = -8775358157899L; /** The index of the year field in the field array */ private static final int YEAR = 0; /** The index of the monthOfYear field in the field array */ private static final int MONTH_OF_YEAR = 1; /** The index of the dayOfMonth field in the field array */ private static final int DAY_OF_MONTH = 2; /** Set of known duration types. */ private static final Set DATE_DURATION_TYPES = new HashSet(); static { DATE_DURATION_TYPES.add(DurationFieldType.days()); DATE_DURATION_TYPES.add(DurationFieldType.weeks()); DATE_DURATION_TYPES.add(DurationFieldType.months()); DATE_DURATION_TYPES.add(DurationFieldType.weekyears()); DATE_DURATION_TYPES.add(DurationFieldType.years()); DATE_DURATION_TYPES.add(DurationFieldType.centuries()); // eras are supported, although the DurationField generally isn't DATE_DURATION_TYPES.add(DurationFieldType.eras()); } /** The local millis from 1970-01-01T00:00:00 */ private final long iLocalMillis; /** The chronology to use in UTC. */ private final Chronology iChronology; /** The cached hash code. */ private transient volatile int iHash; //----------------------------------------------------------------------- /** * Obtains a {@code LocalDate} set to the current system millisecond time * using ISOChronology in the default time zone. * * @return the current date-time, not null * @since 2.0 */ public static LocalDate now() { return new LocalDate(); } /** * Obtains a {@code LocalDate} set to the current system millisecond time * using ISOChronology in the specified time zone. * * @param zone the time zone, not null * @return the current date-time, not null * @since 2.0 */ public static LocalDate now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new LocalDate(zone); } /** * Obtains a {@code LocalDate} set to the current system millisecond time * using the specified chronology. * * @param chronology the chronology, not null * @return the current date-time, not null * @since 2.0 */ public static LocalDate now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new LocalDate(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code LocalDate} from the specified string. *

* This uses {@link ISODateTimeFormat#localDateParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static LocalDate parse(String str) { return parse(str, ISODateTimeFormat.localDateParser()); } /** * Parses a {@code LocalDate} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static LocalDate parse(String str, DateTimeFormatter formatter) { return formatter.parseLocalDate(str); } //----------------------------------------------------------------------- /** * Constructs a LocalDate from a java.util.Calendar * using exactly the same field values. *

* Each field is queried from the Calendar and assigned to the LocalDate. * This is useful if you have been using the Calendar as a local date, * ignoring the zone. *

* One advantage of this method is that this method is unaffected if the * version of the time zone data differs between the JDK and Joda-Time. * That is because the local field values are transferred, calculated using * the JDK time zone data and without using the Joda-Time time zone data. *

* This factory method ignores the type of the calendar and always * creates a LocalDate with ISO chronology. It is expected that you * will only pass in instances of GregorianCalendar however * this is not validated. * * @param calendar the Calendar to extract fields from, not null * @return the created local date, not null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology */ public static LocalDate fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } int era = calendar.get(Calendar.ERA); int yearOfEra = calendar.get(Calendar.YEAR); return new LocalDate( (era == GregorianCalendar.AD ? yearOfEra : 1 - yearOfEra), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH) ); } /** * Constructs a LocalDate from a java.util.Date * using exactly the same field values. *

* Each field is queried from the Date and assigned to the LocalDate. * This is useful if you have been using the Date as a local date, * ignoring the zone. *

* One advantage of this method is that this method is unaffected if the * version of the time zone data differs between the JDK and Joda-Time. * That is because the local field values are transferred, calculated using * the JDK time zone data and without using the Joda-Time time zone data. *

* This factory method always creates a LocalDate with ISO chronology. * * @param date the Date to extract fields from, not null * @return the created local date, not null * @throws IllegalArgumentException if the calendar is null * @throws IllegalArgumentException if the date is invalid for the ISO chronology */ @SuppressWarnings("deprecation") public static LocalDate fromDateFields(Date date) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } if (date.getTime() < 0) { // handle years in era BC GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); return fromCalendarFields(cal); } return new LocalDate( date.getYear() + 1900, date.getMonth() + 1, date.getDate() ); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current local time evaluated using * ISO chronology in the default zone. *

* Once the constructor is completed, the zone is no longer used. * * @see #now() */ public LocalDate() { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance()); } /** * Constructs an instance set to the current local time evaluated using * ISO chronology in the specified zone. *

* If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param zone the time zone, null means default zone * @see #now(DateTimeZone) */ public LocalDate(DateTimeZone zone) { this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the current local time evaluated using * specified chronology. *

* If the chronology is null, ISO chronology in the default time zone is used. * Once the constructor is completed, the zone is no longer used. * * @param chronology the chronology, null means ISOChronology in default zone * @see #now(Chronology) */ public LocalDate(Chronology chronology) { this(DateTimeUtils.currentTimeMillis(), chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the local time defined by the specified * instant evaluated using ISO chronology in the default zone. *

* Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public LocalDate(long instant) { this(instant, ISOChronology.getInstance()); } /** * Constructs an instance set to the local time defined by the specified * instant evaluated using ISO chronology in the specified zone. *

* If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public LocalDate(long instant, DateTimeZone zone) { this(instant, ISOChronology.getInstance(zone)); } /** * Constructs an instance set to the local time defined by the specified * instant evaluated using the specified chronology. *

* If the chronology is null, ISO chronology in the default zone is used. * Once the constructor is completed, the zone is no longer used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public LocalDate(long instant, Chronology chronology) { chronology = DateTimeUtils.getChronology(chronology); long localMillis = chronology.getZone().getMillisKeepLocal(DateTimeZone.UTC, instant); chronology = chronology.withUTC(); iLocalMillis = chronology.dayOfMonth().roundFloor(localMillis); iChronology = chronology; } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime. * The time zone will be retrieved from the object if possible, * otherwise the default time zone will be used. *

* If the object contains no chronology, ISOChronology is used. * Once the constructor is completed, the zone is no longer used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @throws IllegalArgumentException if the instant is invalid */ public LocalDate(Object instant) { this(instant, (Chronology) null); } /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. *

* If the object contains no chronology, ISOChronology is used. * If the specified time zone is null, the default zone is used. * Once the constructor is completed, the zone is no longer used. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @param zone the time zone * @throws IllegalArgumentException if the instant is invalid */ public LocalDate(Object instant, DateTimeZone zone) { PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); Chronology chronology = converter.getChronology(instant, zone); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); int[] values = converter.getPartialValues(this, instant, chronology, ISODateTimeFormat.localDateParser()); iLocalMillis = iChronology.getDateTimeMillis(values[0], values[1], values[2], 0); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. *

* If the chronology is null, ISO in the default time zone is used. * Once the constructor is completed, the zone is no longer used. * If the instant contains a chronology, it will be ignored. * For example, passing a {@code LocalDate} and a different chronology * will return a date with the year/month/day from the date applied * unaltered to the specified chronology. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePartial, ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#localDateParser()}. * The default String converter ignores the zone and only parses the field values. * * @param instant the datetime object * @param chronology the chronology * @throws IllegalArgumentException if the instant is invalid */ public LocalDate(Object instant, Chronology chronology) { PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); chronology = converter.getChronology(instant, chronology); chronology = DateTimeUtils.getChronology(chronology); iChronology = chronology.withUTC(); int[] values = converter.getPartialValues(this, instant, chronology, ISODateTimeFormat.localDateParser()); iLocalMillis = iChronology.getDateTimeMillis(values[0], values[1], values[2], 0); } //----------------------------------------------------------------------- /** * Constructs an instance set to the specified date and time * using ISOChronology. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 */ public LocalDate( int year, int monthOfYear, int dayOfMonth) { this(year, monthOfYear, dayOfMonth, ISOChronology.getInstanceUTC()); } /** * Constructs an instance set to the specified date and time * using the specified chronology, whose zone is ignored. *

* If the chronology is null, ISOChronology is used. * * @param year the year, valid values defined by the chronology * @param monthOfYear the month of the year, valid values defined by the chronology * @param dayOfMonth the day of the month, valid values defined by the chronology * @param chronology the chronology, null means ISOChronology in default zone */ public LocalDate( int year, int monthOfYear, int dayOfMonth, Chronology chronology) { super(); chronology = DateTimeUtils.getChronology(chronology).withUTC(); long instant = chronology.getDateTimeMillis(year, monthOfYear, dayOfMonth, 0); iChronology = chronology; iLocalMillis = instant; } /** * Handle broken serialization from other tools. * @return the resolved object, not null */ private Object readResolve() { if (iChronology == null) { return new LocalDate(iLocalMillis, ISOChronology.getInstanceUTC()); } if (DateTimeZone.UTC.equals(iChronology.getZone()) == false) { return new LocalDate(iLocalMillis, iChronology.withUTC()); } return this; } //----------------------------------------------------------------------- /** * Gets the number of fields in this partial, which is three. * The supported fields are Year, MonthOfYear and DayOfMonth. * Note that all fields from day and above may in fact be queried via * other methods. * * @return the field count, three */ public int size() { return 3; } /** * Gets the field for a specific index in the chronology specified. *

* This method must not use any instance variables. * * @param index the index to retrieve * @param chrono the chronology to use * @return the field */ protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case YEAR: return chrono.year(); case MONTH_OF_YEAR: return chrono.monthOfYear(); case DAY_OF_MONTH: return chrono.dayOfMonth(); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } /** * Gets the value of the field at the specifed index. *

* This method is required to support the ReadablePartial * interface. The supported fields are Year, MonthOfYear and DayOfMonth. * Note that all fields from day and above may in fact be queried via * other methods. * * @param index the index, zero to two * @return the value * @throws IndexOutOfBoundsException if the index is invalid */ public int getValue(int index) { switch (index) { case YEAR: return getChronology().year().get(getLocalMillis()); case MONTH_OF_YEAR: return getChronology().monthOfYear().get(getLocalMillis()); case DAY_OF_MONTH: return getChronology().dayOfMonth().get(getLocalMillis()); default: throw new IndexOutOfBoundsException("Invalid index: " + index); } } //----------------------------------------------------------------------- /** * Get the value of one of the fields of a datetime. *

* This method gets the value of the specified field. * For example: *

     * LocalDate dt = LocalDate.nowDefaultZone();
     * int year = dt.get(DateTimeFieldType.year());
     * 
* * @param fieldType a field type, usually obtained from DateTimeFieldType, not null * @return the value of that field * @throws IllegalArgumentException if the field type is null or unsupported */ public int get(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } return fieldType.getField(getChronology()).get(getLocalMillis()); } /** * Checks if the field type specified is supported by this * local date and chronology. * This can be used to avoid exceptions in {@link #get(DateTimeFieldType)}. * * @param type a field type, usually obtained from DateTimeFieldType * @return true if the field type is supported */ public boolean isSupported(DateTimeFieldType type) { if (type == null) { return false; } DurationFieldType durType = type.getDurationType(); if (DATE_DURATION_TYPES.contains(durType) || durType.getField(getChronology()).getUnitMillis() >= getChronology().days().getUnitMillis()) { return type.getField(getChronology()).isSupported(); } return false; } /** * Checks if the duration type specified is supported by this * local date and chronology. * * @param type a duration type, usually obtained from DurationFieldType * @return true if the field type is supported */ public boolean isSupported(DurationFieldType type) { if (type == null) { return false; } DurationField field = type.getField(getChronology()); if (DATE_DURATION_TYPES.contains(type) || field.getUnitMillis() >= getChronology().days().getUnitMillis()) { return field.isSupported(); } return false; } //----------------------------------------------------------------------- /** * Gets the local milliseconds from the Java epoch * of 1970-01-01T00:00:00 (not fixed to any specific time zone). * * @return the number of milliseconds since 1970-01-01T00:00:00 * @since 1.5 (previously private) */ protected long getLocalMillis() { return iLocalMillis; } /** * Gets the chronology of the date. * * @return the Chronology that the date is using */ public Chronology getChronology() { return iChronology; } //----------------------------------------------------------------------- /** * Compares this ReadablePartial with another returning true if the chronology, * field types and values are equal. * * @param partial an object to check against * @return true if fields and values are equal */ public boolean equals(Object partial) { // override to perform faster if (this == partial) { return true; } if (partial instanceof LocalDate) { LocalDate other = (LocalDate) partial; if (iChronology.equals(other.iChronology)) { return iLocalMillis == other.iLocalMillis; } } return super.equals(partial); } /** * Gets a hash code for the instant as defined in ReadablePartial. * * @return a suitable hash code */ public int hashCode() { // override for performance int hash = iHash; if (hash == 0) { hash = iHash = super.hashCode(); } return hash; } /** * Compares this partial with another returning an integer * indicating the order. *

* The fields are compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. *

* The specified object must be a partial instance whose field types * match those of this partial. * * @param partial an object to check against * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the partial is the wrong class * or if it has field types that don't match * @throws NullPointerException if the partial is null */ public int compareTo(ReadablePartial partial) { // override to perform faster if (this == partial) { return 0; } if (partial instanceof LocalDate) { LocalDate other = (LocalDate) partial; if (iChronology.equals(other.iChronology)) { return (iLocalMillis < other.iLocalMillis ? -1 : (iLocalMillis == other.iLocalMillis ? 0 : 1)); } } return super.compareTo(partial); } //----------------------------------------------------------------------- /** * Converts this LocalDate to a full datetime at the earliest valid time * for the date using the default time zone. *

* The time will normally be midnight, as that is the earliest time on * any given day. However, in some time zones when Daylight Savings Time * starts, there is no midnight because time jumps from 11:59 to 01:00. * This method handles that situation by returning 01:00 on that date. *

* This instance is immutable and unaffected by this method call. * * @return this date as a datetime at the start of the day * @since 1.5 */ public DateTime toDateTimeAtStartOfDay() { return toDateTimeAtStartOfDay(null); } /** * Converts this LocalDate to a full datetime at the earliest valid time * for the date using the specified time zone. *

* The time will normally be midnight, as that is the earliest time on * any given day. However, in some time zones when Daylight Savings Time * starts, there is no midnight because time jumps from 11:59 to 01:00. * This method handles that situation by returning 01:00 on that date. *

* This method uses the chronology from this instance plus the time zone * specified. *

* This instance is immutable and unaffected by this method call. * * @param zone the zone to use, null means default zone * @return this date as a datetime at the start of the day * @since 1.5 */ public DateTime toDateTimeAtStartOfDay(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); Chronology chrono = getChronology().withZone(zone); long localMillis = getLocalMillis() + 6L * DateTimeConstants.MILLIS_PER_HOUR; long instant = zone.convertLocalToUTC(localMillis, false); instant = chrono.dayOfMonth().roundFloor(instant); return new DateTime(instant, chrono); } //----------------------------------------------------------------------- /** * Converts this LocalDate to a full datetime at midnight using the default * time zone. *

* This method will throw an exception if the default time zone switches * to Daylight Savings Time at midnight and this LocalDate represents * that switchover date. The problem is that there is no such time as * midnight on the required date, and as such an exception is thrown. *

* This instance is immutable and unaffected by this method call. * * @return this date as a datetime at midnight * @deprecated Use {@link #toDateTimeAtStartOfDay()} which won't throw an exception */ @Deprecated public DateTime toDateTimeAtMidnight() { return toDateTimeAtMidnight(null); } /** * Converts this LocalDate to a full datetime at midnight using the * specified time zone. *

* This method will throw an exception if the time zone switches * to Daylight Savings Time at midnight and this LocalDate represents * that switchover date. The problem is that there is no such time as * midnight on the required date, and as such an exception is thrown. *

* This method uses the chronology from this instance plus the time zone * specified. *

* This instance is immutable and unaffected by this method call. * * @param zone the zone to use, null means default zone * @return this date as a datetime at midnight * @deprecated Use {@link #toDateTimeAtStartOfDay(DateTimeZone)} which won't throw an exception */ @Deprecated public DateTime toDateTimeAtMidnight(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); Chronology chrono = getChronology().withZone(zone); return new DateTime(getYear(), getMonthOfYear(), getDayOfMonth(), 0, 0, 0, 0, chrono); } //----------------------------------------------------------------------- /** * Converts this LocalDate to a full datetime using the default time zone * setting the date fields from this instance and the time fields from * the current time. *

* This method will throw an exception if the datetime that would be * created does not exist when the time zone is taken into account. *

* This instance is immutable and unaffected by this method call. * * @return this date as a datetime with the time as the current time */ public DateTime toDateTimeAtCurrentTime() { return toDateTimeAtCurrentTime(null); } /** * Converts this LocalDate to a full datetime using the specified time zone * setting the date fields from this instance and the time fields from * the current time. *

* This method uses the chronology from this instance plus the time zone * specified. *

* This method will throw an exception if the datetime that would be * created does not exist when the time zone is taken into account. *

* This instance is immutable and unaffected by this method call. * * @param zone the zone to use, null means default zone * @return this date as a datetime with the time as the current time */ public DateTime toDateTimeAtCurrentTime(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); Chronology chrono = getChronology().withZone(zone); long instantMillis = DateTimeUtils.currentTimeMillis(); long resolved = chrono.set(this, instantMillis); return new DateTime(resolved, chrono); } //----------------------------------------------------------------------- /** * Converts this LocalDate to a DateMidnight in the default time zone. *

* As from v1.5, you are recommended to avoid DateMidnight and use * {@link #toDateTimeAtStartOfDay()} instead because of the exception * detailed below. *

* This method will throw an exception if the default time zone switches * to Daylight Savings Time at midnight and this LocalDate represents * that switchover date. The problem is that there is no such time as * midnight on the required date, and as such an exception is thrown. *

* This instance is immutable and unaffected by this method call. * * @return the DateMidnight instance in the default zone * @deprecated DateMidnight is deprecated */ @Deprecated public DateMidnight toDateMidnight() { return toDateMidnight(null); } /** * Converts this LocalDate to a DateMidnight. *

* As from v1.5, you are recommended to avoid DateMidnight and use * {@link #toDateTimeAtStartOfDay()} instead because of the exception * detailed below. *

* This method will throw an exception if the time zone switches * to Daylight Savings Time at midnight and this LocalDate represents * that switchover date. The problem is that there is no such time as * midnight on the required date, and as such an exception is thrown. *

* This instance is immutable and unaffected by this method call. * * @param zone the zone to get the DateMidnight in, null means default zone * @return the DateMidnight instance * @deprecated DateMidnight is deprecated */ @Deprecated public DateMidnight toDateMidnight(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); Chronology chrono = getChronology().withZone(zone); return new DateMidnight(getYear(), getMonthOfYear(), getDayOfMonth(), chrono); } //----------------------------------------------------------------------- /** * Converts this object to a LocalDateTime using a LocalTime to fill in * the missing fields. *

* The resulting chronology is determined by the chronology of this * LocalDate. The chronology of the time must also match. * If the time is null an exception is thrown. *

* This instance is immutable and unaffected by this method call. * * @param time the time of day to use, must not be null * @return the LocalDateTime instance * @throws IllegalArgumentException if the time is null * @throws IllegalArgumentException if the chronology of the time does not match * @since 1.5 */ public LocalDateTime toLocalDateTime(LocalTime time) { if (time == null) { throw new IllegalArgumentException("The time must not be null"); } if (getChronology() != time.getChronology()) { throw new IllegalArgumentException("The chronology of the time does not match"); } long localMillis = getLocalMillis() + time.getLocalMillis(); return new LocalDateTime(localMillis, getChronology()); } //----------------------------------------------------------------------- /** * Converts this object to a DateTime using a LocalTime to fill in the * missing fields and using the default time zone. *

* The resulting chronology is determined by the chronology of this * LocalDate. The chronology of the time must match. * If the time is null, the current time in the date's chronology is used. *

* This method will throw an exception if the datetime that would be * created does not exist when the time zone is taken into account. *

* This instance is immutable and unaffected by this method call. * * @param time the time of day to use, null means current time * @return the DateTime instance * @throws IllegalArgumentException if the chronology of the time does not match */ public DateTime toDateTime(LocalTime time) { return toDateTime(time, null); } /** * Converts this object to a DateTime using a LocalTime to fill in the * missing fields. *

* The resulting chronology is determined by the chronology of this * LocalDate plus the time zone. The chronology of the time must match. * If the time is null, the current time in the date's chronology is used. *

* This method will throw an exception if the datetime that would be * created does not exist when the time zone is taken into account. *

* This instance is immutable and unaffected by this method call. * * @param time the time of day to use, null means current time * @param zone the zone to get the DateTime in, null means default * @return the DateTime instance * @throws IllegalArgumentException if the chronology of the time does not match */ public DateTime toDateTime(LocalTime time, DateTimeZone zone) { if (time != null && getChronology() != time.getChronology()) { throw new IllegalArgumentException("The chronology of the time does not match"); } Chronology chrono = getChronology().withZone(zone); long instant = DateTimeUtils.currentTimeMillis(); instant = chrono.set(this, instant); if (time != null) { instant = chrono.set(time, instant); } return new DateTime(instant, chrono); } //----------------------------------------------------------------------- /** * Converts this object to an Interval representing the whole day * in the default time zone. *

* The interval may have more or less than 24 hours if this is a daylight * savings cutover date. *

* This instance is immutable and unaffected by this method call. * * @return a interval over the day */ public Interval toInterval() { return toInterval(null); } /** * Converts this object to an Interval representing the whole day. *

* The interval may have more or less than 24 hours if this is a daylight * savings cutover date. *

* This instance is immutable and unaffected by this method call. * * @param zone the zone to get the Interval in, null means default * @return a interval over the day */ public Interval toInterval(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); DateTime start = toDateTimeAtStartOfDay(zone); DateTime end = plusDays(1).toDateTimeAtStartOfDay(zone); return new Interval(start, end); } //----------------------------------------------------------------------- /** * Get the date time as a java.util.Date. *

* The Date object created has exactly the same year, month and day * as this date. The time will be set to the earliest valid time for that date. *

* Converting to a JDK Date is full of complications as the JDK Date constructor * doesn't behave as you might expect around DST transitions. This method works * by taking a first guess and then adjusting the JDK date until it has the * earliest valid instant. This also handles the situation where the JDK time * zone data differs from the Joda-Time time zone data. * * @return a Date initialised with this date, never null * @since 2.0 */ @SuppressWarnings("deprecation") public Date toDate() { int dom = getDayOfMonth(); Date date = new Date(getYear() - 1900, getMonthOfYear() - 1, dom); LocalDate check = LocalDate.fromDateFields(date); if (check.isBefore(this)) { // DST gap (no midnight) // move forward in units of one hour until date correct while (check.equals(this) == false) { date.setTime(date.getTime() + 3600000); check = LocalDate.fromDateFields(date); } // move back in units of one second until date wrong while (date.getDate() == dom) { date.setTime(date.getTime() - 1000); } // fix result date.setTime(date.getTime() + 1000); } else if (check.equals(this)) { // check for DST overlap (two midnights) Date earlier = new Date(date.getTime() - TimeZone.getDefault().getDSTSavings()); if (earlier.getDate() == dom) { date = earlier; } } return date; } //----------------------------------------------------------------------- /** * Returns a copy of this date with different local millis. *

* The returned object will be a new instance of the same type. * Only the millis will change, the chronology is kept. * The returned object will be either be a new instance or this. * * @param newMillis the new millis, from 1970-01-01T00:00:00 * @return a copy of this date with different millis */ LocalDate withLocalMillis(long newMillis) { newMillis = iChronology.dayOfMonth().roundFloor(newMillis); return (newMillis == getLocalMillis() ? this : new LocalDate(newMillis, getChronology())); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the partial set of fields replacing * those from this instance. *

* For example, if the partial contains a year and a month then those two * fields will be changed in the returned instance. * Unsupported fields are ignored. * If the partial is null, then this is returned. * * @param partial the partial set of fields to apply to this date, null ignored * @return a copy of this date with a different set of fields * @throws IllegalArgumentException if any value is invalid */ public LocalDate withFields(ReadablePartial partial) { if (partial == null) { return this; } return withLocalMillis(getChronology().set(partial, getLocalMillis())); } /** * Returns a copy of this date with the specified field set to a new value. *

* For example, if the field type is monthOfYear then the * month of year field will be changed in the returned instance. * If the field type is null, then this is returned. *

* These two lines are equivalent: *

     * LocalDate updated = dt.withDayOfMonth(6);
     * LocalDate updated = dt.withField(DateTimeFieldType.dayOfMonth(), 6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this date with the field set * @throws IllegalArgumentException if the field is null or unsupported */ public LocalDate withField(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } long instant = fieldType.getField(getChronology()).set(getLocalMillis(), value); return withLocalMillis(instant); } /** * Returns a copy of this date with the value of the specified field increased. *

* If the addition is zero or the field is null, then this is returned. *

* These three lines are equivalent: *

     * LocalDate added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * LocalDate added = dt.plusYears(6);
     * LocalDate added = dt.plus(Period.years(6));
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this date with the field updated * @throws IllegalArgumentException if the field is null or unsupported * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDate withFieldAdded(DurationFieldType fieldType, int amount) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } if (amount == 0) { return this; } long instant = fieldType.getField(getChronology()).add(getLocalMillis(), amount); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified period added. *

* If the addition is zero, then this is returned. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusYears(int)}. *

* Unsupported time fields are ignored, thus adding a period of 24 hours * will not have any effect. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this date with the period added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDate withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getLocalMillis(); Chronology chrono = getChronology(); for (int i = 0; i < period.size(); i++) { long value = FieldUtils.safeMultiply(period.getValue(i), scalar); DurationFieldType type = period.getFieldType(i); if (isSupported(type)) { instant = type.getField(chrono).add(instant, value); } } return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified period added. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusYears(int)}. *

* Unsupported time fields are ignored, thus adding a period of 24 hours * will not have any effect. * * @param period the period to add to this one, null means zero * @return a copy of this date with the period added * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDate plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this date plus the specified number of years. *

* This adds the specified number of years to the date. * If adding years makes the day-of-month invalid, it is adjusted to the last valid day in the month. * This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate added = dt.plusYears(6);
     * LocalDate added = dt.plus(Period.years(6));
     * LocalDate added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * 
* * @param years the amount of years to add, may be negative * @return the new LocalDate plus the increased years */ public LocalDate plusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().add(getLocalMillis(), years); return withLocalMillis(instant); } /** * Returns a copy of this date plus the specified number of months. *

* This adds the specified number of months to the date. * The addition may change the year, but the day-of-month is normally unchanged. * If adding months makes the day-of-month invalid, it is adjusted to the last valid day in the month. * This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate added = dt.plusMonths(6);
     * LocalDate added = dt.plus(Period.months(6));
     * LocalDate added = dt.withFieldAdded(DurationFieldType.months(), 6);
     * 
* * @param months the amount of months to add, may be negative * @return the new LocalDate plus the increased months */ public LocalDate plusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().add(getLocalMillis(), months); return withLocalMillis(instant); } /** * Returns a copy of this date plus the specified number of weeks. *

* This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate added = dt.plusWeeks(6);
     * LocalDate added = dt.plus(Period.weeks(6));
     * LocalDate added = dt.withFieldAdded(DurationFieldType.weeks(), 6);
     * 
* * @param weeks the amount of weeks to add, may be negative * @return the new LocalDate plus the increased weeks */ public LocalDate plusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().add(getLocalMillis(), weeks); return withLocalMillis(instant); } /** * Returns a copy of this date plus the specified number of days. *

* This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate added = dt.plusDays(6);
     * LocalDate added = dt.plus(Period.days(6));
     * LocalDate added = dt.withFieldAdded(DurationFieldType.days(), 6);
     * 
* * @param days the amount of days to add, may be negative * @return the new LocalDate plus the increased days */ public LocalDate plusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().add(getLocalMillis(), days); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the specified period taken away. *

* If the amount is zero or null, then this is returned. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusYears(int)}. *

* Unsupported time fields are ignored, thus subtracting a period of 24 hours * will not have any effect. * * @param period the period to reduce this instant by * @return a copy of this LocalDate with the period taken away * @throws ArithmeticException if the result exceeds the internal capacity */ public LocalDate minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this date minus the specified number of years. *

* This subtracts the specified number of years from the date. * If subtracting years makes the day-of-month invalid, it is adjusted to the last valid day in the month. * This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate subtracted = dt.minusYears(6);
     * LocalDate subtracted = dt.minus(Period.years(6));
     * LocalDate subtracted = dt.withFieldAdded(DurationFieldType.years(), -6);
     * 
* * @param years the amount of years to subtract, may be negative * @return the new LocalDate minus the increased years */ public LocalDate minusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().subtract(getLocalMillis(), years); return withLocalMillis(instant); } /** * Returns a copy of this date minus the specified number of months. *

* This subtracts the specified number of months from the date. * The subtraction may change the year, but the day-of-month is normally unchanged. * If subtracting months makes the day-of-month invalid, it is adjusted to the last valid day in the month. * This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate subtracted = dt.minusMonths(6);
     * LocalDate subtracted = dt.minus(Period.months(6));
     * LocalDate subtracted = dt.withFieldAdded(DurationFieldType.months(), -6);
     * 
* * @param months the amount of months to subtract, may be negative * @return the new LocalDate minus the increased months */ public LocalDate minusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().subtract(getLocalMillis(), months); return withLocalMillis(instant); } /** * Returns a copy of this date minus the specified number of weeks. *

* This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate subtracted = dt.minusWeeks(6);
     * LocalDate subtracted = dt.minus(Period.weeks(6));
     * LocalDate subtracted = dt.withFieldAdded(DurationFieldType.weeks(), -6);
     * 
* * @param weeks the amount of weeks to subtract, may be negative * @return the new LocalDate minus the increased weeks */ public LocalDate minusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().subtract(getLocalMillis(), weeks); return withLocalMillis(instant); } /** * Returns a copy of this date minus the specified number of days. *

* This LocalDate instance is immutable and unaffected by this method call. *

* The following three lines are identical in effect: *

     * LocalDate subtracted = dt.minusDays(6);
     * LocalDate subtracted = dt.minus(Period.days(6));
     * LocalDate subtracted = dt.withFieldAdded(DurationFieldType.days(), -6);
     * 
* * @param days the amount of days to subtract, may be negative * @return the new LocalDate minus the increased days */ public LocalDate minusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().subtract(getLocalMillis(), days); return withLocalMillis(instant); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains many * useful methods. * * @param fieldType the field type to get the chronology for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } if (isSupported(fieldType) == false) { throw new IllegalArgumentException("Field '" + fieldType + "' is not supported"); } return new Property(this, fieldType.getField(getChronology())); } //----------------------------------------------------------------------- /** * Get the era field value. * * @return the era */ public int getEra() { return getChronology().era().get(getLocalMillis()); } /** * Get the year of era field value. * * @return the year of era */ public int getCenturyOfEra() { return getChronology().centuryOfEra().get(getLocalMillis()); } /** * Get the year of era field value. * * @return the year of era */ public int getYearOfEra() { return getChronology().yearOfEra().get(getLocalMillis()); } /** * Get the year of century field value. * * @return the year of century */ public int getYearOfCentury() { return getChronology().yearOfCentury().get(getLocalMillis()); } /** * Get the year field value. * * @return the year */ public int getYear() { return getChronology().year().get(getLocalMillis()); } /** * Get the weekyear field value. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. * * @return the weekyear */ public int getWeekyear() { return getChronology().weekyear().get(getLocalMillis()); } /** * Get the month of year field value. * * @return the month of year */ public int getMonthOfYear() { return getChronology().monthOfYear().get(getLocalMillis()); } /** * Get the week of weekyear field value. *

* This field is associated with the "weekyear" via {@link #getWeekyear()}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * * @return the week of a week based year */ public int getWeekOfWeekyear() { return getChronology().weekOfWeekyear().get(getLocalMillis()); } /** * Get the day of year field value. * * @return the day of year */ public int getDayOfYear() { return getChronology().dayOfYear().get(getLocalMillis()); } /** * Get the day of month field value. *

* The values for the day of month are defined in {@link org.joda.time.DateTimeConstants}. * * @return the day of month */ public int getDayOfMonth() { return getChronology().dayOfMonth().get(getLocalMillis()); } /** * Get the day of week field value. *

* The values for the day of week are defined in {@link org.joda.time.DateTimeConstants}. * * @return the day of week */ public int getDayOfWeek() { return getChronology().dayOfWeek().get(getLocalMillis()); } //----------------------------------------------------------------------- /** * Returns a copy of this date with the era field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * era changed. * * @param era the era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withEra(int era) { return withLocalMillis(getChronology().era().set(getLocalMillis(), era)); } /** * Returns a copy of this date with the century of era field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * century of era changed. * * @param centuryOfEra the centurey of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withCenturyOfEra(int centuryOfEra) { return withLocalMillis(getChronology().centuryOfEra().set(getLocalMillis(), centuryOfEra)); } /** * Returns a copy of this date with the year of era field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of era changed. * * @param yearOfEra the year of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withYearOfEra(int yearOfEra) { return withLocalMillis(getChronology().yearOfEra().set(getLocalMillis(), yearOfEra)); } /** * Returns a copy of this date with the year of century field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of century changed. * * @param yearOfCentury the year of century to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withYearOfCentury(int yearOfCentury) { return withLocalMillis(getChronology().yearOfCentury().set(getLocalMillis(), yearOfCentury)); } /** * Returns a copy of this date with the year field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year changed. * * @param year the year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withYear(int year) { return withLocalMillis(getChronology().year().set(getLocalMillis(), year)); } /** * Returns a copy of this date with the weekyear field updated. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * weekyear changed. * * @param weekyear the weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withWeekyear(int weekyear) { return withLocalMillis(getChronology().weekyear().set(getLocalMillis(), weekyear)); } /** * Returns a copy of this date with the month of year field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withMonthOfYear(int monthOfYear) { return withLocalMillis(getChronology().monthOfYear().set(getLocalMillis(), monthOfYear)); } /** * Returns a copy of this date with the week of weekyear field updated. *

* This field is associated with the "weekyear" via {@link #withWeekyear(int)}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * week of weekyear changed. * * @param weekOfWeekyear the week of weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withWeekOfWeekyear(int weekOfWeekyear) { return withLocalMillis(getChronology().weekOfWeekyear().set(getLocalMillis(), weekOfWeekyear)); } /** * Returns a copy of this date with the day of year field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of year changed. * * @param dayOfYear the day of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withDayOfYear(int dayOfYear) { return withLocalMillis(getChronology().dayOfYear().set(getLocalMillis(), dayOfYear)); } /** * Returns a copy of this date with the day of month field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of month changed. * * @param dayOfMonth the day of month to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withDayOfMonth(int dayOfMonth) { return withLocalMillis(getChronology().dayOfMonth().set(getLocalMillis(), dayOfMonth)); } /** * Returns a copy of this date with the day of week field updated. *

* LocalDate is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of week changed. * * @param dayOfWeek the day of week to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid */ public LocalDate withDayOfWeek(int dayOfWeek) { return withLocalMillis(getChronology().dayOfWeek().set(getLocalMillis(), dayOfWeek)); } //----------------------------------------------------------------------- /** * Get the era property which provides access to advanced functionality. * * @return the era property */ public Property era() { return new Property(this, getChronology().era()); } /** * Get the century of era property which provides access to advanced functionality. * * @return the year of era property */ public Property centuryOfEra() { return new Property(this, getChronology().centuryOfEra()); } /** * Get the year of century property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfCentury() { return new Property(this, getChronology().yearOfCentury()); } /** * Get the year of era property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfEra() { return new Property(this, getChronology().yearOfEra()); } /** * Get the year property which provides access to advanced functionality. * * @return the year property */ public Property year() { return new Property(this, getChronology().year()); } /** * Get the weekyear property which provides access to advanced functionality. * * @return the weekyear property */ public Property weekyear() { return new Property(this, getChronology().weekyear()); } /** * Get the month of year property which provides access to advanced functionality. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, getChronology().monthOfYear()); } /** * Get the week of a week based year property which provides access to advanced functionality. * * @return the week of a week based year property */ public Property weekOfWeekyear() { return new Property(this, getChronology().weekOfWeekyear()); } /** * Get the day of year property which provides access to advanced functionality. * * @return the day of year property */ public Property dayOfYear() { return new Property(this, getChronology().dayOfYear()); } /** * Get the day of month property which provides access to advanced functionality. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, getChronology().dayOfMonth()); } /** * Get the day of week property which provides access to advanced functionality. * * @return the day of week property */ public Property dayOfWeek() { return new Property(this, getChronology().dayOfWeek()); } //----------------------------------------------------------------------- /** * Output the date time in ISO8601 format (yyyy-MM-dd). * * @return ISO8601 time formatted string. */ @ToString public String toString() { return ISODateTimeFormat.date().print(this); } /** * Output the date using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern) { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).print(this); } /** * Output the date using the specified format pattern. * * @param pattern the pattern specification, null means use toString * @param locale Locale to use, null means default * @see org.joda.time.format.DateTimeFormat */ public String toString(String pattern, Locale locale) throws IllegalArgumentException { if (pattern == null) { return toString(); } return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); } //----------------------------------------------------------------------- /** * LocalDate.Property binds a LocalDate to a DateTimeField allowing * powerful datetime functionality to be easily accessed. *

* The simplest use of this class is as an alternative get method, here used to * get the year '1972' (as an int) and the month 'December' (as a String). *

     * LocalDate dt = new LocalDate(1972, 12, 3, 0, 0);
     * int year = dt.year().get();
     * String monthStr = dt.month().getAsText();
     * 
*

* Methods are also provided that allow date modification. These return * new instances of LocalDate - they do not modify the original. The example * below yields two independent immutable date objects 20 years apart. *

     * LocalDate dt = new LocalDate(1972, 12, 3);
     * LocalDate dt1920 = dt.year().setCopy(1920);
     * 
*

* LocalDate.Property itself is thread-safe and immutable, as well as the * LocalDate being operated on. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.3 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization version */ private static final long serialVersionUID = -3193829732634L; /** The instant this property is working against */ private transient LocalDate iInstant; /** The field this property is working against */ private transient DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(LocalDate instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Writes the property in a safe serialization format. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(iInstant); oos.writeObject(iField.getType()); } /** * Reads the property from a safe serialization format. */ private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException { iInstant = (LocalDate) oos.readObject(); DateTimeFieldType type = (DateTimeFieldType) oos.readObject(); iField = type.getField(iInstant.getChronology()); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the milliseconds of the date that this property is linked to. * * @return the milliseconds */ protected long getMillis() { return iInstant.getLocalMillis(); } /** * Gets the chronology of the datetime that this property is linked to. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { return iInstant.getChronology(); } /** * Gets the LocalDate object linked to this property. * * @return the linked LocalDate */ public LocalDate getLocalDate() { return iInstant; } //----------------------------------------------------------------------- /** * Adds to this field in a copy of this LocalDate. *

* The LocalDate attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalDate with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalDate addToCopy(int value) { return iInstant.withLocalMillis(iField.add(iInstant.getLocalMillis(), value)); } /** * Adds to this field, possibly wrapped, in a copy of this LocalDate. * A field wrapped operation only changes this field. * Thus 31st January addWrapField one day goes to the 1st January. *

* The LocalDate attached to this property is unchanged by this call. * * @param value the value to add to the field in the copy * @return a copy of the LocalDate with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalDate addWrapFieldToCopy(int value) { return iInstant.withLocalMillis(iField.addWrapField(iInstant.getLocalMillis(), value)); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the LocalDate. *

* The LocalDate attached to this property is unchanged by this call. * * @param value the value to set the field in the copy to * @return a copy of the LocalDate with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public LocalDate setCopy(int value) { return iInstant.withLocalMillis(iField.set(iInstant.getLocalMillis(), value)); } /** * Sets this field in a copy of the LocalDate to a parsed text value. *

* The LocalDate attached to this property is unchanged by this call. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the LocalDate with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public LocalDate setCopy(String text, Locale locale) { return iInstant.withLocalMillis(iField.set(iInstant.getLocalMillis(), text, locale)); } /** * Sets this field in a copy of the LocalDate to a parsed text value. *

* The LocalDate attached to this property is unchanged by this call. * * @param text the text value to set * @return a copy of the LocalDate with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public LocalDate setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new LocalDate with this field set to the maximum value * for this field. *

* This operation is useful for obtaining a LocalDate on the last day * of the month, as month lengths vary. *

         * LocalDate lastDayOfMonth = dt.dayOfMonth().withMaximumValue();
         * 
*

* The LocalDate attached to this property is unchanged by this call. * * @return a copy of the LocalDate with this field set to its maximum */ public LocalDate withMaximumValue() { return setCopy(getMaximumValue()); } /** * Returns a new LocalDate with this field set to the minimum value * for this field. *

* The LocalDate attached to this property is unchanged by this call. * * @return a copy of the LocalDate with this field set to its minimum */ public LocalDate withMinimumValue() { return setCopy(getMinimumValue()); } //----------------------------------------------------------------------- /** * Rounds to the lowest whole unit of this field on a copy of this * LocalDate. *

* For example, rounding floor on the hourOfDay field of a LocalDate * where the time is 10:30 would result in new LocalDate with the * time of 10:00. * * @return a copy of the LocalDate with the field value changed */ public LocalDate roundFloorCopy() { return iInstant.withLocalMillis(iField.roundFloor(iInstant.getLocalMillis())); } /** * Rounds to the highest whole unit of this field on a copy of this * LocalDate. *

* For example, rounding floor on the hourOfDay field of a LocalDate * where the time is 10:30 would result in new LocalDate with the * time of 11:00. * * @return a copy of the LocalDate with the field value changed */ public LocalDate roundCeilingCopy() { return iInstant.withLocalMillis(iField.roundCeiling(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalDate, favoring the floor if halfway. * * @return a copy of the LocalDate with the field value changed */ public LocalDate roundHalfFloorCopy() { return iInstant.withLocalMillis(iField.roundHalfFloor(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalDate, favoring the ceiling if halfway. * * @return a copy of the LocalDate with the field value changed */ public LocalDate roundHalfCeilingCopy() { return iInstant.withLocalMillis(iField.roundHalfCeiling(iInstant.getLocalMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * LocalDate. If halfway, the ceiling is favored over the floor * only if it makes this field's value even. * * @return a copy of the LocalDate with the field value changed */ public LocalDate roundHalfEvenCopy() { return iInstant.withLocalMillis(iField.roundHalfEven(iInstant.getLocalMillis())); } } } joda-time-2.3/src/main/java/org/joda/time/IllegalFieldValueException.java0000644000175000017500000002475411763631153025733 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Exception thrown when attempting to set a field outside its supported range. * * @author Brian S O'Neill * @since 1.1 */ public class IllegalFieldValueException extends IllegalArgumentException { /** Serialization lock. */ private static final long serialVersionUID = 6305711765985447737L; /** * Creates a message for the exception. * * @param fieldName the field name * @param value the value rejected * @param lowerBound the lower bound allowed * @param upperBound the uppe bound allowed * @param explain an explanation * @return the message */ private static String createMessage(String fieldName, Number value, Number lowerBound, Number upperBound, String explain) { StringBuilder buf = new StringBuilder() .append("Value ").append(value).append(" for ").append(fieldName).append(' '); if (lowerBound == null) { if (upperBound == null) { buf.append("is not supported"); } else { buf.append("must not be larger than ").append(upperBound); } } else if (upperBound == null) { buf.append("must not be smaller than ").append(lowerBound); } else { buf.append("must be in the range [") .append(lowerBound) .append(',') .append(upperBound) .append(']'); } if (explain != null) { buf.append(": ").append(explain); } return buf.toString(); } /** * Creates a message for the exception. * * @param fieldName the field name * @param value the value rejected * @return the message */ private static String createMessage(String fieldName, String value) { StringBuffer buf = new StringBuffer().append("Value "); if (value == null) { buf.append("null"); } else { buf.append('"'); buf.append(value); buf.append('"'); } buf.append(" for ").append(fieldName).append(' ').append("is not supported"); return buf.toString(); } private final DateTimeFieldType iDateTimeFieldType; private final DurationFieldType iDurationFieldType; private final String iFieldName; private final Number iNumberValue; private final String iStringValue; private final Number iLowerBound; private final Number iUpperBound; private String iMessage; /** * Constructor. * * @param fieldType type of field being set * @param value illegal value being set * @param lowerBound lower legal field value, or null if not applicable * @param upperBound upper legal field value, or null if not applicable */ public IllegalFieldValueException(DateTimeFieldType fieldType, Number value, Number lowerBound, Number upperBound) { super(createMessage(fieldType.getName(), value, lowerBound, upperBound, null)); iDateTimeFieldType = fieldType; iDurationFieldType = null; iFieldName = fieldType.getName(); iNumberValue = value; iStringValue = null; iLowerBound = lowerBound; iUpperBound = upperBound; iMessage = super.getMessage(); } /** * Constructor. * * @param fieldType type of field being set * @param value illegal value being set * @param explain an explanation * @since 1.5 */ public IllegalFieldValueException(DateTimeFieldType fieldType, Number value, String explain) { super(createMessage(fieldType.getName(), value, null, null, explain)); iDateTimeFieldType = fieldType; iDurationFieldType = null; iFieldName = fieldType.getName(); iNumberValue = value; iStringValue = null; iLowerBound = null; iUpperBound = null; iMessage = super.getMessage(); } /** * Constructor. * * @param fieldType type of field being set * @param value illegal value being set * @param lowerBound lower legal field value, or null if not applicable * @param upperBound upper legal field value, or null if not applicable */ public IllegalFieldValueException(DurationFieldType fieldType, Number value, Number lowerBound, Number upperBound) { super(createMessage(fieldType.getName(), value, lowerBound, upperBound, null)); iDateTimeFieldType = null; iDurationFieldType = fieldType; iFieldName = fieldType.getName(); iNumberValue = value; iStringValue = null; iLowerBound = lowerBound; iUpperBound = upperBound; iMessage = super.getMessage(); } /** * Constructor. * * @param fieldName name of field being set * @param value illegal value being set * @param lowerBound lower legal field value, or null if not applicable * @param upperBound upper legal field value, or null if not applicable */ public IllegalFieldValueException(String fieldName, Number value, Number lowerBound, Number upperBound) { super(createMessage(fieldName, value, lowerBound, upperBound, null)); iDateTimeFieldType = null; iDurationFieldType = null; iFieldName = fieldName; iNumberValue = value; iStringValue = null; iLowerBound = lowerBound; iUpperBound = upperBound; iMessage = super.getMessage(); } /** * Constructor. * * @param fieldType type of field being set * @param value illegal value being set */ public IllegalFieldValueException(DateTimeFieldType fieldType, String value) { super(createMessage(fieldType.getName(), value)); iDateTimeFieldType = fieldType; iDurationFieldType = null; iFieldName = fieldType.getName(); iStringValue = value; iNumberValue = null; iLowerBound = null; iUpperBound = null; iMessage = super.getMessage(); } /** * Constructor. * * @param fieldType type of field being set * @param value illegal value being set */ public IllegalFieldValueException(DurationFieldType fieldType, String value) { super(createMessage(fieldType.getName(), value)); iDateTimeFieldType = null; iDurationFieldType = fieldType; iFieldName = fieldType.getName(); iStringValue = value; iNumberValue = null; iLowerBound = null; iUpperBound = null; iMessage = super.getMessage(); } /** * Constructor. * * @param fieldName name of field being set * @param value illegal value being set */ public IllegalFieldValueException(String fieldName, String value) { super(createMessage(fieldName, value)); iDateTimeFieldType = null; iDurationFieldType = null; iFieldName = fieldName; iStringValue = value; iNumberValue = null; iLowerBound = null; iUpperBound = null; iMessage = super.getMessage(); } //----------------------------------------------------------------------- /** * Returns the DateTimeFieldType whose value was invalid, or null if not applicable. * * @return the datetime field type */ public DateTimeFieldType getDateTimeFieldType() { return iDateTimeFieldType; } /** * Returns the DurationFieldType whose value was invalid, or null if not applicable. * * @return the duration field type */ public DurationFieldType getDurationFieldType() { return iDurationFieldType; } /** * Returns the name of the field whose value was invalid. * * @return the field name */ public String getFieldName() { return iFieldName; } /** * Returns the illegal integer value assigned to the field, or null if not applicable. * * @return the value */ public Number getIllegalNumberValue() { return iNumberValue; } /** * Returns the illegal string value assigned to the field, or null if not applicable. * * @return the value */ public String getIllegalStringValue() { return iStringValue; } /** * Returns the illegal value assigned to the field as a non-null string. * * @return the value */ public String getIllegalValueAsString() { String value = iStringValue; if (value == null) { value = String.valueOf(iNumberValue); } return value; } /** * Returns the lower bound of the legal value range, or null if not applicable. * * @return the lower bound */ public Number getLowerBound() { return iLowerBound; } /** * Returns the upper bound of the legal value range, or null if not applicable. * * @return the upper bound */ public Number getUpperBound() { return iUpperBound; } public String getMessage() { return iMessage; } /** * Provide additional detail by prepending a message to the existing message. * A colon is separator is automatically inserted between the messages. * @since 1.3 */ public void prependMessage(String message) { if (iMessage == null) { iMessage = message; } else if (message != null) { iMessage = message + ": " + iMessage; } } } joda-time-2.3/src/main/java/org/joda/time/ReadablePeriod.java0000644000175000017500000001372611564251363023401 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines a time period specified in terms of individual duration fields * such as years and days. *

* The implementation of this interface may be mutable or immutable. This * interface only gives access to retrieve data, never to change it. *

* Periods are split up into multiple fields, for example days and seconds. * Implementations are not required to evenly distribute the values across the fields. * The value for each field may be positive or negative. *

* When a time period is added to an instant, the effect is to add each field in turn. * For example, a time period could be defined as 3 months, 2 days and -1 hours. * In most circumstances this would be the same as 3 months, 1 day, and 23 hours. * However, when adding across a daylight savings boundary, a day may be 23 or 25 hours long. * Thus, the time period is always added field by field to the datetime. *

* Periods are independent of chronology, and can only be treated as durations * when paired with a time via an interval. * * @see ReadableDuration * @see ReadableInterval * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public interface ReadablePeriod { /** * Gets the period type that defines which fields are included in the period. * * @return the period type */ PeriodType getPeriodType(); /** * Gets the number of fields that this period supports. * * @return the number of fields supported */ int size(); /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DurationFieldType getFieldType(int index); /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value of the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ int getValue(int index); /** * Gets the value of one of the fields. *

* If the field type specified is not supported by the period then zero * is returned. * * @param field the field type to query, null returns zero * @return the value of that field, zero if field not supported */ int get(DurationFieldType field); /** * Checks whether the field type specified is supported by this period. * * @param field the field to check, may be null which returns false * @return true if the field is supported */ boolean isSupported(DurationFieldType field); //----------------------------------------------------------------------- /** * Get this period as an immutable Period object. *

* This will either typecast this instance, or create a new Period. * * @return a Duration using the same field set and values */ Period toPeriod(); /** * Get this object as a MutablePeriod. *

* This will always return a new MutablePeriod with the same fields. * * @return a MutablePeriod using the same field set and values */ MutablePeriod toMutablePeriod(); //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the value and type of each supported field. * All ReadablePeriod instances are accepted. *

* Note that a period of 1 day is not equal to a period of 24 hours, * nor is 1 hour equal to 60 minutes. Only periods with the same amount * in each field are equal. *

* This is because periods represent an abstracted definition of a time * period (eg. a day may not actually be 24 hours, it might be 23 or 25 * at daylight savings boundary). *

* To compare the actual duration of two periods, convert both to * {@link Duration}s, an operation that emphasises that the result may * differ according to the date you choose. * * @param readablePeriod a readable period to check against * @return true if all the field values and types are equal, false if * not or the period is null or of an incorrect type */ boolean equals(Object readablePeriod); /** * Gets a hash code for the period that is compatible with the equals method. * The hashcode is calculated as follows: *

     *  int total = 17;
     *  for (int i = 0; i < fields.length; i++) {
     *      total = 27 * total + getValue(i);
     *      total = 27 * total + getFieldType(i).hashCode();
     *  }
     *  return total;
     * 
* * @return a hash code */ int hashCode(); //----------------------------------------------------------------------- /** * Gets the value as a String in the style of the ISO8601 duration format. * Technically, the output can breach the ISO specification as weeks may be included. *

* For example, "PT6H3M5S" represents 6 hours, 3 minutes, 5 seconds. * * @return the value as an ISO8601 style string */ String toString(); } joda-time-2.3/src/main/java/org/joda/time/DateTime.java0000644000175000017500000026405512200501234022215 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Locale; import org.joda.convert.FromString; import org.joda.time.base.BaseDateTime; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * DateTime is the standard implementation of an unmodifiable datetime class. *

* DateTime is the most widely used implementation of * {@link ReadableInstant}. As with all instants, it represents an exact * point on the time-line, but limited to the precision of milliseconds. * A DateTime calculates its fields with respect to a * {@link DateTimeZone time zone}. *

* Internally, the class holds two pieces of data. Firstly, it holds the * datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. * Secondly, it holds a {@link Chronology} which determines how the * millisecond instant value is converted into the date time fields. * The default Chronology is {@link ISOChronology} which is the agreed * international standard and compatible with the modern Gregorian calendar. *

* Each individual field can be queried in two ways: *

    *
  • getHourOfDay() *
  • hourOfDay().get() *
* The second technique also provides access to other useful methods on the * field: *
    *
  • numeric value *
  • text value *
  • short text value *
  • maximum/minimum values *
  • add/subtract *
  • set *
  • rounding *
*

* DateTime is thread-safe and immutable, provided that the Chronology is as well. * All standard Chronology classes supplied are thread-safe and immutable. * * @author Stephen Colebourne * @author Kandarp Shah * @author Brian S O'Neill * @since 1.0 * @see MutableDateTime */ public final class DateTime extends BaseDateTime implements ReadableDateTime, Serializable { /** Serialization lock */ private static final long serialVersionUID = -5171125899451703815L; //----------------------------------------------------------------------- /** * Obtains a {@code DateTime} set to the current system millisecond time * using ISOChronology in the default time zone. * * @return the current date-time, not null * @since 2.0 */ public static DateTime now() { return new DateTime(); } /** * Obtains a {@code DateTime} set to the current system millisecond time * using ISOChronology in the specified time zone. * * @param zone the time zone, not null * @return the current date-time, not null * @since 2.0 */ public static DateTime now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new DateTime(zone); } /** * Obtains a {@code DateTime} set to the current system millisecond time * using the specified chronology. * * @param chronology the chronology, not null * @return the current date-time, not null * @since 2.0 */ public static DateTime now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new DateTime(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code DateTime} from the specified string. *

* This uses {@link ISODateTimeFormat#dateTimeParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static DateTime parse(String str) { return parse(str, ISODateTimeFormat.dateTimeParser().withOffsetParsed()); } /** * Parses a {@code DateTime} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static DateTime parse(String str, DateTimeFormatter formatter) { return formatter.parseDateTime(str); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the default time zone. * * @see #now() */ public DateTime() { super(); } /** * Constructs an instance set to the current system millisecond time * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param zone the time zone, null means default zone * @see #now(DateTimeZone) */ public DateTime(DateTimeZone zone) { super(zone); } /** * Constructs an instance set to the current system millisecond time * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param chronology the chronology, null means ISOChronology in default zone * @see #now(Chronology) */ public DateTime(Chronology chronology) { super(chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the default time zone. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public DateTime(long instant) { super(instant); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public DateTime(long instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public DateTime(long instant, Chronology chronology) { super(instant, chronology); } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime. *

* If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used. Otherwise, ISO default is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()}. * * @param instant the datetime object, null means now * @throws IllegalArgumentException if the instant is invalid */ public DateTime(Object instant) { super(instant, (Chronology) null); } /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. *

* If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used, but with the time zone adjusted. * Otherwise, ISO is used in the specified time zone. * If the specified time zone is null, the default zone is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()}. * * @param instant the datetime object, null means now * @param zone the time zone, null means default time zone * @throws IllegalArgumentException if the instant is invalid */ public DateTime(Object instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. *

* If the chronology is null, ISO in the default time zone is used. * Any chronology implied by the object (such as GregorianCalendar does) * is ignored. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * The String formats are described by {@link ISODateTimeFormat#dateTimeParser()}. * * @param instant the datetime object, null means now * @param chronology the chronology, null means ISO in default zone * @throws IllegalArgumentException if the instant is invalid */ public DateTime(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology)); } //----------------------------------------------------------------------- /** * Constructs an instance from datetime field values * using ISOChronology in the default time zone. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @since 2.0 */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, 0, 0); } /** * Constructs an instance from datetime field values * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param zone the time zone, null means default time zone * @since 2.0 */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, DateTimeZone zone) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, 0, 0, zone); } /** * Constructs an instance from datetime field values * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param year the year, valid values defined by the chronology * @param monthOfYear the month of the year, valid values defined by the chronology * @param dayOfMonth the day of the month, valid values defined by the chronology * @param hourOfDay the hour of the day, valid values defined by the chronology * @param minuteOfHour the minute of the hour, valid values defined by the chronology * @param chronology the chronology, null means ISOChronology in default zone * @since 2.0 */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, Chronology chronology) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, 0, 0, chronology); } //----------------------------------------------------------------------- /** * Constructs an instance from datetime field values * using ISOChronology in the default time zone. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 * @since 2.0 */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, 0); } /** * Constructs an instance from datetime field values * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 * @param zone the time zone, null means default time zone * @since 2.0 */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, DateTimeZone zone) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, 0, zone); } /** * Constructs an instance from datetime field values * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param year the year, valid values defined by the chronology * @param monthOfYear the month of the year, valid values defined by the chronology * @param dayOfMonth the day of the month, valid values defined by the chronology * @param hourOfDay the hour of the day, valid values defined by the chronology * @param minuteOfHour the minute of the hour, valid values defined by the chronology * @param secondOfMinute the second of the minute, valid values defined by the chronology * @param chronology the chronology, null means ISOChronology in default zone * @since 2.0 */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, Chronology chronology) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, 0, chronology); } //----------------------------------------------------------------------- /** * Constructs an instance from datetime field values * using ISOChronology in the default time zone. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 * @param millisOfSecond the millisecond of the second, from 0 to 999 */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } /** * Constructs an instance from datetime field values * using ISOChronology in the specified time zone. *

* If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year, from 1 to 12 * @param dayOfMonth the day of the month, from 1 to 31 * @param hourOfDay the hour of the day, from 0 to 23 * @param minuteOfHour the minute of the hour, from 0 to 59 * @param secondOfMinute the second of the minute, from 0 to 59 * @param millisOfSecond the millisecond of the second, from 0 to 999 * @param zone the time zone, null means default time zone */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, DateTimeZone zone) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, zone); } /** * Constructs an instance from datetime field values * using the specified chronology. *

* If the chronology is null, ISOChronology * in the default time zone is used. * * @param year the year, valid values defined by the chronology * @param monthOfYear the month of the year, valid values defined by the chronology * @param dayOfMonth the day of the month, valid values defined by the chronology * @param hourOfDay the hour of the day, valid values defined by the chronology * @param minuteOfHour the minute of the hour, valid values defined by the chronology * @param secondOfMinute the second of the minute, valid values defined by the chronology * @param millisOfSecond the millisecond of the second, valid values defined by the chronology * @param chronology the chronology, null means ISOChronology in default zone */ public DateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, chronology); } //----------------------------------------------------------------------- /** * Get this object as a DateTime by returning this. * * @return this */ public DateTime toDateTime() { return this; } /** * Get this object as a DateTime using ISOChronology in the default zone, * returning this if possible. * * @return a DateTime using the same millis */ public DateTime toDateTimeISO() { if (getChronology() == ISOChronology.getInstance()) { return this; } return super.toDateTimeISO(); } /** * Get this object as a DateTime, returning this if possible. * * @param zone time zone to apply, or default if null * @return a DateTime using the same millis */ public DateTime toDateTime(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); if (getZone() == zone) { return this; } return super.toDateTime(zone); } /** * Get this object as a DateTime, returning this if possible. * * @param chronology chronology to apply, or ISOChronology if null * @return a DateTime using the same millis */ public DateTime toDateTime(Chronology chronology) { chronology = DateTimeUtils.getChronology(chronology); if (getChronology() == chronology) { return this; } return super.toDateTime(chronology); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with different millis. *

* The returned object will be either be a new instance or this. * Only the millis will change, the chronology and time zone are kept. * * @param newMillis the new millis, from 1970-01-01T00:00:00Z * @return a copy of this datetime with different millis */ public DateTime withMillis(long newMillis) { return (newMillis == getMillis() ? this : new DateTime(newMillis, getChronology())); } /** * Returns a copy of this datetime with a different chronology. *

* The returned object will be either be a new instance or this. * Only the chronology will change, the millis are kept. * * @param newChronology the new chronology, null means ISO default * @return a copy of this datetime with a different chronology */ public DateTime withChronology(Chronology newChronology) { newChronology = DateTimeUtils.getChronology(newChronology); return (newChronology == getChronology() ? this : new DateTime(getMillis(), newChronology)); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with a different time zone, preserving the * millisecond instant. *

* This method is useful for finding the local time in another timezone. * For example, if this instant holds 12:30 in Europe/London, the result * from this method with Europe/Paris would be 13:30. *

* The returned object will be a new instance of the same implementation type. * This method changes the time zone, and does not change the * millisecond instant, with the effect that the field values usually change. * The returned object will be either be a new instance or this. * * @param newZone the new time zone * @return a copy of this datetime with a different time zone * @see #withZoneRetainFields */ public DateTime withZone(DateTimeZone newZone) { return withChronology(getChronology().withZone(newZone)); } /** * Returns a copy of this datetime with a different time zone, preserving the * field values. *

* This method is useful for finding the millisecond time in another timezone. * For example, if this instant holds 12:30 in Europe/London (ie. 12:30Z), * the result from this method with Europe/Paris would be 12:30 (ie. 11:30Z). *

* The returned object will be a new instance of the same implementation type. * This method changes the time zone and the millisecond instant to keep * the field values the same. * The returned object will be either be a new instance or this. * * @param newZone the new time zone, null means default * @return a copy of this datetime with a different time zone * @see #withZone */ public DateTime withZoneRetainFields(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); if (newZone == originalZone) { return this; } long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); return new DateTime(millis, getChronology().withZone(newZone)); } /** * Returns a copy of this ZonedDateTime changing the zone offset to the earlier * of the two valid offsets at a local time-line overlap. *

* This method only has any effect when the local time-line overlaps, such as at * an autumn daylight savings cutover. In this scenario, there are two valid offsets * for the local date-time. Calling this method will return a date-time with the * earlier of the two selected. *

* If this method is called when it is not an overlap, this is returned. *

* This instance is immutable and unaffected by this method call. * * @return a copy of this datetime with the earliest valid offset for the local datetime */ public DateTime withEarlierOffsetAtOverlap() { long newMillis = getZone().adjustOffset(getMillis(), false); return withMillis(newMillis); } /** * Returns a copy of this ZonedDateTime changing the zone offset to the later * of the two valid offsets at a local time-line overlap. *

* This method only has any effect when the local time-line overlaps, such as at * an autumn daylight savings cutover. In this scenario, there are two valid offsets * for the local date-time. Calling this method will return a date-time with the * later of the two selected. *

* If this method is called when it is not an overlap, this is returned. *

* This instance is immutable and unaffected by this method call. * * @return a copy of this datetime with the latest valid offset for the local datetime */ public DateTime withLaterOffsetAtOverlap() { long newMillis = getZone().adjustOffset(getMillis(), true); return withMillis(newMillis); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified date, retaining the time fields. *

* If the date is already the date passed in, then this is returned. *

* To set a single field use the properties, for example: *

     * DateTime set = monthOfYear().setCopy(6);
     * 
*

* This instance is immutable and unaffected by this method call. * * @param year the new year value * @param monthOfYear the new monthOfYear value * @param dayOfMonth the new dayOfMonth value * @return a copy of this datetime with a different date * @throws IllegalArgumentException if any value if invalid */ public DateTime withDate(int year, int monthOfYear, int dayOfMonth) { Chronology chrono = getChronology(); long instant = getMillis(); instant = chrono.year().set(instant, year); instant = chrono.monthOfYear().set(instant, monthOfYear); instant = chrono.dayOfMonth().set(instant, dayOfMonth); return withMillis(instant); } /** * Returns a copy of this datetime with the specified time, retaining the date fields. *

* If the time is already the time passed in, then this is returned. *

* To set a single field use the properties, for example: *

     * DateTime set = dt.hourOfDay().setCopy(6);
     * 
*

* This instance is immutable and unaffected by this method call. * * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @return a copy of this datetime with a different time * @throws IllegalArgumentException if any value if invalid */ public DateTime withTime(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { Chronology chrono = getChronology(); long instant = getMillis(); instant = chrono.hourOfDay().set(instant, hourOfDay); instant = chrono.minuteOfHour().set(instant, minuteOfHour); instant = chrono.secondOfMinute().set(instant, secondOfMinute); instant = chrono.millisOfSecond().set(instant, millisOfSecond); return withMillis(instant); } /** * Returns a copy of this datetime with the time set to the start of the day. *

* The time will normally be midnight, as that is the earliest time on * any given day. However, in some time zones when Daylight Savings Time * starts, there is no midnight because time jumps from 11:59 to 01:00. * This method handles that situation by returning 01:00 on that date. *

* This instance is immutable and unaffected by this method call. * * @return a copy of this datetime with the time set to the start of the day, not null */ public DateTime withTimeAtStartOfDay() { return toLocalDate().toDateTimeAtStartOfDay(getZone()); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the partial set of fields replacing those * from this instance. *

* For example, if the partial is a TimeOfDay then the time fields * would be changed in the returned instance. * If the partial is null, then this is returned. * * @param partial the partial set of fields to apply to this datetime, null ignored * @return a copy of this datetime with a different set of fields * @throws IllegalArgumentException if any value is invalid */ public DateTime withFields(ReadablePartial partial) { if (partial == null) { return this; } return withMillis(getChronology().set(partial, getMillis())); } /** * Returns a copy of this datetime with the specified field set to a new value. *

* For example, if the field type is hourOfDay then the hour of day * field would be changed in the returned instance. * If the field type is null, then this is returned. *

* These three lines are equivalent: *

     * DateTime updated = dt.withField(DateTimeFieldType.dayOfMonth(), 6);
     * DateTime updated = dt.dayOfMonth().setCopy(6);
     * DateTime updated = dt.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
     * 
* * @param fieldType the field type to set, not null * @param value the value to set * @return a copy of this datetime with the field set * @throws IllegalArgumentException if the value is null or invalid */ public DateTime withField(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } long instant = fieldType.getField(getChronology()).set(getMillis(), value); return withMillis(instant); } /** * Returns a copy of this datetime with the value of the specified field increased. *

* If the addition is zero or the field is null, then this is returned. *

* These three lines are equivalent: *

     * DateTime added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * DateTime added = dt.plusYears(6);
     * DateTime added = dt.plus(Period.years(6));
     * 
* * @param fieldType the field type to add to, not null * @param amount the amount to add * @return a copy of this datetime with the field updated * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime withFieldAdded(DurationFieldType fieldType, int amount) { if (fieldType == null) { throw new IllegalArgumentException("Field must not be null"); } if (amount == 0) { return this; } long instant = fieldType.getField(getChronology()).add(getMillis(), amount); return withMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified duration added. *

* If the addition is zero, then this is returned. * * @param durationToAdd the duration to add to this one * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime withDurationAdded(long durationToAdd, int scalar) { if (durationToAdd == 0 || scalar == 0) { return this; } long instant = getChronology().add(getMillis(), durationToAdd, scalar); return withMillis(instant); } /** * Returns a copy of this datetime with the specified duration added. *

* If the addition is zero, then this is returned. * * @param durationToAdd the duration to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime withDurationAdded(ReadableDuration durationToAdd, int scalar) { if (durationToAdd == null || scalar == 0) { return this; } return withDurationAdded(durationToAdd.getMillis(), scalar); } /** * Returns a copy of this datetime with the specified period added. *

* If the addition is zero, then this is returned. *

* This method is typically used to add multiple copies of complex * period instances. Adding one field is best achieved using methods * like {@link #withFieldAdded(DurationFieldType, int)} * or {@link #plusYears(int)}. * * @param period the period to add to this one, null means zero * @param scalar the amount of times to add, such as -1 to subtract once * @return a copy of this datetime with the period added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getChronology().add(period, getMillis(), scalar); return withMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified duration added. *

* If the amount is zero or null, then this is returned. * This datetime instance is immutable and unaffected by this method call. * * @param duration the duration, in millis, to add to this one * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime plus(long duration) { return withDurationAdded(duration, 1); } /** * Returns a copy of this datetime with the specified duration added. *

* If the amount is zero or null, then this is returned. * This datetime instance is immutable and unaffected by this method call. * * @param duration the duration to add to this one, null means zero * @return a copy of this datetime with the duration added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime plus(ReadableDuration duration) { return withDurationAdded(duration, 1); } /** * Returns a copy of this datetime with the specified period added. *

* This method will add each element of the period one by one, from largest * to smallest, adjusting the datetime to be accurate between each. *

* Thus, adding a period of one month and one day to 2007-03-31 will * work as follows: * First add one month and adjust, resulting in 2007-04-30 * Then add one day and adjust, resulting in 2007-05-01. *

* This method is typically used to add complex period instances. * Adding one field is best achieved using methods * like {@link #plusYears(int)}. *

* If the amount is zero or null, then this is returned. * This datetime instance is immutable and unaffected by this method call. * * @param period the duration to add to this one, null means zero * @return a copy of this datetime with the period added * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime plus(ReadablePeriod period) { return withPeriodAdded(period, 1); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime plus the specified number of years. *

* The calculation will do its best to only change the year field * retaining the same month of year. * However, in certain circumstances, it may be necessary to alter * smaller fields. For example, 2008-02-29 plus one year cannot result * in 2009-02-29, so the day of month is adjusted to 2009-02-28. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusYears(6);
     * DateTime added = dt.plus(Period.years(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.years(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param years the amount of years to add, may be negative * @return the new datetime plus the increased years * @since 1.1 */ public DateTime plusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().add(getMillis(), years); return withMillis(instant); } /** * Returns a copy of this datetime plus the specified number of months. *

* The calculation will do its best to only change the month field * retaining the same day of month. * However, in certain circumstances, it may be necessary to alter * smaller fields. For example, 2007-03-31 plus one month cannot result * in 2007-04-31, so the day of month is adjusted to 2007-04-30. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusMonths(6);
     * DateTime added = dt.plus(Period.months(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.months(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param months the amount of months to add, may be negative * @return the new datetime plus the increased months * @since 1.1 */ public DateTime plusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().add(getMillis(), months); return withMillis(instant); } /** * Returns a copy of this datetime plus the specified number of weeks. *

* The calculation operates as if it were adding the equivalent in days. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusWeeks(6);
     * DateTime added = dt.plus(Period.weeks(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.weeks(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to add, may be negative * @return the new datetime plus the increased weeks * @since 1.1 */ public DateTime plusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().add(getMillis(), weeks); return withMillis(instant); } /** * Returns a copy of this datetime plus the specified number of days. *

* The calculation will do its best to only change the day field * retaining the same time of day. * However, in certain circumstances, typically daylight savings cutover, * it may be necessary to alter the time fields. *

* In spring an hour is typically removed. If adding one day results in * the time being within the cutover then the time is adjusted to be * within summer time. For example, if the cutover is from 01:59 to 03:00 * and the result of this method would have been 02:30, then the result * will be adjusted to 03:30. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusDays(6);
     * DateTime added = dt.plus(Period.days(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.days(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param days the amount of days to add, may be negative * @return the new datetime plus the increased days * @since 1.1 */ public DateTime plusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().add(getMillis(), days); return withMillis(instant); } /** * Returns a copy of this datetime plus the specified number of hours. *

* The calculation will add a duration equivalent to the number of hours * expressed in milliseconds. *

* For example, if a spring daylight savings cutover is from 01:59 to 03:00 * then adding one hour to 01:30 will result in 03:30. This is a duration * of one hour later, even though the hour field value changed from 1 to 3. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusHours(6);
     * DateTime added = dt.plus(Period.hours(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.hours(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param hours the amount of hours to add, may be negative * @return the new datetime plus the increased hours * @since 1.1 */ public DateTime plusHours(int hours) { if (hours == 0) { return this; } long instant = getChronology().hours().add(getMillis(), hours); return withMillis(instant); } /** * Returns a copy of this datetime plus the specified number of minutes. *

* The calculation will add a duration equivalent to the number of minutes * expressed in milliseconds. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusMinutes(6);
     * DateTime added = dt.plus(Period.minutes(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.minutes(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to add, may be negative * @return the new datetime plus the increased minutes * @since 1.1 */ public DateTime plusMinutes(int minutes) { if (minutes == 0) { return this; } long instant = getChronology().minutes().add(getMillis(), minutes); return withMillis(instant); } /** * Returns a copy of this datetime plus the specified number of seconds. *

* The calculation will add a duration equivalent to the number of seconds * expressed in milliseconds. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusSeconds(6);
     * DateTime added = dt.plus(Period.seconds(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.seconds(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to add, may be negative * @return the new datetime plus the increased seconds * @since 1.1 */ public DateTime plusSeconds(int seconds) { if (seconds == 0) { return this; } long instant = getChronology().seconds().add(getMillis(), seconds); return withMillis(instant); } /** * Returns a copy of this datetime plus the specified number of millis. *

* The calculation will add a duration equivalent to the number of milliseconds. *

* The following three lines are identical in effect: *

     * DateTime added = dt.plusMillis(6);
     * DateTime added = dt.plus(Period.millis(6));
     * DateTime added = dt.withFieldAdded(DurationFieldType.millis(), 6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param millis the amount of millis to add, may be negative * @return the new datetime plus the increased millis * @since 1.1 */ public DateTime plusMillis(int millis) { if (millis == 0) { return this; } long instant = getChronology().millis().add(getMillis(), millis); return withMillis(instant); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the specified duration taken away. *

* If the amount is zero or null, then this is returned. * This datetime instance is immutable and unaffected by this method call. * * @param duration the duration, in millis, to reduce this instant by * @return a copy of this datetime with the duration taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime minus(long duration) { return withDurationAdded(duration, -1); } /** * Returns a copy of this datetime with the specified duration taken away. *

* If the amount is zero or null, then this is returned. * This datetime instance is immutable and unaffected by this method call. * * @param duration the duration to reduce this instant by * @return a copy of this datetime with the duration taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime minus(ReadableDuration duration) { return withDurationAdded(duration, -1); } /** * Returns a copy of this datetime with the specified period taken away. *

* This method will subtract each element of the period one by one, from * largest to smallest, adjusting the datetime to be accurate between each. *

* Thus, subtracting a period of one month and one day from 2007-05-31 will * work as follows: * First subtract one month and adjust, resulting in 2007-04-30 * Then subtract one day and adjust, resulting in 2007-04-29. * Note that the day has been adjusted by two. *

* This method is typically used to subtract complex period instances. * Subtracting one field is best achieved using methods * like {@link #minusYears(int)}. *

* If the amount is zero or null, then this is returned. * This datetime instance is immutable and unaffected by this method call. * * @param period the period to reduce this instant by * @return a copy of this datetime with the period taken away * @throws ArithmeticException if the new datetime exceeds the capacity of a long */ public DateTime minus(ReadablePeriod period) { return withPeriodAdded(period, -1); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime minus the specified number of years. *

* The calculation will do its best to only change the year field * retaining the same month of year. * However, in certain circumstances, it may be necessary to alter * smaller fields. For example, 2008-02-29 minus one year cannot result * in 2007-02-29, so the day of month is adjusted to 2007-02-28. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusYears(6);
     * DateTime subtracted = dt.minus(Period.years(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.years(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param years the amount of years to subtract, may be negative * @return the new datetime minus the increased years * @since 1.1 */ public DateTime minusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().subtract(getMillis(), years); return withMillis(instant); } /** * Returns a copy of this datetime minus the specified number of months. *

* The calculation will do its best to only change the month field * retaining the same day of month. * However, in certain circumstances, it may be necessary to alter * smaller fields. For example, 2007-05-31 minus one month cannot result * in 2007-04-31, so the day of month is adjusted to 2007-04-30. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusMonths(6);
     * DateTime subtracted = dt.minus(Period.months(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.months(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param months the amount of months to subtract, may be negative * @return the new datetime minus the increased months * @since 1.1 */ public DateTime minusMonths(int months) { if (months == 0) { return this; } long instant = getChronology().months().subtract(getMillis(), months); return withMillis(instant); } /** * Returns a copy of this datetime minus the specified number of weeks. *

* The calculation operates as if it were subtracting the equivalent in days. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusWeeks(6);
     * DateTime subtracted = dt.minus(Period.weeks(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.weeks(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to subtract, may be negative * @return the new datetime minus the increased weeks * @since 1.1 */ public DateTime minusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().subtract(getMillis(), weeks); return withMillis(instant); } /** * Returns a copy of this datetime minus the specified number of days. *

* The calculation will do its best to only change the day field * retaining the same time of day. * However, in certain circumstances, typically daylight savings cutover, * it may be necessary to alter the time fields. *

* In spring an hour is typically removed. If subtracting one day results * in the time being within the cutover then the time is adjusted to be * within summer time. For example, if the cutover is from 01:59 to 03:00 * and the result of this method would have been 02:30, then the result * will be adjusted to 03:30. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusDays(6);
     * DateTime subtracted = dt.minus(Period.days(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.days(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param days the amount of days to subtract, may be negative * @return the new datetime minus the increased days * @since 1.1 */ public DateTime minusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().subtract(getMillis(), days); return withMillis(instant); } /** * Returns a copy of this datetime minus the specified number of hours. *

* The calculation will subtract a duration equivalent to the number of * hours expressed in milliseconds. *

* For example, if a spring daylight savings cutover is from 01:59 to 03:00 * then subtracting one hour from 03:30 will result in 01:30. This is a * duration of one hour earlier, even though the hour field value changed * from 3 to 1. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusHours(6);
     * DateTime subtracted = dt.minus(Period.hours(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.hours(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param hours the amount of hours to subtract, may be negative * @return the new datetime minus the increased hours * @since 1.1 */ public DateTime minusHours(int hours) { if (hours == 0) { return this; } long instant = getChronology().hours().subtract(getMillis(), hours); return withMillis(instant); } /** * Returns a copy of this datetime minus the specified number of minutes. *

* The calculation will subtract a duration equivalent to the number of * minutes expressed in milliseconds. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusMinutes(6);
     * DateTime subtracted = dt.minus(Period.minutes(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.minutes(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to subtract, may be negative * @return the new datetime minus the increased minutes * @since 1.1 */ public DateTime minusMinutes(int minutes) { if (minutes == 0) { return this; } long instant = getChronology().minutes().subtract(getMillis(), minutes); return withMillis(instant); } /** * Returns a copy of this datetime minus the specified number of seconds. *

* The calculation will subtract a duration equivalent to the number of * seconds expressed in milliseconds. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusSeconds(6);
     * DateTime subtracted = dt.minus(Period.seconds(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.seconds(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to subtract, may be negative * @return the new datetime minus the increased seconds * @since 1.1 */ public DateTime minusSeconds(int seconds) { if (seconds == 0) { return this; } long instant = getChronology().seconds().subtract(getMillis(), seconds); return withMillis(instant); } /** * Returns a copy of this datetime minus the specified number of millis. *

* The calculation will subtract a duration equivalent to the number of * milliseconds. *

* The following three lines are identical in effect: *

     * DateTime subtracted = dt.minusMillis(6);
     * DateTime subtracted = dt.minus(Period.millis(6));
     * DateTime subtracted = dt.withFieldAdded(DurationFieldType.millis(), -6);
     * 
*

* This datetime instance is immutable and unaffected by this method call. * * @param millis the amount of millis to subtract, may be negative * @return the new datetime minus the increased millis * @since 1.1 */ public DateTime minusMillis(int millis) { if (millis == 0) { return this; } long instant = getChronology().millis().subtract(getMillis(), millis); return withMillis(instant); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains many useful methods. * * @param type the field type to get the chronology for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported */ public Property property(DateTimeFieldType type) { if (type == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } DateTimeField field = type.getField(getChronology()); if (field.isSupported() == false) { throw new IllegalArgumentException("Field '" + type + "' is not supported"); } return new Property(this, field); } //----------------------------------------------------------------------- /** * Converts this object to a DateMidnight using the * same millis and chronology. * * @return a DateMidnight using the same millis and chronology * @deprecated DateMidnight is deprecated */ @Deprecated public DateMidnight toDateMidnight() { return new DateMidnight(getMillis(), getChronology()); } /** * Converts this object to a YearMonthDay using the * same millis and chronology. * * @return a YearMonthDay using the same millis and chronology * @deprecated Use LocalDate instead of YearMonthDay */ @Deprecated public YearMonthDay toYearMonthDay() { return new YearMonthDay(getMillis(), getChronology()); } /** * Converts this object to a TimeOfDay using the * same millis and chronology. * * @return a TimeOfDay using the same millis and chronology * @deprecated Use LocalTime instead of TimeOfDay */ @Deprecated public TimeOfDay toTimeOfDay() { return new TimeOfDay(getMillis(), getChronology()); } /** * Converts this object to a LocalDateTime with * the same datetime and chronology. * * @return a LocalDateTime with the same datetime and chronology * @since 1.3 */ public LocalDateTime toLocalDateTime() { return new LocalDateTime(getMillis(), getChronology()); } /** * Converts this object to a LocalDate with the * same date and chronology. * * @return a LocalDate with the same date and chronology * @since 1.3 */ public LocalDate toLocalDate() { return new LocalDate(getMillis(), getChronology()); } /** * Converts this object to a LocalTime with the * same time and chronology. * * @return a LocalTime with the same time and chronology * @since 1.3 */ public LocalTime toLocalTime() { return new LocalTime(getMillis(), getChronology()); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the era field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * era changed. * * @param era the era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withEra(int era) { return withMillis(getChronology().era().set(getMillis(), era)); } /** * Returns a copy of this datetime with the century of era field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * century of era changed. * * @param centuryOfEra the centurey of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withCenturyOfEra(int centuryOfEra) { return withMillis(getChronology().centuryOfEra().set(getMillis(), centuryOfEra)); } /** * Returns a copy of this datetime with the year of era field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of era changed. * * @param yearOfEra the year of era to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withYearOfEra(int yearOfEra) { return withMillis(getChronology().yearOfEra().set(getMillis(), yearOfEra)); } /** * Returns a copy of this datetime with the year of century field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year of century changed. * * @param yearOfCentury the year of century to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withYearOfCentury(int yearOfCentury) { return withMillis(getChronology().yearOfCentury().set(getMillis(), yearOfCentury)); } /** * Returns a copy of this datetime with the year field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * year changed. * * @param year the year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withYear(int year) { return withMillis(getChronology().year().set(getMillis(), year)); } /** * Returns a copy of this datetime with the weekyear field updated. *

* The weekyear is the year that matches with the weekOfWeekyear field. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. * The weekyear allows you to query the effective year for that day. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * weekyear changed. * * @param weekyear the weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withWeekyear(int weekyear) { return withMillis(getChronology().weekyear().set(getMillis(), weekyear)); } /** * Returns a copy of this datetime with the month of year field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * month of year changed. * * @param monthOfYear the month of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withMonthOfYear(int monthOfYear) { return withMillis(getChronology().monthOfYear().set(getMillis(), monthOfYear)); } /** * Returns a copy of this datetime with the week of weekyear field updated. *

* This field is associated with the "weekyear" via {@link #withWeekyear(int)}. * In the standard ISO8601 week algorithm, the first week of the year * is that in which at least 4 days are in the year. As a result of this * definition, day 1 of the first week may be in the previous year. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * week of weekyear changed. * * @param weekOfWeekyear the week of weekyear to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withWeekOfWeekyear(int weekOfWeekyear) { return withMillis(getChronology().weekOfWeekyear().set(getMillis(), weekOfWeekyear)); } /** * Returns a copy of this datetime with the day of year field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of year changed. * * @param dayOfYear the day of year to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withDayOfYear(int dayOfYear) { return withMillis(getChronology().dayOfYear().set(getMillis(), dayOfYear)); } /** * Returns a copy of this datetime with the day of month field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of month changed. * * @param dayOfMonth the day of month to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withDayOfMonth(int dayOfMonth) { return withMillis(getChronology().dayOfMonth().set(getMillis(), dayOfMonth)); } /** * Returns a copy of this datetime with the day of week field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * day of week changed. * * @param dayOfWeek the day of week to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withDayOfWeek(int dayOfWeek) { return withMillis(getChronology().dayOfWeek().set(getMillis(), dayOfWeek)); } //----------------------------------------------------------------------- /** * Returns a copy of this datetime with the hour of day field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * hour of day changed. * * @param hour the hour of day to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withHourOfDay(int hour) { return withMillis(getChronology().hourOfDay().set(getMillis(), hour)); } /** * Returns a copy of this datetime with the minute of hour updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * minute of hour changed. * * @param minute the minute of hour to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withMinuteOfHour(int minute) { return withMillis(getChronology().minuteOfHour().set(getMillis(), minute)); } /** * Returns a copy of this datetime with the second of minute field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * second of minute changed. * * @param second the second of minute to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withSecondOfMinute(int second) { return withMillis(getChronology().secondOfMinute().set(getMillis(), second)); } /** * Returns a copy of this datetime with the millis of second field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * millis of second changed. * * @param millis the millis of second to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withMillisOfSecond(int millis) { return withMillis(getChronology().millisOfSecond().set(getMillis(), millis)); } /** * Returns a copy of this datetime with the millis of day field updated. *

* DateTime is immutable, so there are no set methods. * Instead, this method returns a new instance with the value of * millis of day changed. * * @param millis the millis of day to set * @return a copy of this object with the field set * @throws IllegalArgumentException if the value is invalid * @since 1.3 */ public DateTime withMillisOfDay(int millis) { return withMillis(getChronology().millisOfDay().set(getMillis(), millis)); } // Date properties //----------------------------------------------------------------------- /** * Get the era property which provides access to advanced functionality. * * @return the era property */ public Property era() { return new Property(this, getChronology().era()); } /** * Get the century of era property which provides access to advanced functionality. * * @return the year of era property */ public Property centuryOfEra() { return new Property(this, getChronology().centuryOfEra()); } /** * Get the year of century property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfCentury() { return new Property(this, getChronology().yearOfCentury()); } /** * Get the year of era property which provides access to advanced functionality. * * @return the year of era property */ public Property yearOfEra() { return new Property(this, getChronology().yearOfEra()); } /** * Get the year property which provides access to advanced functionality. * * @return the year property */ public Property year() { return new Property(this, getChronology().year()); } /** * Get the year of a week based year property which provides access to advanced functionality. * * @return the year of a week based year property */ public Property weekyear() { return new Property(this, getChronology().weekyear()); } /** * Get the month of year property which provides access to advanced functionality. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, getChronology().monthOfYear()); } /** * Get the week of a week based year property which provides access to advanced functionality. * * @return the week of a week based year property */ public Property weekOfWeekyear() { return new Property(this, getChronology().weekOfWeekyear()); } /** * Get the day of year property which provides access to advanced functionality. * * @return the day of year property */ public Property dayOfYear() { return new Property(this, getChronology().dayOfYear()); } /** * Get the day of month property which provides access to advanced functionality. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, getChronology().dayOfMonth()); } /** * Get the day of week property which provides access to advanced functionality. * * @return the day of week property */ public Property dayOfWeek() { return new Property(this, getChronology().dayOfWeek()); } // Time properties //----------------------------------------------------------------------- /** * Get the hour of day field property which provides access to advanced functionality. * * @return the hour of day property */ public Property hourOfDay() { return new Property(this, getChronology().hourOfDay()); } /** * Get the minute of day property which provides access to advanced functionality. * * @return the minute of day property */ public Property minuteOfDay() { return new Property(this, getChronology().minuteOfDay()); } /** * Get the minute of hour field property which provides access to advanced functionality. * * @return the minute of hour property */ public Property minuteOfHour() { return new Property(this, getChronology().minuteOfHour()); } /** * Get the second of day property which provides access to advanced functionality. * * @return the second of day property */ public Property secondOfDay() { return new Property(this, getChronology().secondOfDay()); } /** * Get the second of minute field property which provides access to advanced functionality. * * @return the second of minute property */ public Property secondOfMinute() { return new Property(this, getChronology().secondOfMinute()); } /** * Get the millis of day property which provides access to advanced functionality. * * @return the millis of day property */ public Property millisOfDay() { return new Property(this, getChronology().millisOfDay()); } /** * Get the millis of second property which provides access to advanced functionality. * * @return the millis of second property */ public Property millisOfSecond() { return new Property(this, getChronology().millisOfSecond()); } //----------------------------------------------------------------------- /** * DateTime.Property binds a DateTime to a DateTimeField allowing powerful * datetime functionality to be easily accessed. *

* The simplest use of this class is as an alternative get method, here used to * get the year '1972' (as an int) and the month 'December' (as a String). *

     * DateTime dt = new DateTime(1972, 12, 3, 0, 0, 0, 0);
     * int year = dt.year().get();
     * String monthStr = dt.month().getAsText();
     * 
*

* Methods are also provided that allow date modification. These return new instances * of DateTime - they do not modify the original. The example below yields two * independent immutable date objects 20 years apart. *

     * DateTime dt = new DateTime(1972, 12, 3, 0, 0, 0, 0);
     * DateTime dt20 = dt.year().addToCopy(20);
     * 
* Serious modification of dates (ie. more than just changing one or two fields) * should use the {@link org.joda.time.MutableDateTime MutableDateTime} class. *

* DateTime.Propery itself is thread-safe and immutable, as well as the * DateTime being operated on. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization version */ private static final long serialVersionUID = -6983323811635733510L; /** The instant this property is working against */ private DateTime iInstant; /** The field this property is working against */ private DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(DateTime instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Writes the property in a safe serialization format. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(iInstant); oos.writeObject(iField.getType()); } /** * Reads the property from a safe serialization format. */ private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException { iInstant = (DateTime) oos.readObject(); DateTimeFieldType type = (DateTimeFieldType) oos.readObject(); iField = type.getField(iInstant.getChronology()); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the milliseconds of the datetime that this property is linked to. * * @return the milliseconds */ protected long getMillis() { return iInstant.getMillis(); } /** * Gets the chronology of the datetime that this property is linked to. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { return iInstant.getChronology(); } /** * Gets the datetime being used. * * @return the datetime */ public DateTime getDateTime() { return iInstant; } //----------------------------------------------------------------------- /** * Adds to this field in a copy of this DateTime. *

* The DateTime attached to this property is unchanged by this call. * This operation is faster than converting a DateTime to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to add to the field in the copy * @return a copy of the DateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateTime addToCopy(int value) { return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); } /** * Adds to this field in a copy of this DateTime. *

* The DateTime attached to this property is unchanged by this call. * This operation is faster than converting a DateTime to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to add to the field in the copy * @return a copy of the DateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateTime addToCopy(long value) { return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); } /** * Adds to this field, possibly wrapped, in a copy of this DateTime. * A wrapped operation only changes this field. * Thus 31st January addWrapField one day goes to the 1st January. *

* The DateTime attached to this property is unchanged by this call. * This operation is faster than converting a DateTime to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to add to the field in the copy * @return a copy of the DateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateTime addWrapFieldToCopy(int value) { return iInstant.withMillis(iField.addWrapField(iInstant.getMillis(), value)); } //----------------------------------------------------------------------- /** * Sets this field in a copy of the DateTime. *

* The DateTime attached to this property is unchanged by this call. * This operation is faster than converting a DateTime to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param value the value to set the field in the copy to * @return a copy of the DateTime with the field value changed * @throws IllegalArgumentException if the value isn't valid */ public DateTime setCopy(int value) { return iInstant.withMillis(iField.set(iInstant.getMillis(), value)); } /** * Sets this field in a copy of the DateTime to a parsed text value. *

* The DateTime attached to this property is unchanged by this call. * This operation is faster than converting a DateTime to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return a copy of the DateTime with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public DateTime setCopy(String text, Locale locale) { return iInstant.withMillis(iField.set(iInstant.getMillis(), text, locale)); } /** * Sets this field in a copy of the DateTime to a parsed text value. *

* The DateTime attached to this property is unchanged by this call. * This operation is faster than converting a DateTime to a MutableDateTime * and back again when setting one field. When setting multiple fields, * it is generally quicker to make the conversion to MutableDateTime. * * @param text the text value to set * @return a copy of the DateTime with the field value changed * @throws IllegalArgumentException if the text value isn't valid */ public DateTime setCopy(String text) { return setCopy(text, null); } //----------------------------------------------------------------------- /** * Returns a new DateTime with this field set to the maximum value * for this field. *

* This operation is useful for obtaining a DateTime on the last day * of the month, as month lengths vary. *

         * DateTime lastDayOfMonth = dt.dayOfMonth().withMaximumValue();
         * 
*

* Where possible, the offset from UTC will be retained, thus applications * may need to call {@link DateTime#withLaterOffsetAtOverlap()} on the result * to force the later time during a DST overlap if desired. *

* From v2.2, this method handles a daylight svaings time gap, setting the * time to the last instant before the gap. *

* The DateTime attached to this property is unchanged by this call. * * @return a copy of the DateTime with this field set to its maximum * @since 1.2 */ public DateTime withMaximumValue() { try { return setCopy(getMaximumValue()); } catch (RuntimeException ex) { if (IllegalInstantException.isIllegalInstant(ex)) { // adding MILLIS_PER_DAY is not perfect, but will work in almost all situations long beforeGap = getChronology().getZone().previousTransition(getMillis() + DateTimeConstants.MILLIS_PER_DAY); return new DateTime(beforeGap, getChronology()); } throw ex; } } /** * Returns a new DateTime with this field set to the minimum value * for this field. *

* Where possible, the offset from UTC will be retained, thus applications * may need to call {@link DateTime#withEarlierOffsetAtOverlap()} on the result * to force the earlier time during a DST overlap if desired. *

* From v2.2, this method handles a daylight svaings time gap, setting the * time to the first instant after the gap. *

* The DateTime attached to this property is unchanged by this call. * * @return a copy of the DateTime with this field set to its minimum * @since 1.2 */ public DateTime withMinimumValue() { try { return setCopy(getMinimumValue()); } catch (RuntimeException ex) { if (IllegalInstantException.isIllegalInstant(ex)) { // subtracting MILLIS_PER_DAY is not perfect, but will work in almost all situations long afterGap = getChronology().getZone().nextTransition(getMillis() - DateTimeConstants.MILLIS_PER_DAY); return new DateTime(afterGap, getChronology()); } throw ex; } } //----------------------------------------------------------------------- /** * Rounds to the lowest whole unit of this field on a copy of this DateTime. * * @return a copy of the DateTime with the field value changed */ public DateTime roundFloorCopy() { return iInstant.withMillis(iField.roundFloor(iInstant.getMillis())); } /** * Rounds to the highest whole unit of this field on a copy of this DateTime. * * @return a copy of the DateTime with the field value changed */ public DateTime roundCeilingCopy() { return iInstant.withMillis(iField.roundCeiling(iInstant.getMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this DateTime, * favoring the floor if halfway. * * @return a copy of the DateTime with the field value changed */ public DateTime roundHalfFloorCopy() { return iInstant.withMillis(iField.roundHalfFloor(iInstant.getMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this DateTime, * favoring the ceiling if halfway. * * @return a copy of the DateTime with the field value changed */ public DateTime roundHalfCeilingCopy() { return iInstant.withMillis(iField.roundHalfCeiling(iInstant.getMillis())); } /** * Rounds to the nearest whole unit of this field on a copy of this * DateTime. If halfway, the ceiling is favored over the floor only if * it makes this field's value even. * * @return a copy of the DateTime with the field value changed */ public DateTime roundHalfEvenCopy() { return iInstant.withMillis(iField.roundHalfEven(iInstant.getMillis())); } } } joda-time-2.3/src/main/java/org/joda/time/ReadablePartial.java0000644000175000017500000001547311567200522023546 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines a partial time that does not support every datetime field, and is * thus a local time. *

* A {@code ReadablePartial} supports a subset of those fields on the chronology. * It cannot be compared to a {@code ReadableInstant}, as it does not fully * specify an instant in time. The time it does specify is a local time, and does * not include a time zone. *

* A {@code ReadablePartial} can be converted to a {@code ReadableInstant} * using the {@code toDateTime} method. This works by providing a full base * instant that can be used to 'fill in the gaps' and specify a time zone. *

* {@code ReadablePartial} is {@code Comparable} from v2.0. * The comparison is based on the fields, compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. * * @author Stephen Colebourne * @since 1.0 */ public interface ReadablePartial extends Comparable { /** * Gets the number of fields that this partial supports. * * @return the number of fields supported */ int size(); /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeFieldType getFieldType(int index); /** * Gets the field at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeField getField(int index); /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value of the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ int getValue(int index); /** * Gets the chronology of the partial which is never null. *

* The {@link Chronology} is the calculation engine behind the partial and * provides conversion and validation of the fields in a particular calendar system. * * @return the chronology, never null */ Chronology getChronology(); /** * Gets the value of one of the fields. *

* The field type specified must be one of those that is supported by the partial. * * @param field a DateTimeFieldType instance that is supported by this partial * @return the value of that field * @throws IllegalArgumentException if the field is null or not supported */ int get(DateTimeFieldType field); /** * Checks whether the field type specified is supported by this partial. * * @param field the field to check, may be null which returns false * @return true if the field is supported */ boolean isSupported(DateTimeFieldType field); /** * Converts this partial to a full datetime by resolving it against another * datetime. *

* This method takes the specified datetime and sets the fields from this * instant on top. The chronology from the base instant is used. *

* For example, if this partial represents a time, then the result of this * method will be the datetime from the specified base instant plus the * time from this partial. * * @param baseInstant the instant that provides the missing fields, null means now * @return the combined datetime */ DateTime toDateTime(ReadableInstant baseInstant); //----------------------------------------------------------------------- /** * Compares this partial with the specified object for equality based * on the supported fields, chronology and values. *

* Two instances of ReadablePartial are equal if they have the same * chronology, same field types (in same order) and same values. * * @param partial the object to compare to * @return true if equal */ boolean equals(Object partial); /** * Gets a hash code for the partial that is compatible with the * equals method. *

* The formula used must be: *

     *  int total = 157;
     *  for (int i = 0; i < fields.length; i++) {
     *      total = 23 * total + values[i];
     *      total = 23 * total + fieldTypes[i].hashCode();
     *  }
     *  total += chronology.hashCode();
     *  return total;
     * 
* * @return a suitable hash code */ int hashCode(); //----------------------------------------------------------------------- // This is commented out to improve backwards compatibility // /** // * Compares this partial with another returning an integer // * indicating the order. // *

// * The fields are compared in order, from largest to smallest. // * The first field that is non-equal is used to determine the result. // * Thus a year-hour partial will first be compared on the year, and then // * on the hour. // *

// * The specified object must be a partial instance whose field types // * match those of this partial. If the partial instance has different // * fields then a {@code ClassCastException} is thrown. // * // * @param partial an object to check against // * @return negative if this is less, zero if equal, positive if greater // * @throws ClassCastException if the partial is the wrong class // * or if it has field types that don't match // * @throws NullPointerException if the partial is null // * @since 2.0, previously on {@code AbstractPartial} // */ // int compareTo(ReadablePartial partial); //----------------------------------------------------------------------- /** * Get the value as a String in a recognisable ISO8601 format, only * displaying supported fields. *

* The string output is in ISO8601 format to enable the String * constructor to correctly parse it. * * @return the value as an ISO8601 string */ String toString(); } joda-time-2.3/src/main/java/org/joda/time/ReadWritableInterval.java0000644000175000017500000001164411564251363024606 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Writable interface for an interval. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public interface ReadWritableInterval extends ReadableInterval { /** * Sets this interval from two millisecond instants. * * @param startInstant the start of the time interval * @param endInstant the start of the time interval * @throws IllegalArgumentException if the end is before the start */ void setInterval(long startInstant, long endInstant); /** * Sets this interval to be the same as another. * * @param interval the interval to copy * @throws IllegalArgumentException if the end is before the start */ void setInterval(ReadableInterval interval); /** * Sets this interval from two instants. * * @param startInstant the start of the time interval * @param endInstant the start of the time interval * @throws IllegalArgumentException if the end is before the start */ void setInterval(ReadableInstant startInstant, ReadableInstant endInstant); //----------------------------------------------------------------------- /** * Sets the chronology of this time interval. * * @param chrono the chronology to use, null means ISO default */ void setChronology(Chronology chrono); //----------------------------------------------------------------------- /** * Sets the start of this time interval. * * @param millisInstant the start of the time interval, * millisecond instant from 1970-01-01T00:00:00Z * @throws IllegalArgumentException if the end is before the start */ void setStartMillis(long millisInstant); /** * Sets the start of this time interval as an Instant. * * @param instant the start of the time interval * @throws IllegalArgumentException if the end is before the start */ void setStart(ReadableInstant instant); //----------------------------------------------------------------------- /** * Sets the end of this time interval. * * @param millisInstant the end of the time interval, * millisecond instant from 1970-01-01T00:00:00Z * @throws IllegalArgumentException if the end is before the start */ void setEndMillis(long millisInstant); /** * Sets the end of this time interval as an Instant. * * @param instant the end of the time interval * @throws IllegalArgumentException if the end is before the start */ void setEnd(ReadableInstant instant); //----------------------------------------------------------------------- /** * Sets the duration of this time interval, preserving the start instant. * * @param duration new duration for interval * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ void setDurationAfterStart(ReadableDuration duration); /** * Sets the duration of this time interval, preserving the end instant. * * @param duration new duration for interval * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ void setDurationBeforeEnd(ReadableDuration duration); //----------------------------------------------------------------------- /** * Sets the period of this time interval, preserving the start instant. * * @param period new period for interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ void setPeriodAfterStart(ReadablePeriod period); /** * Sets the period of this time interval, preserving the end instant. * * @param period new period for interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ void setPeriodBeforeEnd(ReadablePeriod period); } joda-time-2.3/src/main/java/org/joda/time/ReadableInterval.java0000644000175000017500000003042411564251363023735 0ustar ebourgebourg/* * Copyright 2001-2006 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Readable interface for an interval of time between two instants. *

* A time interval represents a period of time between two instants. * Intervals are inclusive of the start instant and exclusive of the end. * The end instant is always greater than or equal to the start instant. *

* Intervals have a fixed millisecond duration. * This is the difference between the start and end instants. * The duration is represented separately by {@link ReadableDuration}. * As a result, intervals are not comparable. * To compare the length of two intervals, you should compare their durations. *

* An interval can also be converted to a {@link ReadablePeriod}. * This represents the difference between the start and end points in terms of fields * such as years and days. *

* Methods that are passed an interval as a parameter will treat null * as a zero length interval at the current instant in time. * * @author Sean Geoghegan * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public interface ReadableInterval { /** * Gets the chronology of the interval, which is the chronology of the first datetime. * * @return the chronology of the interval */ Chronology getChronology(); /** * Gets the start of this time interval which is inclusive. * * @return the start of the time interval, * millisecond instant from 1970-01-01T00:00:00Z */ long getStartMillis(); /** * Gets the start of this time interval, which is inclusive, as a DateTime. * * @return the start of the time interval */ DateTime getStart(); /** * Gets the end of this time interval which is exclusive. * * @return the end of the time interval, * millisecond instant from 1970-01-01T00:00:00Z */ long getEndMillis(); /** * Gets the end of this time interval, which is exclusive, as a DateTime. * * @return the end of the time interval */ DateTime getEnd(); //----------------------------------------------------------------------- /** * Does this time interval contain the specified instant. *

* Non-zero duration intervals are inclusive of the start instant and * exclusive of the end. A zero duration interval cannot contain anything. *

* For example: *

     * [09:00 to 10:00) contains 08:59  = false (before start)
     * [09:00 to 10:00) contains 09:00  = true
     * [09:00 to 10:00) contains 09:59  = true
     * [09:00 to 10:00) contains 10:00  = false (equals end)
     * [09:00 to 10:00) contains 10:01  = false (after end)
     * 
     * [14:00 to 14:00) contains 14:00  = false (zero duration contains nothing)
     * 
* * @param instant the instant, null means now * @return true if this time interval contains the instant */ boolean contains(ReadableInstant instant); /** * Does this time interval contain the specified time interval. *

* Non-zero duration intervals are inclusive of the start instant and * exclusive of the end. The other interval is contained if this interval * wholly contains, starts, finishes or equals it. * A zero duration interval cannot contain anything. *

* When two intervals are compared the result is one of three states: * (a) they abut, (b) there is a gap between them, (c) they overlap. * The contains method is not related to these states. * In particular, a zero duration interval is contained at the start of * a larger interval, but does not overlap (it abuts instead). *

* For example: *

     * [09:00 to 10:00) contains [09:00 to 10:00)  = true
     * [09:00 to 10:00) contains [09:00 to 09:30)  = true
     * [09:00 to 10:00) contains [09:30 to 10:00)  = true
     * [09:00 to 10:00) contains [09:15 to 09:45)  = true
     * [09:00 to 10:00) contains [09:00 to 09:00)  = true
     * 
     * [09:00 to 10:00) contains [08:59 to 10:00)  = false (otherStart before thisStart)
     * [09:00 to 10:00) contains [09:00 to 10:01)  = false (otherEnd after thisEnd)
     * [09:00 to 10:00) contains [10:00 to 10:00)  = false (otherStart equals thisEnd)
     * 
     * [14:00 to 14:00) contains [14:00 to 14:00)  = false (zero duration contains nothing)
     * 
* * @param interval the time interval to compare to, null means a zero duration interval now * @return true if this time interval contains the time interval */ boolean contains(ReadableInterval interval); /** * Does this time interval overlap the specified time interval. *

* Intervals are inclusive of the start instant and exclusive of the end. * An interval overlaps another if it shares some common part of the * datetime continuum. *

* When two intervals are compared the result is one of three states: * (a) they abut, (b) there is a gap between them, (c) they overlap. * The abuts state takes precedence over the other two, thus a zero duration * interval at the start of a larger interval abuts and does not overlap. *

* For example: *

     * [09:00 to 10:00) overlaps [08:00 to 08:30)  = false (completely before)
     * [09:00 to 10:00) overlaps [08:00 to 09:00)  = false (abuts before)
     * [09:00 to 10:00) overlaps [08:00 to 09:30)  = true
     * [09:00 to 10:00) overlaps [08:00 to 10:00)  = true
     * [09:00 to 10:00) overlaps [08:00 to 11:00)  = true
     * 
     * [09:00 to 10:00) overlaps [09:00 to 09:00)  = false (abuts before)
     * [09:00 to 10:00) overlaps [09:00 to 09:30)  = true
     * [09:00 to 10:00) overlaps [09:00 to 10:00)  = true
     * [09:00 to 10:00) overlaps [09:00 to 11:00)  = true
     * 
     * [09:00 to 10:00) overlaps [09:30 to 09:30)  = true
     * [09:00 to 10:00) overlaps [09:30 to 10:00)  = true
     * [09:00 to 10:00) overlaps [09:30 to 11:00)  = true
     * 
     * [09:00 to 10:00) overlaps [10:00 to 10:00)  = false (abuts after)
     * [09:00 to 10:00) overlaps [10:00 to 11:00)  = false (abuts after)
     * 
     * [09:00 to 10:00) overlaps [10:30 to 11:00)  = false (completely after)
     * 
     * [14:00 to 14:00) overlaps [14:00 to 14:00)  = false (abuts before and after)
     * [14:00 to 14:00) overlaps [13:00 to 15:00)  = true
     * 
* * @param interval the time interval to compare to, null means a zero length interval now * @return true if the time intervals overlap */ boolean overlaps(ReadableInterval interval); //----------------------------------------------------------------------- /** * Is this time interval after the specified instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param instant the instant to compare to, null means now * @return true if this time interval is after the instant */ boolean isAfter(ReadableInstant instant); /** * Is this time interval entirely after the specified interval. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param interval the interval to compare to, null means now * @return true if this time interval is after the interval specified */ boolean isAfter(ReadableInterval interval); /** * Is this time interval before the specified instant. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param instant the instant to compare to, null means now * @return true if this time interval is before the instant */ boolean isBefore(ReadableInstant instant); /** * Is this time interval entirely before the specified interval. *

* Intervals are inclusive of the start instant and exclusive of the end. * * @param interval the interval to compare to, null means now * @return true if this time interval is before the interval specified */ boolean isBefore(ReadableInterval interval); //----------------------------------------------------------------------- /** * Get this interval as an immutable Interval object. *

* This will either typecast this instance, or create a new Interval. * * @return the interval as an Interval object */ Interval toInterval(); /** * Get this time interval as a MutableInterval. *

* This will always return a new MutableInterval with the same interval. * * @return the time interval as a MutableInterval object */ MutableInterval toMutableInterval(); //----------------------------------------------------------------------- /** * Gets the millisecond duration of this time interval. * * @return the millisecond duration of the time interval * @throws ArithmeticException if the duration exceeds the capacity of a long */ Duration toDuration(); /** * Gets the millisecond duration of this time interval. * * @return the millisecond duration of the time interval * @throws ArithmeticException if the duration exceeds the capacity of a long */ long toDurationMillis(); /** * Converts the duration of the interval to a period using the * standard period type. *

* This method should be used to exract the field values describing the * difference between the start and end instants. * * @return a time period derived from the interval */ Period toPeriod(); /** * Converts the duration of the interval to a period using the * specified period type. *

* This method should be used to exract the field values describing the * difference between the start and end instants. * * @param type the requested type of the duration, null means standard * @return a time period derived from the interval */ Period toPeriod(PeriodType type); //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on start and end millis plus the chronology. * All ReadableInterval instances are accepted. *

* To compare the duration of two time intervals, use {@link #toDuration()} * to get the durations and compare those. * * @param readableInterval a readable interval to check against * @return true if the start and end millis are equal */ boolean equals(Object readableInterval); /** * Gets a hash code for the time interval that is compatable with the * equals method. *

* The formula used must be as follows: *

int result = 97;
     * result = 31 * result + ((int) (getStartMillis() ^ (getStartMillis() >>> 32)));
     * result = 31 * result + ((int) (getEndMillis() ^ (getEndMillis() >>> 32)));
     * result = 31 * result + getChronology().hashCode();
     * return result;
* * @return a hash code */ int hashCode(); //----------------------------------------------------------------------- /** * Get the value as a String in the ISO8601 interval format. *

* For example, "2004-06-09T12:30:00.000/2004-07-10T13:30:00.000". * * @return the value as an ISO8601 string */ String toString(); } joda-time-2.3/src/main/java/org/joda/time/DateTimeZone.java0000644000175000017500000014771112203434612023060 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.chrono.BaseChronology; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import org.joda.time.format.FormatUtils; import org.joda.time.tz.DefaultNameProvider; import org.joda.time.tz.FixedDateTimeZone; import org.joda.time.tz.NameProvider; import org.joda.time.tz.Provider; import org.joda.time.tz.UTCProvider; import org.joda.time.tz.ZoneInfoProvider; /** * DateTimeZone represents a time zone. *

* A time zone is a system of rules to convert time from one geographic * location to another. For example, Paris, France is one hour ahead of * London, England. Thus when it is 10:00 in London, it is 11:00 in Paris. *

* All time zone rules are expressed, for historical reasons, relative to * Greenwich, London. Local time in Greenwich is referred to as Greenwich Mean * Time (GMT). This is similar, but not precisely identical, to Universal * Coordinated Time, or UTC. This library only uses the term UTC. *

* Using this system, America/Los_Angeles is expressed as UTC-08:00, or UTC-07:00 * in the summer. The offset -08:00 indicates that America/Los_Angeles time is * obtained from UTC by adding -08:00, that is, by subtracting 8 hours. *

* The offset differs in the summer because of daylight saving time, or DST. * The following definitions of time are generally used: *

    *
  • UTC - The reference time. *
  • Standard Time - The local time without a daylight saving time offset. * For example, in Paris, standard time is UTC+01:00. *
  • Daylight Saving Time - The local time with a daylight saving time * offset. This offset is typically one hour, but not always. It is typically * used in most countries away from the equator. In Paris, daylight saving * time is UTC+02:00. *
  • Wall Time - This is what a local clock on the wall reads. This will be * either Standard Time or Daylight Saving Time depending on the time of year * and whether the location uses Daylight Saving Time. *
*

* Unlike the Java TimeZone class, DateTimeZone is immutable. It also only * supports long format time zone ids. Thus EST and ECT are not accepted. * However, the factory that accepts a TimeZone will attempt to convert from * the old short id to a suitable long id. *

* DateTimeZone is thread-safe and immutable, and all subclasses must be as * well. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class DateTimeZone implements Serializable { /** Serialization version. */ private static final long serialVersionUID = 5546345482340108586L; /** The time zone for Universal Coordinated Time */ public static final DateTimeZone UTC = new FixedDateTimeZone("UTC", "UTC", 0, 0); /** Maximum offset. */ private static final int MAX_MILLIS = (86400 * 1000) - 1; /** The instance that is providing time zones. */ private static Provider cProvider; /** The instance that is providing time zone names. */ private static NameProvider cNameProvider; /** The set of ID strings. */ private static Set cAvailableIDs; /** The default time zone. */ private static volatile DateTimeZone cDefault; /** A formatter for printing and parsing zones. */ private static DateTimeFormatter cOffsetFormatter; /** Cache that maps fixed offset strings to softly referenced DateTimeZones */ private static Map> iFixedOffsetCache; /** Cache of old zone IDs to new zone IDs */ private static Map cZoneIdConversion; static { setProvider0(null); setNameProvider0(null); } //----------------------------------------------------------------------- /** * Gets the default time zone. *

* The default time zone is derived from the system property {@code user.timezone}. * If that is {@code null} or is not a valid identifier, then the value of the * JDK {@code TimeZone} default is converted. If that fails, {@code UTC} is used. *

* NOTE: If the {@code java.util.TimeZone} default is updated after calling this * method, then the change will not be picked up here. * * @return the default datetime zone object */ public static DateTimeZone getDefault() { DateTimeZone zone = cDefault; if (zone == null) { synchronized(DateTimeZone.class) { zone = cDefault; if (zone == null) { DateTimeZone temp = null; try { try { String id = System.getProperty("user.timezone"); if (id != null) { // null check avoids stack overflow temp = forID(id); } } catch (RuntimeException ex) { // ignored } if (temp == null) { temp = forTimeZone(TimeZone.getDefault()); } } catch (IllegalArgumentException ex) { // ignored } if (temp == null) { temp = UTC; } cDefault = zone = temp; } } } return zone; } /** * Sets the default time zone. *

* NOTE: Calling this method does not set the {@code java.util.TimeZone} default. * * @param zone the default datetime zone object, must not be null * @throws IllegalArgumentException if the zone is null * @throws SecurityException if the application has insufficient security rights */ public static void setDefault(DateTimeZone zone) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("DateTimeZone.setDefault")); } if (zone == null) { throw new IllegalArgumentException("The datetime zone must not be null"); } synchronized(DateTimeZone.class) { cDefault = zone; } } //----------------------------------------------------------------------- /** * Gets a time zone instance for the specified time zone id. *

* The time zone id may be one of those returned by getAvailableIDs. * Short ids, as accepted by {@link java.util.TimeZone}, are not accepted. * All IDs must be specified in the long format. * The exception is UTC, which is an acceptable id. *

* Alternatively a locale independent, fixed offset, datetime zone can * be specified. The form [+-]hh:mm can be used. * * @param id the ID of the datetime zone, null means default * @return the DateTimeZone object for the ID * @throws IllegalArgumentException if the ID is not recognised */ @FromString public static DateTimeZone forID(String id) { if (id == null) { return getDefault(); } if (id.equals("UTC")) { return DateTimeZone.UTC; } DateTimeZone zone = cProvider.getZone(id); if (zone != null) { return zone; } if (id.startsWith("+") || id.startsWith("-")) { int offset = parseOffset(id); if (offset == 0L) { return DateTimeZone.UTC; } else { id = printOffset(offset); return fixedOffsetZone(id, offset); } } throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised"); } /** * Gets a time zone instance for the specified offset to UTC in hours. * This method assumes standard length hours. *

* This factory is a convenient way of constructing zones with a fixed offset. * * @param hoursOffset the offset in hours from UTC, from -23 to +23 * @return the DateTimeZone object for the offset * @throws IllegalArgumentException if the offset is too large or too small */ public static DateTimeZone forOffsetHours(int hoursOffset) throws IllegalArgumentException { return forOffsetHoursMinutes(hoursOffset, 0); } /** * Gets a time zone instance for the specified offset to UTC in hours and minutes. * This method assumes 60 minutes in an hour, and standard length minutes. *

* This factory is a convenient way of constructing zones with a fixed offset. * The hours value must be in the range -23 to +23. * The minutes value must be in the range -59 to +59. * The following combinations of sign for the hour and minute are possible: *

     *  Hour    Minute    Example    Result
     * 
     *  +ve     +ve       (2, 15)    +02:15
     *  +ve     zero      (2, 0)     +02:00
     *  +ve     -ve       (2, -15)   IllegalArgumentException
     * 
     *  zero    +ve       (0, 15)    +00:15
     *  zero    zero      (0, 0)     +00:00
     *  zero    -ve       (0, -15)   -00:15
     * 
     *  -ve     +ve       (-2, 15)   -02:15
     *  -ve     zero      (-2, 0)    -02:00
     *  -ve     -ve       (-2, -15)  -02:15
     * 
* Note that in versions before 2.3, the minutes had to be zero or positive. * * @param hoursOffset the offset in hours from UTC, from -23 to +23 * @param minutesOffset the offset in minutes from UTC, from -59 to +59 * @return the DateTimeZone object for the offset * @throws IllegalArgumentException if any value is out of range, the minutes are negative * when the hours are positive, or the resulting offset exceeds +/- 23:59:59.000 */ public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException { if (hoursOffset == 0 && minutesOffset == 0) { return DateTimeZone.UTC; } if (hoursOffset < -23 || hoursOffset > 23) { throw new IllegalArgumentException("Hours out of range: " + hoursOffset); } if (minutesOffset < -59 || minutesOffset > 59) { throw new IllegalArgumentException("Minutes out of range: " + minutesOffset); } if (hoursOffset > 0 && minutesOffset < 0) { throw new IllegalArgumentException("Positive hours must not have negative minutes: " + minutesOffset); } int offset = 0; try { int hoursInMinutes = hoursOffset * 60; if (hoursInMinutes < 0) { minutesOffset = hoursInMinutes - Math.abs(minutesOffset); } else { minutesOffset = hoursInMinutes + minutesOffset; } offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE); } catch (ArithmeticException ex) { throw new IllegalArgumentException("Offset is too large"); } return forOffsetMillis(offset); } /** * Gets a time zone instance for the specified offset to UTC in milliseconds. * * @param millisOffset the offset in millis from UTC, from -23:59:59.999 to +23:59:59.999 * @return the DateTimeZone object for the offset */ public static DateTimeZone forOffsetMillis(int millisOffset) { if (millisOffset < -MAX_MILLIS || millisOffset > MAX_MILLIS) { throw new IllegalArgumentException("Millis out of range: " + millisOffset); } String id = printOffset(millisOffset); return fixedOffsetZone(id, millisOffset); } /** * Gets a time zone instance for a JDK TimeZone. *

* DateTimeZone only accepts a subset of the IDs from TimeZone. The * excluded IDs are the short three letter form (except UTC). This * method will attempt to convert between time zones created using the * short IDs and the full version. *

* This method is not designed to parse time zones with rules created by * applications using SimpleTimeZone directly. * * @param zone the zone to convert, null means default * @return the DateTimeZone object for the zone * @throws IllegalArgumentException if the zone is not recognised */ public static DateTimeZone forTimeZone(TimeZone zone) { if (zone == null) { return getDefault(); } final String id = zone.getID(); if (id.equals("UTC")) { return DateTimeZone.UTC; } // Convert from old alias before consulting provider since they may differ. DateTimeZone dtz = null; String convId = getConvertedId(id); if (convId != null) { dtz = cProvider.getZone(convId); } if (dtz == null) { dtz = cProvider.getZone(id); } if (dtz != null) { return dtz; } // Support GMT+/-hh:mm formats if (convId == null) { convId = zone.getID(); if (convId.startsWith("GMT+") || convId.startsWith("GMT-")) { convId = convId.substring(3); int offset = parseOffset(convId); if (offset == 0L) { return DateTimeZone.UTC; } else { convId = printOffset(offset); return fixedOffsetZone(convId, offset); } } } throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised"); } //----------------------------------------------------------------------- /** * Gets the zone using a fixed offset amount. * * @param id the zone id * @param offset the offset in millis * @return the zone */ private static synchronized DateTimeZone fixedOffsetZone(String id, int offset) { if (offset == 0) { return DateTimeZone.UTC; } if (iFixedOffsetCache == null) { iFixedOffsetCache = new HashMap>(); } DateTimeZone zone; Reference ref = iFixedOffsetCache.get(id); if (ref != null) { zone = ref.get(); if (zone != null) { return zone; } } zone = new FixedDateTimeZone(id, null, offset, offset); iFixedOffsetCache.put(id, new SoftReference(zone)); return zone; } /** * Gets all the available IDs supported. * * @return an unmodifiable Set of String IDs */ public static Set getAvailableIDs() { return cAvailableIDs; } //----------------------------------------------------------------------- /** * Gets the zone provider factory. *

* The zone provider is a pluggable instance factory that supplies the * actual instances of DateTimeZone. * * @return the provider */ public static Provider getProvider() { return cProvider; } /** * Sets the zone provider factory. *

* The zone provider is a pluggable instance factory that supplies the * actual instances of DateTimeZone. * * @param provider provider to use, or null for default * @throws SecurityException if you do not have the permission DateTimeZone.setProvider * @throws IllegalArgumentException if the provider is invalid */ public static void setProvider(Provider provider) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("DateTimeZone.setProvider")); } setProvider0(provider); } /** * Sets the zone provider factory without performing the security check. * * @param provider provider to use, or null for default * @throws IllegalArgumentException if the provider is invalid */ private static void setProvider0(Provider provider) { if (provider == null) { provider = getDefaultProvider(); } Set ids = provider.getAvailableIDs(); if (ids == null || ids.size() == 0) { throw new IllegalArgumentException ("The provider doesn't have any available ids"); } if (!ids.contains("UTC")) { throw new IllegalArgumentException("The provider doesn't support UTC"); } if (!UTC.equals(provider.getZone("UTC"))) { throw new IllegalArgumentException("Invalid UTC zone provided"); } cProvider = provider; cAvailableIDs = ids; } /** * Gets the default zone provider. *

* Tries the system property org.joda.time.DateTimeZone.Provider. * Then tries a ZoneInfoProvider using the data in org/joda/time/tz/data. * Then uses UTCProvider. * * @return the default name provider */ private static Provider getDefaultProvider() { Provider provider = null; try { String providerClass = System.getProperty("org.joda.time.DateTimeZone.Provider"); if (providerClass != null) { try { provider = (Provider) Class.forName(providerClass).newInstance(); } catch (Exception ex) { Thread thread = Thread.currentThread(); thread.getThreadGroup().uncaughtException(thread, ex); } } } catch (SecurityException ex) { // ignored } if (provider == null) { try { provider = new ZoneInfoProvider("org/joda/time/tz/data"); } catch (Exception ex) { Thread thread = Thread.currentThread(); thread.getThreadGroup().uncaughtException(thread, ex); } } if (provider == null) { provider = new UTCProvider(); } return provider; } //----------------------------------------------------------------------- /** * Gets the name provider factory. *

* The name provider is a pluggable instance factory that supplies the * names of each DateTimeZone. * * @return the provider */ public static NameProvider getNameProvider() { return cNameProvider; } /** * Sets the name provider factory. *

* The name provider is a pluggable instance factory that supplies the * names of each DateTimeZone. * * @param nameProvider provider to use, or null for default * @throws SecurityException if you do not have the permission DateTimeZone.setNameProvider * @throws IllegalArgumentException if the provider is invalid */ public static void setNameProvider(NameProvider nameProvider) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("DateTimeZone.setNameProvider")); } setNameProvider0(nameProvider); } /** * Sets the name provider factory without performing the security check. * * @param nameProvider provider to use, or null for default * @throws IllegalArgumentException if the provider is invalid */ private static void setNameProvider0(NameProvider nameProvider) { if (nameProvider == null) { nameProvider = getDefaultNameProvider(); } cNameProvider = nameProvider; } /** * Gets the default name provider. *

* Tries the system property org.joda.time.DateTimeZone.NameProvider. * Then uses DefaultNameProvider. * * @return the default name provider */ private static NameProvider getDefaultNameProvider() { NameProvider nameProvider = null; try { String providerClass = System.getProperty("org.joda.time.DateTimeZone.NameProvider"); if (providerClass != null) { try { nameProvider = (NameProvider) Class.forName(providerClass).newInstance(); } catch (Exception ex) { Thread thread = Thread.currentThread(); thread.getThreadGroup().uncaughtException(thread, ex); } } } catch (SecurityException ex) { // ignore } if (nameProvider == null) { nameProvider = new DefaultNameProvider(); } return nameProvider; } //----------------------------------------------------------------------- /** * Converts an old style id to a new style id. * * @param id the old style id * @return the new style id, null if not found */ private static synchronized String getConvertedId(String id) { Map map = cZoneIdConversion; if (map == null) { // Backwards compatibility with TimeZone. map = new HashMap(); map.put("GMT", "UTC"); map.put("WET", "WET"); map.put("CET", "CET"); map.put("MET", "CET"); map.put("ECT", "CET"); map.put("EET", "EET"); map.put("MIT", "Pacific/Apia"); map.put("HST", "Pacific/Honolulu"); // JDK 1.1 compatible map.put("AST", "America/Anchorage"); map.put("PST", "America/Los_Angeles"); map.put("MST", "America/Denver"); // JDK 1.1 compatible map.put("PNT", "America/Phoenix"); map.put("CST", "America/Chicago"); map.put("EST", "America/New_York"); // JDK 1.1 compatible map.put("IET", "America/Indiana/Indianapolis"); map.put("PRT", "America/Puerto_Rico"); map.put("CNT", "America/St_Johns"); map.put("AGT", "America/Argentina/Buenos_Aires"); map.put("BET", "America/Sao_Paulo"); map.put("ART", "Africa/Cairo"); map.put("CAT", "Africa/Harare"); map.put("EAT", "Africa/Addis_Ababa"); map.put("NET", "Asia/Yerevan"); map.put("PLT", "Asia/Karachi"); map.put("IST", "Asia/Kolkata"); map.put("BST", "Asia/Dhaka"); map.put("VST", "Asia/Ho_Chi_Minh"); map.put("CTT", "Asia/Shanghai"); map.put("JST", "Asia/Tokyo"); map.put("ACT", "Australia/Darwin"); map.put("AET", "Australia/Sydney"); map.put("SST", "Pacific/Guadalcanal"); map.put("NST", "Pacific/Auckland"); cZoneIdConversion = map; } return map.get(id); } private static int parseOffset(String str) { // Can't use a real chronology if called during class // initialization. Offset parser doesn't need it anyhow. Chronology chrono = new BaseChronology() { private static final long serialVersionUID = -3128740902654445468L; public DateTimeZone getZone() { return null; } public Chronology withUTC() { return this; } public Chronology withZone(DateTimeZone zone) { return this; } public String toString() { return getClass().getName(); } }; return -(int) offsetFormatter().withChronology(chrono).parseMillis(str); } /** * Formats a timezone offset string. *

* This method is kept separate from the formatting classes to speed and * simplify startup and classloading. * * @param offset the offset in milliseconds * @return the time zone string */ private static String printOffset(int offset) { StringBuffer buf = new StringBuffer(); if (offset >= 0) { buf.append('+'); } else { buf.append('-'); offset = -offset; } int hours = offset / DateTimeConstants.MILLIS_PER_HOUR; FormatUtils.appendPaddedInteger(buf, hours, 2); offset -= hours * (int) DateTimeConstants.MILLIS_PER_HOUR; int minutes = offset / DateTimeConstants.MILLIS_PER_MINUTE; buf.append(':'); FormatUtils.appendPaddedInteger(buf, minutes, 2); offset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; if (offset == 0) { return buf.toString(); } int seconds = offset / DateTimeConstants.MILLIS_PER_SECOND; buf.append(':'); FormatUtils.appendPaddedInteger(buf, seconds, 2); offset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; if (offset == 0) { return buf.toString(); } buf.append('.'); FormatUtils.appendPaddedInteger(buf, offset, 3); return buf.toString(); } /** * Gets a printer/parser for managing the offset id formatting. * * @return the formatter */ private static synchronized DateTimeFormatter offsetFormatter() { if (cOffsetFormatter == null) { cOffsetFormatter = new DateTimeFormatterBuilder() .appendTimeZoneOffset(null, true, 2, 4) .toFormatter(); } return cOffsetFormatter; } // Instance fields and methods //-------------------------------------------------------------------- private final String iID; /** * Constructor. * * @param id the id to use * @throws IllegalArgumentException if the id is null */ protected DateTimeZone(String id) { if (id == null) { throw new IllegalArgumentException("Id must not be null"); } iID = id; } // Principal methods //-------------------------------------------------------------------- /** * Gets the ID of this datetime zone. * * @return the ID of this datetime zone */ @ToString public final String getID() { return iID; } /** * Returns a non-localized name that is unique to this time zone. It can be * combined with id to form a unique key for fetching localized names. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for * @return name key or null if id should be used for names */ public abstract String getNameKey(long instant); /** * Gets the short name of this datetime zone suitable for display using * the default locale. *

* If the name is not available for the locale, then this method returns a * string in the format [+-]hh:mm. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for * @return the human-readable short name in the default locale */ public final String getShortName(long instant) { return getShortName(instant, null); } /** * Gets the short name of this datetime zone suitable for display using * the specified locale. *

* If the name is not available for the locale, then this method returns a * string in the format [+-]hh:mm. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for * @param locale the locale to get the name for * @return the human-readable short name in the specified locale */ public String getShortName(long instant, Locale locale) { if (locale == null) { locale = Locale.getDefault(); } String nameKey = getNameKey(instant); if (nameKey == null) { return iID; } String name = cNameProvider.getShortName(locale, iID, nameKey); if (name != null) { return name; } return printOffset(getOffset(instant)); } /** * Gets the long name of this datetime zone suitable for display using * the default locale. *

* If the name is not available for the locale, then this method returns a * string in the format [+-]hh:mm. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for * @return the human-readable long name in the default locale */ public final String getName(long instant) { return getName(instant, null); } /** * Gets the long name of this datetime zone suitable for display using * the specified locale. *

* If the name is not available for the locale, then this method returns a * string in the format [+-]hh:mm. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for * @param locale the locale to get the name for * @return the human-readable long name in the specified locale */ public String getName(long instant, Locale locale) { if (locale == null) { locale = Locale.getDefault(); } String nameKey = getNameKey(instant); if (nameKey == null) { return iID; } String name = cNameProvider.getName(locale, iID, nameKey); if (name != null) { return name; } return printOffset(getOffset(instant)); } /** * Gets the millisecond offset to add to UTC to get local time. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the offset for * @return the millisecond offset to add to UTC to get local time */ public abstract int getOffset(long instant); /** * Gets the millisecond offset to add to UTC to get local time. * * @param instant instant to get the offset for, null means now * @return the millisecond offset to add to UTC to get local time */ public final int getOffset(ReadableInstant instant) { if (instant == null) { return getOffset(DateTimeUtils.currentTimeMillis()); } return getOffset(instant.getMillis()); } /** * Gets the standard millisecond offset to add to UTC to get local time, * when standard time is in effect. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the offset for * @return the millisecond offset to add to UTC to get local time */ public abstract int getStandardOffset(long instant); /** * Checks whether, at a particular instant, the offset is standard or not. *

* This method can be used to determine whether Summer Time (DST) applies. * As a general rule, if the offset at the specified instant is standard, * then either Winter time applies, or there is no Summer Time. If the * instant is not standard, then Summer Time applies. *

* The implementation of the method is simply whether {@link #getOffset(long)} * equals {@link #getStandardOffset(long)} at the specified instant. * * @param instant milliseconds from 1970-01-01T00:00:00Z to get the offset for * @return true if the offset at the given instant is the standard offset * @since 1.5 */ public boolean isStandardOffset(long instant) { return getOffset(instant) == getStandardOffset(instant); } /** * Gets the millisecond offset to subtract from local time to get UTC time. * This offset can be used to undo adding the offset obtained by getOffset. * *

     * millisLocal == millisUTC   + getOffset(millisUTC)
     * millisUTC   == millisLocal - getOffsetFromLocal(millisLocal)
     * 
* * NOTE: After calculating millisLocal, some error may be introduced. At * offset transitions (due to DST or other historical changes), ranges of * local times may map to different UTC times. *

* This method will return an offset suitable for calculating an instant * after any DST gap. For example, consider a zone with a cutover * from 01:00 to 01:59:
* Input: 00:00 Output: 00:00
* Input: 00:30 Output: 00:30
* Input: 01:00 Output: 02:00
* Input: 01:30 Output: 02:30
* Input: 02:00 Output: 02:00
* Input: 02:30 Output: 02:30
*

* During a DST overlap (where the local time is ambiguous) this method will return * the earlier instant. The combination of these two rules is to always favour * daylight (summer) time over standard (winter) time. *

* NOTE: Prior to v2.0, the DST overlap behaviour was not defined and varied by hemisphere. * Prior to v1.5, the DST gap behaviour was also not defined. * * @param instantLocal the millisecond instant, relative to this time zone, to get the offset for * @return the millisecond offset to subtract from local time to get UTC time */ public int getOffsetFromLocal(long instantLocal) { // get the offset at instantLocal (first estimate) final int offsetLocal = getOffset(instantLocal); // adjust instantLocal using the estimate and recalc the offset final long instantAdjusted = instantLocal - offsetLocal; final int offsetAdjusted = getOffset(instantAdjusted); // if the offsets differ, we must be near a DST boundary if (offsetLocal != offsetAdjusted) { // we need to ensure that time is always after the DST gap // this happens naturally for positive offsets, but not for negative if ((offsetLocal - offsetAdjusted) < 0) { // if we just return offsetAdjusted then the time is pushed // back before the transition, whereas it should be // on or after the transition long nextLocal = nextTransition(instantAdjusted); long nextAdjusted = nextTransition(instantLocal - offsetAdjusted); if (nextLocal != nextAdjusted) { return offsetLocal; } } } else if (offsetLocal >= 0) { long prev = previousTransition(instantAdjusted); if (prev < instantAdjusted) { int offsetPrev = getOffset(prev); int diff = offsetPrev - offsetLocal; if (instantAdjusted - prev <= diff) { return offsetPrev; } } } return offsetAdjusted; } /** * Converts a standard UTC instant to a local instant with the same * local time. This conversion is used before performing a calculation * so that the calculation can be done using a simple local zone. * * @param instantUTC the UTC instant to convert to local * @return the local instant with the same local time * @throws ArithmeticException if the result overflows a long * @since 1.5 */ public long convertUTCToLocal(long instantUTC) { int offset = getOffset(instantUTC); long instantLocal = instantUTC + offset; // If there is a sign change, but the two values have the same sign... if ((instantUTC ^ instantLocal) < 0 && (instantUTC ^ offset) >= 0) { throw new ArithmeticException("Adding time zone offset caused overflow"); } return instantLocal; } /** * Converts a local instant to a standard UTC instant with the same * local time attempting to use the same offset as the original. *

* This conversion is used after performing a calculation * where the calculation was done using a simple local zone. * Whenever possible, the same offset as the original offset will be used. * This is most significant during a daylight savings overlap. * * @param instantLocal the local instant to convert to UTC * @param strict whether the conversion should reject non-existent local times * @param originalInstantUTC the original instant that the calculation is based on * @return the UTC instant with the same local time, * @throws ArithmeticException if the result overflows a long * @throws IllegalArgumentException if the zone has no equivalent local time * @since 2.0 */ public long convertLocalToUTC(long instantLocal, boolean strict, long originalInstantUTC) { int offsetOriginal = getOffset(originalInstantUTC); long instantUTC = instantLocal - offsetOriginal; int offsetLocalFromOriginal = getOffset(instantUTC); if (offsetLocalFromOriginal == offsetOriginal) { return instantUTC; } return convertLocalToUTC(instantLocal, strict); } /** * Converts a local instant to a standard UTC instant with the same * local time. This conversion is used after performing a calculation * where the calculation was done using a simple local zone. * * @param instantLocal the local instant to convert to UTC * @param strict whether the conversion should reject non-existent local times * @return the UTC instant with the same local time, * @throws ArithmeticException if the result overflows a long * @throws IllegalInstantException if the zone has no equivalent local time * @since 1.5 */ public long convertLocalToUTC(long instantLocal, boolean strict) { // get the offset at instantLocal (first estimate) int offsetLocal = getOffset(instantLocal); // adjust instantLocal using the estimate and recalc the offset int offset = getOffset(instantLocal - offsetLocal); // if the offsets differ, we must be near a DST boundary if (offsetLocal != offset) { // if strict then always check if in DST gap // otherwise only check if zone in Western hemisphere (as the // value of offset is already correct for Eastern hemisphere) if (strict || offsetLocal < 0) { // determine if we are in the DST gap long nextLocal = nextTransition(instantLocal - offsetLocal); if (nextLocal == (instantLocal - offsetLocal)) { nextLocal = Long.MAX_VALUE; } long nextAdjusted = nextTransition(instantLocal - offset); if (nextAdjusted == (instantLocal - offset)) { nextAdjusted = Long.MAX_VALUE; } if (nextLocal != nextAdjusted) { // yes we are in the DST gap if (strict) { // DST gap is not acceptable throw new IllegalInstantException(instantLocal, getID()); } else { // DST gap is acceptable, but for the Western hemisphere // the offset is wrong and will result in local times // before the cutover so use the offsetLocal instead offset = offsetLocal; } } } } // check for overflow long instantUTC = instantLocal - offset; // If there is a sign change, but the two values have different signs... if ((instantLocal ^ instantUTC) < 0 && (instantLocal ^ offset) < 0) { throw new ArithmeticException("Subtracting time zone offset caused overflow"); } return instantUTC; } /** * Gets the millisecond instant in another zone keeping the same local time. *

* The conversion is performed by converting the specified UTC millis to local * millis in this zone, then converting back to UTC millis in the new zone. * * @param newZone the new zone, null means default * @param oldInstant the UTC millisecond instant to convert * @return the UTC millisecond instant with the same local time in the new zone */ public long getMillisKeepLocal(DateTimeZone newZone, long oldInstant) { if (newZone == null) { newZone = DateTimeZone.getDefault(); } if (newZone == this) { return oldInstant; } long instantLocal = convertUTCToLocal(oldInstant); return newZone.convertLocalToUTC(instantLocal, false, oldInstant); } // //----------------------------------------------------------------------- // /** // * Checks if the given {@link LocalDateTime} is within an overlap. // *

// * When switching from Daylight Savings Time to standard time there is // * typically an overlap where the same clock hour occurs twice. This // * method identifies whether the local datetime refers to such an overlap. // * // * @param localDateTime the time to check, not null // * @return true if the given datetime refers to an overlap // */ // public boolean isLocalDateTimeOverlap(LocalDateTime localDateTime) { // if (isFixed()) { // return false; // } // long instantLocal = localDateTime.toDateTime(DateTimeZone.UTC).getMillis(); // // get the offset at instantLocal (first estimate) // int offsetLocal = getOffset(instantLocal); // // adjust instantLocal using the estimate and recalc the offset // int offset = getOffset(instantLocal - offsetLocal); // // if the offsets differ, we must be near a DST boundary // if (offsetLocal != offset) { // long nextLocal = nextTransition(instantLocal - offsetLocal); // long nextAdjusted = nextTransition(instantLocal - offset); // if (nextLocal != nextAdjusted) { // // in DST gap // return false; // } // long diff = Math.abs(offset - offsetLocal); // DateTime dateTime = localDateTime.toDateTime(this); // DateTime adjusted = dateTime.plus(diff); // if (dateTime.getHourOfDay() == adjusted.getHourOfDay() && // dateTime.getMinuteOfHour() == adjusted.getMinuteOfHour() && // dateTime.getSecondOfMinute() == adjusted.getSecondOfMinute()) { // return true; // } // adjusted = dateTime.minus(diff); // if (dateTime.getHourOfDay() == adjusted.getHourOfDay() && // dateTime.getMinuteOfHour() == adjusted.getMinuteOfHour() && // dateTime.getSecondOfMinute() == adjusted.getSecondOfMinute()) { // return true; // } // return false; // } // return false; // } // // // DateTime dateTime = null; // try { // dateTime = localDateTime.toDateTime(this); // } catch (IllegalArgumentException ex) { // return false; // it is a gap, not an overlap // } // long offset1 = Math.abs(getOffset(dateTime.getMillis() + 1) - getStandardOffset(dateTime.getMillis() + 1)); // long offset2 = Math.abs(getOffset(dateTime.getMillis() - 1) - getStandardOffset(dateTime.getMillis() - 1)); // long offset = Math.max(offset1, offset2); // if (offset == 0) { // return false; // } // DateTime adjusted = dateTime.plus(offset); // if (dateTime.getHourOfDay() == adjusted.getHourOfDay() && // dateTime.getMinuteOfHour() == adjusted.getMinuteOfHour() && // dateTime.getSecondOfMinute() == adjusted.getSecondOfMinute()) { // return true; // } // adjusted = dateTime.minus(offset); // if (dateTime.getHourOfDay() == adjusted.getHourOfDay() && // dateTime.getMinuteOfHour() == adjusted.getMinuteOfHour() && // dateTime.getSecondOfMinute() == adjusted.getSecondOfMinute()) { // return true; // } // return false; // long millis = dateTime.getMillis(); // long nextTransition = nextTransition(millis); // long previousTransition = previousTransition(millis); // long deltaToPreviousTransition = millis - previousTransition; // long deltaToNextTransition = nextTransition - millis; // if (deltaToNextTransition < deltaToPreviousTransition) { // int offset = getOffset(nextTransition); // int standardOffset = getStandardOffset(nextTransition); // if (Math.abs(offset - standardOffset) >= deltaToNextTransition) { // return true; // } // } else { // int offset = getOffset(previousTransition); // int standardOffset = getStandardOffset(previousTransition); // if (Math.abs(offset - standardOffset) >= deltaToPreviousTransition) { // return true; // } // } // return false; // } /** * Checks if the given {@link LocalDateTime} is within a gap. *

* When switching from standard time to Daylight Savings Time there is * typically a gap where a clock hour is missing. This method identifies * whether the local datetime refers to such a gap. * * @param localDateTime the time to check, not null * @return true if the given datetime refers to a gap * @since 1.6 */ public boolean isLocalDateTimeGap(LocalDateTime localDateTime) { if (isFixed()) { return false; } try { localDateTime.toDateTime(this); return false; } catch (IllegalInstantException ex) { return true; } } /** * Adjusts the offset to be the earlier or later one during an overlap. * * @param instant the instant to adjust * @param earlierOrLater false for earlier, true for later * @return the adjusted instant millis */ public long adjustOffset(long instant, boolean earlierOrLater) { // a bit messy, but will work in all non-pathological cases // evaluate 3 hours before and after to work out if anything is happening long instantBefore = instant - 3 * DateTimeConstants.MILLIS_PER_HOUR; long instantAfter = instant + 3 * DateTimeConstants.MILLIS_PER_HOUR; long offsetBefore = getOffset(instantBefore); long offsetAfter = getOffset(instantAfter); if (offsetBefore <= offsetAfter) { return instant; // not an overlap (less than is a gap, equal is normal case) } // work out range of instants that have duplicate local times long diff = offsetBefore - offsetAfter; long transition = nextTransition(instantBefore); long overlapStart = transition - diff; long overlapEnd = transition + diff; if (instant < overlapStart || instant >= overlapEnd) { return instant; // not an overlap } // calculate result long afterStart = instant - overlapStart; if (afterStart >= diff) { // currently in later offset return earlierOrLater ? instant : instant - diff; } else { // currently in earlier offset return earlierOrLater ? instant + diff : instant; } } // System.out.println(new DateTime(transitionStart, DateTimeZone.UTC) + " " + new DateTime(transitionStart, this)); //----------------------------------------------------------------------- /** * Returns true if this time zone has no transitions. * * @return true if no transitions */ public abstract boolean isFixed(); /** * Advances the given instant to where the time zone offset or name changes. * If the instant returned is exactly the same as passed in, then * no changes occur after the given instant. * * @param instant milliseconds from 1970-01-01T00:00:00Z * @return milliseconds from 1970-01-01T00:00:00Z */ public abstract long nextTransition(long instant); /** * Retreats the given instant to where the time zone offset or name changes. * If the instant returned is exactly the same as passed in, then * no changes occur before the given instant. * * @param instant milliseconds from 1970-01-01T00:00:00Z * @return milliseconds from 1970-01-01T00:00:00Z */ public abstract long previousTransition(long instant); // Basic methods //-------------------------------------------------------------------- /** * Get the datetime zone as a {@link java.util.TimeZone}. * * @return the closest matching TimeZone object */ public java.util.TimeZone toTimeZone() { return java.util.TimeZone.getTimeZone(iID); } /** * Compare this datetime zone with another. * * @param object the object to compare with * @return true if equal, based on the ID and all internal rules */ public abstract boolean equals(Object object); /** * Gets a hash code compatable with equals. * * @return suitable hashcode */ public int hashCode() { return 57 + getID().hashCode(); } /** * Gets the datetime zone as a string, which is simply its ID. * @return the id of the zone */ public String toString() { return getID(); } /** * By default, when DateTimeZones are serialized, only a "stub" object * referring to the id is written out. When the stub is read in, it * replaces itself with a DateTimeZone object. * @return a stub object to go in the stream */ protected Object writeReplace() throws ObjectStreamException { return new Stub(iID); } /** * Used to serialize DateTimeZones by id. */ private static final class Stub implements Serializable { /** Serialization lock. */ private static final long serialVersionUID = -6471952376487863581L; /** The ID of the zone. */ private transient String iID; /** * Constructor. * @param id the id of the zone */ Stub(String id) { iID = id; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeUTF(iID); } private void readObject(ObjectInputStream in) throws IOException { iID = in.readUTF(); } private Object readResolve() throws ObjectStreamException { return forID(iID); } } } joda-time-2.3/src/main/java/org/joda/time/package.html0000644000175000017500000001735611564251363022160 0ustar ebourgebourg org.joda.time package

Provides support for dates, times, time zones, durations, intervals, and partials. This package aims to fully replace the Java Date, Calendar, and TimeZone classes. This implementation covers both the Gregorian/Julian calendar system and the ISO8601 standard. Additional calendar systems and extensions can be created as well.

The ISO8601 standard is the international standard for dates, times, durations, and intervals. It defines text representations, the first day of the week as Monday, and the first week in a year as having a Thursday in it. This standard is being increasingly used in computer interchange and is the agreed format for XML. For most uses, the ISO standard is the same as Gregorian, and is thus the preferred format.

Interfaces

The main API concepts are defined by interfaces:

  • ReadableInstant - an instant in time
  • ReadableDateTime - an instant in time with field accessors such as dayOfWeek
  • ReadablePartial - a definition for local times that are not defined to the millisecond, such as the time of day
  • ReadableDuration - a duration defined in milliseconds
  • ReadablePeriod - a time period defined in fields such as hours and minutes
  • ReadableInterval - a period of time between two instants
  • ReadWritableInstant - an instant that can be modified
  • ReadWritableDateTime - a datetime that can be modified
  • ReadWritablePeriod - a time period that can be modified
  • ReadWritableInterval - an interval that can be modified

These define the public interface to dates, times, periods, intervals and durations. As with java.util.Date and Calendar, the design is millisecond based with an epoch of 1970-01-01. This should enable easy conversions.

Implementations

The basic implementation of the ReadableInstant interface is Instant. This is a simple immutable class that stores the millisecond value and integrates with Java Date and Calendar. The class follows the definition of the millisecond instant fully, thus it references the ISO-8601 calendar system and UTC time zone. If you are dealing with an instant in time but do not know, or do not want to specify, which calendar system it refers to, then you should use this class.

The main implementation class for datetimes is the DateTime class. This implements the ReadableDateTime interface, providing convenient methods to access the fields of the datetime. Conversion methods allow integration with the Java Date and Calendar classes.

Like Instant, DateTime is immutable, and it can be used safely in a multi-threaded environment. In order to be fully immutable, key clases are declared as final. Abstract superclasses are provided should you need to define your own implementations.

The concrete implementations of the ReadWritable... interfaces are named the same as their immutable counterparts, but with a "Mutable" prefix. For example, MutableDateTime implements ReadWritableDateTime, making datetime editing easy. Note that it is possible to use the immutable DateTime for modifying datetimes, however each modification method returns a new instance of DateTime.

Interface usage

The interfaces in Joda-Time are not designed to operate in the same way as those in the Java Collections Framework (List/Map/Set etc). The Joda-Time interfaces represent a core subset of the functionality available via the actual classes. Thus, much of the work of an application will probably use methods on the class, not on the interface. Your application must determine whether it should define dates in terms of the interfaces, or in terms of the classes.

The interfaces provide simple methods to access an instance of the immutable class, which is implemented either via typecast or object creation. Thus, if you hold a reference to a ReadableInstant, and you call the method toDateTime(), the same instance will be returned (typecast) if it already was a DateTime.

Chronologies and Fields

In order to enable the package to be easily extended, each field of the datetime, such as the month, is calculated by an implementation of DateTimeField. Likewise, duration fields are calculated by specialized DurationField instances. If desired, users can write their own implementations to retrieve an unusual field from the millisecond value.

The datetime and duration fields that together represent a calendar system are grouped into a Chronology. The chronology represents all the information to convert from a millisecond value to human understandable fields in a specific calendar system. Chronologies are provided for ISO, Gregorian/Julian (GJ), Buddhist, Coptic and Ethiopic. More implementations are sought from the community.

The chronology and field classes are singletons. This design results in a low overhead on the date and time classes. The Java Calendar class performs poorly because it has many internal fields that are constantly kept in sync. This design only calculates fields when required, resulting in lightweight and simple date time classes.

When reviewing the library for the first time, it is easy to mistake the number of classes with complexity. The library is in fact clearly divided between user packages and implementation packages in the javadoc. Most users will should not need to be concerned with the back-end implementation.

Partials

Partials are like instants, except they do not completely specify a point in time. The main interface is ReadablePartial.

The main implementations are:

  • LocalTime - A class storing a local time without a date
  • LocalDate - A class storing a local date without a time
  • LocalDateTime - A class storing a local datetime
  • Partial - A class storing any combination of datetime fields, such as dayOfMonth and dayOfWeek
For consistency, the API of each partial class is similar to that of an instant class.

All partial implementations represent a local time, in other words without a time zone. Thus, to convert a partial to an instant (which does contain a time zone) requires adding a zone.

Formatting

Formatting is provided by the format subpackage. Comprehensive support is provided for outputting dates and times in multiple formats. A pattern similar to Java SimpleDateFormat can be used, but a more advanced programmatic technique is available via the builder classes.

joda-time-2.3/src/main/java/org/joda/time/tz/0000755000175000017500000000000012205344143020310 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/tz/ZoneInfoProvider.java0000644000175000017500000002255112203435357024430 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import org.joda.time.DateTimeZone; /** * ZoneInfoProvider loads compiled data files as generated by * {@link ZoneInfoCompiler}. *

* ZoneInfoProvider is thread-safe and publicly immutable. * * @author Brian S O'Neill * @since 1.0 */ public class ZoneInfoProvider implements Provider { /** The directory where the files are held. */ private final File iFileDir; /** The resource path. */ private final String iResourcePath; /** The class loader to use. */ private final ClassLoader iLoader; /** Maps ids to strings or SoftReferences to DateTimeZones. */ private final Map iZoneInfoMap; /** * ZoneInfoProvider searches the given directory for compiled data files. * * @throws IOException if directory or map file cannot be read */ public ZoneInfoProvider(File fileDir) throws IOException { if (fileDir == null) { throw new IllegalArgumentException("No file directory provided"); } if (!fileDir.exists()) { throw new IOException("File directory doesn't exist: " + fileDir); } if (!fileDir.isDirectory()) { throw new IOException("File doesn't refer to a directory: " + fileDir); } iFileDir = fileDir; iResourcePath = null; iLoader = null; iZoneInfoMap = loadZoneInfoMap(openResource("ZoneInfoMap")); } /** * ZoneInfoProvider searches the given ClassLoader resource path for * compiled data files. Resources are loaded from the ClassLoader that * loaded this class. * * @throws IOException if directory or map file cannot be read */ public ZoneInfoProvider(String resourcePath) throws IOException { this(resourcePath, null, false); } /** * ZoneInfoProvider searches the given ClassLoader resource path for * compiled data files. * * @param loader ClassLoader to load compiled data files from. If null, * use system ClassLoader. * @throws IOException if directory or map file cannot be read */ public ZoneInfoProvider(String resourcePath, ClassLoader loader) throws IOException { this(resourcePath, loader, true); } /** * @param favorSystemLoader when true, use the system class loader if * loader null. When false, use the current class loader if loader is null. */ private ZoneInfoProvider(String resourcePath, ClassLoader loader, boolean favorSystemLoader) throws IOException { if (resourcePath == null) { throw new IllegalArgumentException("No resource path provided"); } if (!resourcePath.endsWith("/")) { resourcePath += '/'; } iFileDir = null; iResourcePath = resourcePath; if (loader == null && !favorSystemLoader) { loader = getClass().getClassLoader(); } iLoader = loader; iZoneInfoMap = loadZoneInfoMap(openResource("ZoneInfoMap")); } //----------------------------------------------------------------------- /** * If an error is thrown while loading zone data, uncaughtException is * called to log the error and null is returned for this and all future * requests. * * @param id the id to load * @return the loaded zone */ public DateTimeZone getZone(String id) { if (id == null) { return null; } Object obj = iZoneInfoMap.get(id); if (obj == null) { return null; } if (id.equals(obj)) { // Load zone data for the first time. return loadZoneData(id); } if (obj instanceof SoftReference) { @SuppressWarnings("unchecked") SoftReference ref = (SoftReference) obj; DateTimeZone tz = ref.get(); if (tz != null) { return tz; } // Reference cleared; load data again. return loadZoneData(id); } // If this point is reached, mapping must link to another. return getZone((String)obj); } /** * Gets a list of all the available zone ids. * * @return the zone ids */ public Set getAvailableIDs() { // Return a copy of the keys rather than an umodifiable collection. // This prevents ConcurrentModificationExceptions from being thrown by // some JVMs if zones are opened while this set is iterated over. return new TreeSet(iZoneInfoMap.keySet()); } /** * Called if an exception is thrown from getZone while loading zone data. * * @param ex the exception */ protected void uncaughtException(Exception ex) { Thread t = Thread.currentThread(); t.getThreadGroup().uncaughtException(t, ex); } /** * Opens a resource from file or classpath. * * @param name the name to open * @return the input stream * @throws IOException if an error occurs */ @SuppressWarnings("resource") private InputStream openResource(String name) throws IOException { InputStream in; if (iFileDir != null) { in = new FileInputStream(new File(iFileDir, name)); } else { String path = iResourcePath.concat(name); if (iLoader != null) { in = iLoader.getResourceAsStream(path); } else { in = ClassLoader.getSystemResourceAsStream(path); } if (in == null) { StringBuilder buf = new StringBuilder(40) .append("Resource not found: \"") .append(path) .append("\" ClassLoader: ") .append(iLoader != null ? iLoader.toString() : "system"); throw new IOException(buf.toString()); } } return in; } /** * Loads the time zone data for one id. * * @param id the id to load * @return the zone */ private DateTimeZone loadZoneData(String id) { InputStream in = null; try { in = openResource(id); DateTimeZone tz = DateTimeZoneBuilder.readFrom(in, id); iZoneInfoMap.put(id, new SoftReference(tz)); return tz; } catch (IOException ex) { uncaughtException(ex); iZoneInfoMap.remove(id); return null; } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { } } } //----------------------------------------------------------------------- /** * Loads the zone info map. * * @param in the input stream * @return the map */ private static Map loadZoneInfoMap(InputStream in) throws IOException { Map map = new ConcurrentHashMap(); DataInputStream din = new DataInputStream(in); try { readZoneInfoMap(din, map); } finally { try { din.close(); } catch (IOException ex) { } } map.put("UTC", new SoftReference(DateTimeZone.UTC)); return map; } /** * Reads the zone info map from file. * * @param din the input stream * @param zimap gets filled with string id to string id mappings */ private static void readZoneInfoMap(DataInputStream din, Map zimap) throws IOException { // Read the string pool. int size = din.readUnsignedShort(); String[] pool = new String[size]; for (int i=0; i * CachedDateTimeZone is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public class CachedDateTimeZone extends DateTimeZone { private static final long serialVersionUID = 5472298452022250685L; private static final int cInfoCacheMask; static { Integer i; try { i = Integer.getInteger("org.joda.time.tz.CachedDateTimeZone.size"); } catch (SecurityException e) { i = null; } int cacheSize; if (i == null) { // With a cache size of 512, dates that lie within any 69.7 year // period have no cache collisions. cacheSize = 512; // (1 << 9) } else { cacheSize = i.intValue(); // Ensure cache size is even power of 2. cacheSize--; int shift = 0; while (cacheSize > 0) { shift++; cacheSize >>= 1; } cacheSize = 1 << shift; } cInfoCacheMask = cacheSize - 1; } /** * Returns a new CachedDateTimeZone unless given zone is already cached. */ public static CachedDateTimeZone forZone(DateTimeZone zone) { if (zone instanceof CachedDateTimeZone) { return (CachedDateTimeZone)zone; } return new CachedDateTimeZone(zone); } /* * Caching is performed by breaking timeline down into periods of 2^32 * milliseconds, or about 49.7 days. A year has about 7.3 periods, usually * with only 2 time zone offset periods. Most of the 49.7 day periods will * have no transition, about one quarter have one transition, and very rare * cases have multiple transitions. */ private final DateTimeZone iZone; private final Info[] iInfoCache = new Info[cInfoCacheMask + 1]; private CachedDateTimeZone(DateTimeZone zone) { super(zone.getID()); iZone = zone; } /** * Returns the DateTimeZone being wrapped. */ public DateTimeZone getUncachedZone() { return iZone; } public String getNameKey(long instant) { return getInfo(instant).getNameKey(instant); } public int getOffset(long instant) { return getInfo(instant).getOffset(instant); } public int getStandardOffset(long instant) { return getInfo(instant).getStandardOffset(instant); } public boolean isFixed() { return iZone.isFixed(); } public long nextTransition(long instant) { return iZone.nextTransition(instant); } public long previousTransition(long instant) { return iZone.previousTransition(instant); } public int hashCode() { return iZone.hashCode(); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof CachedDateTimeZone) { return iZone.equals(((CachedDateTimeZone)obj).iZone); } return false; } // Although accessed by multiple threads, this method doesn't need to be // synchronized. private Info getInfo(long millis) { int period = (int)(millis >> 32); Info[] cache = iInfoCache; int index = period & cInfoCacheMask; Info info = cache[index]; if (info == null || (int)((info.iPeriodStart >> 32)) != period) { info = createInfo(millis); cache[index] = info; } return info; } private Info createInfo(long millis) { long periodStart = millis & (0xffffffffL << 32); Info info = new Info(iZone, periodStart); long end = periodStart | 0xffffffffL; Info chain = info; while (true) { long next = iZone.nextTransition(periodStart); if (next == periodStart || next > end) { break; } periodStart = next; chain = (chain.iNextInfo = new Info(iZone, periodStart)); } return info; } private final static class Info { // For first Info in chain, iPeriodStart's lower 32 bits are clear. public final long iPeriodStart; public final DateTimeZone iZoneRef; Info iNextInfo; private String iNameKey; private int iOffset = Integer.MIN_VALUE; private int iStandardOffset = Integer.MIN_VALUE; Info(DateTimeZone zone, long periodStart) { iPeriodStart = periodStart; iZoneRef = zone; } public String getNameKey(long millis) { if (iNextInfo == null || millis < iNextInfo.iPeriodStart) { if (iNameKey == null) { iNameKey = iZoneRef.getNameKey(iPeriodStart); } return iNameKey; } return iNextInfo.getNameKey(millis); } public int getOffset(long millis) { if (iNextInfo == null || millis < iNextInfo.iPeriodStart) { if (iOffset == Integer.MIN_VALUE) { iOffset = iZoneRef.getOffset(iPeriodStart); } return iOffset; } return iNextInfo.getOffset(millis); } public int getStandardOffset(long millis) { if (iNextInfo == null || millis < iNextInfo.iPeriodStart) { if (iStandardOffset == Integer.MIN_VALUE) { iStandardOffset = iZoneRef.getStandardOffset(iPeriodStart); } return iStandardOffset; } return iNextInfo.getStandardOffset(millis); } } } joda-time-2.3/src/main/java/org/joda/time/tz/UTCProvider.java0000644000175000017500000000301511564251363023330 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.util.Collections; import java.util.Set; import org.joda.time.DateTimeZone; /** * Simple time zone provider that supports only UTC. *

* UTCProvider is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public final class UTCProvider implements Provider { /** * Constructor. */ public UTCProvider() { super(); } /** * Returns {@link DateTimeZone#UTC UTC} for "UTC", null * otherwise. */ public DateTimeZone getZone(String id) { if ("UTC".equalsIgnoreCase(id)) { return DateTimeZone.UTC; } return null; } /** * Returns a singleton collection containing only "UTC". */ public Set getAvailableIDs() { return Collections.singleton("UTC"); } } joda-time-2.3/src/main/java/org/joda/time/tz/DefaultNameProvider.java0000644000175000017500000000743611640071136025066 0ustar ebourgebourg/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.text.DateFormatSymbols; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.joda.time.DateTimeUtils; /** * The default name provider acquires localized names from * {@link DateFormatSymbols java.text.DateFormatSymbols}. *

* DefaultNameProvider is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ @SuppressWarnings("unchecked") public class DefaultNameProvider implements NameProvider { // locale -> (id -> (nameKey -> [shortName, name])) private HashMap>> iByLocaleCache = createCache(); public DefaultNameProvider() { } public String getShortName(Locale locale, String id, String nameKey) { String[] nameSet = getNameSet(locale, id, nameKey); return nameSet == null ? null : nameSet[0]; } public String getName(Locale locale, String id, String nameKey) { String[] nameSet = getNameSet(locale, id, nameKey); return nameSet == null ? null : nameSet[1]; } private synchronized String[] getNameSet(Locale locale, String id, String nameKey) { if (locale == null || id == null || nameKey == null) { return null; } Map> byIdCache = iByLocaleCache.get(locale); if (byIdCache == null) { iByLocaleCache.put(locale, byIdCache = createCache()); } Map byNameKeyCache = byIdCache.get(id); if (byNameKeyCache == null) { byIdCache.put(id, byNameKeyCache = createCache()); String[][] zoneStringsEn = DateTimeUtils.getDateFormatSymbols(Locale.ENGLISH).getZoneStrings(); String[] setEn = null; for (String[] strings : zoneStringsEn) { if (strings != null && strings.length == 5 && id.equals(strings[0])) { setEn = strings; break; } } String[][] zoneStringsLoc = DateTimeUtils.getDateFormatSymbols(locale).getZoneStrings(); String[] setLoc = null; for (String[] strings : zoneStringsLoc) { if (strings != null && strings.length == 5 && id.equals(strings[0])) { setLoc = strings; break; } } if (setEn != null && setLoc != null) { byNameKeyCache.put(setEn[2], new String[] {setLoc[2], setLoc[1]}); // need to handle case where summer and winter have the same // abbreviation, such as EST in Australia [1716305] // we handle this by appending "-Summer", cf ZoneInfoCompiler if (setEn[2].equals(setEn[4])) { byNameKeyCache.put(setEn[4] + "-Summer", new String[] {setLoc[4], setLoc[3]}); } else { byNameKeyCache.put(setEn[4], new String[] {setLoc[4], setLoc[3]}); } } } return (String[]) byNameKeyCache.get(nameKey); } private HashMap createCache() { return new HashMap(7); } } joda-time-2.3/src/main/java/org/joda/time/tz/NameProvider.java0000644000175000017500000000260511564251363023561 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.util.Locale; /** * Service provider factory for localized time zone names. * * @author Brian S O'Neill * @since 1.0 */ public interface NameProvider { /** * Returns a localized short name, or null if not found. * * @param locale locale to use for selecting name set * @param id time zone id * @param nameKey time zone name key */ String getShortName(Locale locale, String id, String nameKey); /** * Returns a localized name, or null if not found. * * @param locale locale to use for selecting name set * @param id time zone id * @param nameKey time zone name key */ String getName(Locale locale, String id, String nameKey); } joda-time-2.3/src/main/java/org/joda/time/tz/src/0000755000175000017500000000000012205344143021077 5ustar ebourgebourgjoda-time-2.3/src/main/java/org/joda/time/tz/src/africa0000644000175000017500000014203112200501234022237 0ustar ebourgebourg#

# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# This data is by no means authoritative; if you think you know better,
# go ahead and edit the file (and please send any changes to
# tz@iana.org for general use in the future).

# From Paul Eggert (2013-02-21):
#
# A good source for time zone historical data outside the U.S. is
# Thomas G. Shanks and Rique Pottenger, The International Atlas (6th edition),
# San Diego: ACS Publications, Inc. (2003).
#
# Gwillim Law writes that a good source
# for recent time zone data is the International Air Transport
# Association's Standard Schedules Information Manual (IATA SSIM),
# published semiannually.  Law sent in several helpful summaries
# of the IATA's data after 1990.
#
# Except where otherwise noted, Shanks & Pottenger is the source for
# entries through 1990, and IATA SSIM is the source for entries afterwards.
#
# Another source occasionally used is Edward W. Whitman, World Time Differences,
# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), which
# I found in the UCLA library.
#
# For data circa 1899, a common source is:
# Milne J. Civil time. Geogr J. 1899 Feb;13(2):173-94
# .
#
# A reliable and entertaining source about time zones is
# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997).
#
# Previous editions of this database used WAT, CAT, SAT, and EAT
# for +0:00 through +3:00, respectively,
# but Mark R V Murray reports that
# `SAST' is the official abbreviation for +2:00 in the country of South Africa,
# `CAT' is commonly used for +2:00 in countries north of South Africa, and
# `WAT' is probably the best name for +1:00, as the common phrase for
# the area that includes Nigeria is ``West Africa''.
# He has heard of ``Western Sahara Time'' for +0:00 but can find no reference.
#
# To make things confusing, `WAT' seems to have been used for -1:00 long ago;
# I'd guess that this was because people needed _some_ name for -1:00,
# and at the time, far west Africa was the only major land area in -1:00.
# This usage is now obsolete, as the last use of -1:00 on the African
# mainland seems to have been 1976 in Western Sahara.
#
# To summarize, the following abbreviations seem to have some currency:
#	-1:00	WAT	West Africa Time (no longer used)
#	 0:00	GMT	Greenwich Mean Time
#	 2:00	CAT	Central Africa Time
#	 2:00	SAST	South Africa Standard Time
# and Murray suggests the following abbreviation:
#	 1:00	WAT	West Africa Time
# I realize that this leads to `WAT' being used for both -1:00 and 1:00
# for times before 1976, but this is the best I can think of
# until we get more information.
#
# I invented the following abbreviations; corrections are welcome!
#	 2:00	WAST	West Africa Summer Time
#	 2:30	BEAT	British East Africa Time (no longer used)
#	 2:45	BEAUT	British East Africa Unified Time (no longer used)
#	 3:00	CAST	Central Africa Summer Time (no longer used)
#	 3:00	SAST	South Africa Summer Time (no longer used)
#	 3:00	EAT	East Africa Time
#	 4:00	EAST	East Africa Summer Time (no longer used)

# Algeria
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Algeria	1916	only	-	Jun	14	23:00s	1:00	S
Rule	Algeria	1916	1919	-	Oct	Sun>=1	23:00s	0	-
Rule	Algeria	1917	only	-	Mar	24	23:00s	1:00	S
Rule	Algeria	1918	only	-	Mar	 9	23:00s	1:00	S
Rule	Algeria	1919	only	-	Mar	 1	23:00s	1:00	S
Rule	Algeria	1920	only	-	Feb	14	23:00s	1:00	S
Rule	Algeria	1920	only	-	Oct	23	23:00s	0	-
Rule	Algeria	1921	only	-	Mar	14	23:00s	1:00	S
Rule	Algeria	1921	only	-	Jun	21	23:00s	0	-
Rule	Algeria	1939	only	-	Sep	11	23:00s	1:00	S
Rule	Algeria	1939	only	-	Nov	19	 1:00	0	-
Rule	Algeria	1944	1945	-	Apr	Mon>=1	 2:00	1:00	S
Rule	Algeria	1944	only	-	Oct	 8	 2:00	0	-
Rule	Algeria	1945	only	-	Sep	16	 1:00	0	-
Rule	Algeria	1971	only	-	Apr	25	23:00s	1:00	S
Rule	Algeria	1971	only	-	Sep	26	23:00s	0	-
Rule	Algeria	1977	only	-	May	 6	 0:00	1:00	S
Rule	Algeria	1977	only	-	Oct	21	 0:00	0	-
Rule	Algeria	1978	only	-	Mar	24	 1:00	1:00	S
Rule	Algeria	1978	only	-	Sep	22	 3:00	0	-
Rule	Algeria	1980	only	-	Apr	25	 0:00	1:00	S
Rule	Algeria	1980	only	-	Oct	31	 2:00	0	-
# Shanks & Pottenger give 0:09:20 for Paris Mean Time; go with Howse's
# more precise 0:09:21.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Algiers	0:12:12 -	LMT	1891 Mar 15 0:01
			0:09:21	-	PMT	1911 Mar 11    # Paris Mean Time
			0:00	Algeria	WE%sT	1940 Feb 25 2:00
			1:00	Algeria	CE%sT	1946 Oct  7
			0:00	-	WET	1956 Jan 29
			1:00	-	CET	1963 Apr 14
			0:00	Algeria	WE%sT	1977 Oct 21
			1:00	Algeria	CE%sT	1979 Oct 26
			0:00	Algeria	WE%sT	1981 May
			1:00	-	CET

# Angola
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Luanda	0:52:56	-	LMT	1892
			0:52:04	-	AOT	1911 May 26 # Angola Time
			1:00	-	WAT

# Benin
# Whitman says they switched to 1:00 in 1946, not 1934;
# go with Shanks & Pottenger.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Porto-Novo	0:10:28	-	LMT	1912
			0:00	-	GMT	1934 Feb 26
			1:00	-	WAT

# Botswana
# From Paul Eggert (2013-02-21):
# Milne says they were regulated by the Cape Town Signal in 1899;
# assume they switched to 2:00 when Cape Town did.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Gaborone	1:43:40 -	LMT	1885
			1:30	-	SAST	1903 Mar
			2:00	-	CAT	1943 Sep 19 2:00
			2:00	1:00	CAST	1944 Mar 19 2:00
			2:00	-	CAT

# Burkina Faso
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Ouagadougou	-0:06:04 -	LMT	1912
			 0:00	-	GMT

# Burundi
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Bujumbura	1:57:28	-	LMT	1890
			2:00	-	CAT

# Cameroon
# Whitman says they switched to 1:00 in 1920; go with Shanks & Pottenger.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Douala	0:38:48	-	LMT	1912
			1:00	-	WAT

# Cape Verde
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Atlantic/Cape_Verde -1:34:04 -	LMT	1907			# Praia
			-2:00	-	CVT	1942 Sep
			-2:00	1:00	CVST	1945 Oct 15
			-2:00	-	CVT	1975 Nov 25 2:00
			-1:00	-	CVT

# Central African Republic
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Bangui	1:14:20	-	LMT	1912
			1:00	-	WAT

# Chad
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Ndjamena	1:00:12 -	LMT	1912
			1:00	-	WAT	1979 Oct 14
			1:00	1:00	WAST	1980 Mar  8
			1:00	-	WAT

# Comoros
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Indian/Comoro	2:53:04 -	LMT	1911 Jul   # Moroni, Gran Comoro
			3:00	-	EAT

# Democratic Republic of Congo
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Kinshasa	1:01:12 -	LMT	1897 Nov 9
			1:00	-	WAT
Zone Africa/Lubumbashi	1:49:52 -	LMT	1897 Nov 9
			2:00	-	CAT

# Republic of the Congo
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Brazzaville	1:01:08 -	LMT	1912
			1:00	-	WAT

# Cote D'Ivoire
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Abidjan	-0:16:08 -	LMT	1912
			 0:00	-	GMT

# Djibouti
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Djibouti	2:52:36 -	LMT	1911 Jul
			3:00	-	EAT

###############################################################################

# Egypt

# Milne says Cairo used 2:05:08.9, the local mean time of the Abbasizeh
# observatory; round to nearest.  Milne also says that the official time for
# Egypt was mean noon at the Great Pyramid, 2:04:30.5, but apparently this
# did not apply to Cairo, Alexandria, or Port Said.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Egypt	1940	only	-	Jul	15	0:00	1:00	S
Rule	Egypt	1940	only	-	Oct	 1	0:00	0	-
Rule	Egypt	1941	only	-	Apr	15	0:00	1:00	S
Rule	Egypt	1941	only	-	Sep	16	0:00	0	-
Rule	Egypt	1942	1944	-	Apr	 1	0:00	1:00	S
Rule	Egypt	1942	only	-	Oct	27	0:00	0	-
Rule	Egypt	1943	1945	-	Nov	 1	0:00	0	-
Rule	Egypt	1945	only	-	Apr	16	0:00	1:00	S
Rule	Egypt	1957	only	-	May	10	0:00	1:00	S
Rule	Egypt	1957	1958	-	Oct	 1	0:00	0	-
Rule	Egypt	1958	only	-	May	 1	0:00	1:00	S
Rule	Egypt	1959	1981	-	May	 1	1:00	1:00	S
Rule	Egypt	1959	1965	-	Sep	30	3:00	0	-
Rule	Egypt	1966	1994	-	Oct	 1	3:00	0	-
Rule	Egypt	1982	only	-	Jul	25	1:00	1:00	S
Rule	Egypt	1983	only	-	Jul	12	1:00	1:00	S
Rule	Egypt	1984	1988	-	May	 1	1:00	1:00	S
Rule	Egypt	1989	only	-	May	 6	1:00	1:00	S
Rule	Egypt	1990	1994	-	May	 1	1:00	1:00	S
# IATA (after 1990) says transitions are at 0:00.
# Go with IATA starting in 1995, except correct 1995 entry from 09-30 to 09-29.

# From Alexander Krivenyshev (2011-04-20):
# "...Egypt's interim cabinet decided on Wednesday to cancel daylight
# saving time after a poll posted on its website showed the majority of
# Egyptians would approve the cancellation."
#
# Egypt to cancel daylight saving time
# 
# http://www.almasryalyoum.com/en/node/407168
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_egypt04.html
# 
Rule	Egypt	1995	2010	-	Apr	lastFri	 0:00s	1:00	S
Rule	Egypt	1995	2005	-	Sep	lastThu	23:00s	0	-
# From Steffen Thorsen (2006-09-19):
# The Egyptian Gazette, issue 41,090 (2006-09-18), page 1, reports:
# Egypt will turn back clocks by one hour at the midnight of Thursday
# after observing the daylight saving time since May.
# http://news.gom.com.eg/gazette/pdf/2006/09/18/01.pdf
Rule	Egypt	2006	only	-	Sep	21	23:00s	0	-
# From Dirk Losch (2007-08-14):
# I received a mail from an airline which says that the daylight
# saving time in Egypt will end in the night of 2007-09-06 to 2007-09-07.
# From Jesper Norgaard Welen (2007-08-15): [The following agree:]
# http://www.nentjes.info/Bill/bill5.htm
# http://www.timeanddate.com/worldclock/city.html?n=53
# From Steffen Thorsen (2007-09-04): The official information...:
# http://www.sis.gov.eg/En/EgyptOnline/Miscellaneous/000002/0207000000000000001580.htm
Rule	Egypt	2007	only	-	Sep	Thu>=1	23:00s	0	-
# From Abdelrahman Hassan (2007-09-06):
# Due to the Hijri (lunar Islamic calendar) year being 11 days shorter
# than the year of the Gregorian calendar, Ramadan shifts earlier each
# year. This year it will be observed September 13 (September is quite
# hot in Egypt), and the idea is to make fasting easier for workers by
# shifting business hours one hour out of daytime heat. Consequently,
# unless discontinued, next DST may end Thursday 28 August 2008.
# From Paul Eggert (2007-08-17):
# For lack of better info, assume the new rule is last Thursday in August.

# From Petr Machata (2009-04-06):
# The following appeared in Red Hat bugzilla[1] (edited):
#
# > $ zdump -v /usr/share/zoneinfo/Africa/Cairo | grep 2009
# > /usr/share/zoneinfo/Africa/Cairo  Thu Apr 23 21:59:59 2009 UTC = Thu =
# Apr 23
# > 23:59:59 2009 EET isdst=0 gmtoff=7200
# > /usr/share/zoneinfo/Africa/Cairo  Thu Apr 23 22:00:00 2009 UTC = Fri =
# Apr 24
# > 01:00:00 2009 EEST isdst=1 gmtoff=10800
# > /usr/share/zoneinfo/Africa/Cairo  Thu Aug 27 20:59:59 2009 UTC = Thu =
# Aug 27
# > 23:59:59 2009 EEST isdst=1 gmtoff=10800
# > /usr/share/zoneinfo/Africa/Cairo  Thu Aug 27 21:00:00 2009 UTC = Thu =
# Aug 27
# > 23:00:00 2009 EET isdst=0 gmtoff=7200
#
# > end date should be Thu Sep 24 2009 (Last Thursday in September at 23:59=
# :59)
# > http://support.microsoft.com/kb/958729/
#
# timeanddate[2] and another site I've found[3] also support that.
#
# [1] 
# https://bugzilla.redhat.com/show_bug.cgi?id=492263
# 
# [2] 
# http://www.timeanddate.com/worldclock/clockchange.html?n=53
# 
# [3] 
# http://wwp.greenwichmeantime.com/time-zone/africa/egypt/
# 

# From Arthur David Olson (2009-04-20):
# In 2009 (and for the next several years), Ramadan ends before the fourth
# Thursday in September; Egypt is expected to revert to the last Thursday
# in September.

# From Steffen Thorsen (2009-08-11):
# We have been able to confirm the August change with the Egyptian Cabinet
# Information and Decision Support Center:
# 
# http://www.timeanddate.com/news/time/egypt-dst-ends-2009.html
# 
#
# The Middle East News Agency
# 
# http://www.mena.org.eg/index.aspx
# 
# also reports "Egypt starts winter time on August 21"
# today in article numbered "71, 11/08/2009 12:25 GMT."
# Only the title above is available without a subscription to their service,
# and can be found by searching for "winter" in their search engine
# (at least today).

# From Alexander Krivenyshev (2010-07-20):
# According to News from Egypt -  Al-Masry Al-Youm Egypt's cabinet has
# decided that Daylight Saving Time will not be used in Egypt during
# Ramadan.
#
# Arabic translation:
# "Clocks to go back during Ramadan--and then forward again"
# 
# http://www.almasryalyoum.com/en/news/clocks-go-back-during-ramadan-and-then-forward-again
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_egypt02.html
# 

Rule	Egypt	2008	only	-	Aug	lastThu	23:00s	0	-
Rule	Egypt	2009	only	-	Aug	20	23:00s	0	-
Rule	Egypt	2010	only	-	Aug	11	0:00	0	-
Rule	Egypt	2010	only	-	Sep	10	0:00	1:00	S
Rule	Egypt	2010	only	-	Sep	lastThu	23:00s	0	-

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Cairo	2:05:09 -	LMT	1900 Oct
			2:00	Egypt	EE%sT

# Equatorial Guinea
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Malabo	0:35:08 -	LMT	1912
			0:00	-	GMT	1963 Dec 15
			1:00	-	WAT

# Eritrea
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Asmara	2:35:32 -	LMT	1870
			2:35:32	-	AMT	1890	      # Asmara Mean Time
			2:35:20	-	ADMT	1936 May 5    # Adis Dera MT
			3:00	-	EAT

# Ethiopia
# From Paul Eggert (2006-03-22):
# Shanks & Pottenger write that Ethiopia had six narrowly-spaced time zones
# between 1870 and 1890, and that they merged to 38E50 (2:35:20) in 1890.
# We'll guess that 38E50 is for Adis Dera.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Addis_Ababa	2:34:48 -	LMT	1870
			2:35:20	-	ADMT	1936 May 5    # Adis Dera MT
			3:00	-	EAT

# Gabon
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Libreville	0:37:48 -	LMT	1912
			1:00	-	WAT

# Gambia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Banjul	-1:06:36 -	LMT	1912
			-1:06:36 -	BMT	1935	# Banjul Mean Time
			-1:00	-	WAT	1964
			 0:00	-	GMT

# Ghana
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# Whitman says DST was observed from 1931 to ``the present'';
# go with Shanks & Pottenger.
Rule	Ghana	1936	1942	-	Sep	 1	0:00	0:20	GHST
Rule	Ghana	1936	1942	-	Dec	31	0:00	0	GMT
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Accra	-0:00:52 -	LMT	1918
			 0:00	Ghana	%s

# Guinea
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Conakry	-0:54:52 -	LMT	1912
			 0:00	-	GMT	1934 Feb 26
			-1:00	-	WAT	1960
			 0:00	-	GMT

# Guinea-Bissau
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Bissau	-1:02:20 -	LMT	1911 May 26
			-1:00	-	WAT	1975
			 0:00	-	GMT

# Kenya
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Nairobi	2:27:16	-	LMT	1928 Jul
			3:00	-	EAT	1930
			2:30	-	BEAT	1940
			2:45	-	BEAUT	1960
			3:00	-	EAT

# Lesotho
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Maseru	1:50:00 -	LMT	1903 Mar
			2:00	-	SAST	1943 Sep 19 2:00
			2:00	1:00	SAST	1944 Mar 19 2:00
			2:00	-	SAST

# Liberia
# From Paul Eggert (2006-03-22):
# In 1972 Liberia was the last country to switch
# from a UTC offset that was not a multiple of 15 or 20 minutes.
# Howse reports that it was in honor of their president's birthday.
# Shank & Pottenger report the date as May 1, whereas Howse reports Jan;
# go with Shanks & Pottenger.
# For Liberia before 1972, Shanks & Pottenger report -0:44, whereas Howse and
# Whitman each report -0:44:30; go with the more precise figure.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Monrovia	-0:43:08 -	LMT	1882
			-0:43:08 -	MMT	1919 Mar # Monrovia Mean Time
			-0:44:30 -	LRT	1972 May # Liberia Time
			 0:00	-	GMT

###############################################################################

# Libya

# From Even Scharning (2012-11-10):
# Libya set their time one hour back at 02:00 on Saturday November 10.
# http://www.libyaherald.com/2012/11/04/clocks-to-go-back-an-hour-on-saturday/
# Here is an official source [in Arabic]: http://ls.ly/fb6Yc
#
# Steffen Thorsen forwarded a translation (2012-11-10) in
# http://mm.icann.org/pipermail/tz/2012-November/018451.html
#
# From Tim Parenti (2012-11-11):
# Treat the 2012-11-10 change as a zone change from UTC+2 to UTC+1.
# The DST rules planned for 2013 and onward roughly mirror those of Europe
# (either two days before them or five days after them, so as to fall on
# lastFri instead of lastSun).

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Libya	1951	only	-	Oct	14	2:00	1:00	S
Rule	Libya	1952	only	-	Jan	 1	0:00	0	-
Rule	Libya	1953	only	-	Oct	 9	2:00	1:00	S
Rule	Libya	1954	only	-	Jan	 1	0:00	0	-
Rule	Libya	1955	only	-	Sep	30	0:00	1:00	S
Rule	Libya	1956	only	-	Jan	 1	0:00	0	-
Rule	Libya	1982	1984	-	Apr	 1	0:00	1:00	S
Rule	Libya	1982	1985	-	Oct	 1	0:00	0	-
Rule	Libya	1985	only	-	Apr	 6	0:00	1:00	S
Rule	Libya	1986	only	-	Apr	 4	0:00	1:00	S
Rule	Libya	1986	only	-	Oct	 3	0:00	0	-
Rule	Libya	1987	1989	-	Apr	 1	0:00	1:00	S
Rule	Libya	1987	1989	-	Oct	 1	0:00	0	-
Rule	Libya	1997	only	-	Apr	 4	0:00	1:00	S
Rule	Libya	1997	only	-	Oct	 4	0:00	0	-
Rule	Libya	2013	max	-	Mar	lastFri	1:00	1:00	S
Rule	Libya	2013	max	-	Oct	lastFri	2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Tripoli	0:52:44 -	LMT	1920
			1:00	Libya	CE%sT	1959
			2:00	-	EET	1982
			1:00	Libya	CE%sT	1990 May  4
# The 1996 and 1997 entries are from Shanks & Pottenger;
# the IATA SSIM data contain some obvious errors.
			2:00	-	EET	1996 Sep 30
			1:00	Libya	CE%sT	1997 Oct  4
			2:00	-	EET	2012 Nov 10 2:00
			1:00	Libya	CE%sT

# Madagascar
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Indian/Antananarivo 3:10:04 -	LMT	1911 Jul
			3:00	-	EAT	1954 Feb 27 23:00s
			3:00	1:00	EAST	1954 May 29 23:00s
			3:00	-	EAT

# Malawi
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Blantyre	2:20:00 -	LMT	1903 Mar
			2:00	-	CAT

# Mali
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Bamako	-0:32:00 -	LMT	1912
			 0:00	-	GMT	1934 Feb 26
			-1:00	-	WAT	1960 Jun 20
			 0:00	-	GMT

# Mauritania
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Nouakchott	-1:03:48 -	LMT	1912
			 0:00	-	GMT	1934 Feb 26
			-1:00	-	WAT	1960 Nov 28
			 0:00	-	GMT

# Mauritius

# From Steffen Thorsen (2008-06-25):
# Mauritius plans to observe DST from 2008-11-01 to 2009-03-31 on a trial
# basis....
# It seems that Mauritius observed daylight saving time from 1982-10-10 to
# 1983-03-20 as well, but that was not successful....
# http://www.timeanddate.com/news/time/mauritius-daylight-saving-time.html

# From Alex Krivenyshev (2008-06-25):
# http://economicdevelopment.gov.mu/portal/site/Mainhomepage/menuitem.a42b24128104d9845dabddd154508a0c/?content_id=0a7cee8b5d69a110VgnVCM1000000a04a8c0RCRD

# From Arthur David Olson (2008-06-30):
# The www.timeanddate.com article cited by Steffen Thorsen notes that "A
# final decision has yet to be made on the times that daylight saving
# would begin and end on these dates." As a place holder, use midnight.

# From Paul Eggert (2008-06-30):
# Follow Thorsen on DST in 1982/1983, instead of Shanks & Pottenger.

# From Steffen Thorsen (2008-07-10):
# According to
# 
# http://www.lexpress.mu/display_article.php?news_id=111216
# 
# (in French), Mauritius will start and end their DST a few days earlier
# than previously announced (2008-11-01 to 2009-03-31).  The new start
# date is 2008-10-26 at 02:00 and the new end date is 2009-03-27 (no time
# given, but it is probably at either 2 or 3 wall clock time).
#
# A little strange though, since the article says that they moved the date
# to align itself with Europe and USA which also change time on that date,
# but that means they have not paid attention to what happened in
# USA/Canada last year (DST ends first Sunday in November). I also wonder
# why that they end on a Friday, instead of aligning with Europe which
# changes two days later.

# From Alex Krivenyshev (2008-07-11):
# Seems that English language article "The revival of daylight saving
# time:  Energy conservation?"-# No. 16578 (07/11/2008) was originally
# published on Monday, June 30, 2008...
#
# I guess that article in French "Le gouvernement avance l'introduction
# de l'heure d'ete" stating that DST in Mauritius starting on October 26
# and ending on March 27, 2009 is the most recent one.
# ...
# 
# http://www.worldtimezone.com/dst_news/dst_news_mauritius02.html
# 

# From Riad M. Hossen Ally (2008-08-03):
# The Government of Mauritius weblink
# 
# http://www.gov.mu/portal/site/pmosite/menuitem.4ca0efdee47462e7440a600248a521ca/?content_id=4728ca68b2a5b110VgnVCM1000000a04a8c0RCRD
# 
# Cabinet Decision of July 18th, 2008 states as follows:
#
# 4. ...Cabinet has agreed to the introduction into the National Assembly
# of the Time Bill which provides for the introduction of summer time in
# Mauritius. The summer time period which will be of one hour ahead of
# the standard time, will be aligned with that in Europe and the United
# States of America. It will start at two o'clock in the morning on the
# last Sunday of October and will end at two o'clock in the morning on
# the last Sunday of March the following year. The summer time for the
# year 2008 - 2009 will, therefore, be effective as from 26 October 2008
# and end on 29 March 2009.

# From Ed Maste (2008-10-07):
# THE TIME BILL (No. XXVII of 2008) Explanatory Memorandum states the
# beginning / ending of summer time is 2 o'clock standard time in the
# morning of the last Sunday of October / last Sunday of March.
# 
# http://www.gov.mu/portal/goc/assemblysite/file/bill2708.pdf
# 

# From Steffen Thorsen (2009-06-05):
# According to several sources, Mauritius will not continue to observe
# DST the coming summer...
#
# Some sources, in French:
# 
# http://www.defimedia.info/news/946/Rashid-Beebeejaun-:-%C2%AB-L%E2%80%99heure-d%E2%80%99%C3%A9t%C3%A9-ne-sera-pas-appliqu%C3%A9e-cette-ann%C3%A9e-%C2%BB
# 
# 
# http://lexpress.mu/Story/3398~Beebeejaun---Les-objectifs-d-%C3%A9conomie-d-%C3%A9nergie-de-l-heure-d-%C3%A9t%C3%A9-ont-%C3%A9t%C3%A9-atteints-
# 
#
# Our wrap-up:
# 
# http://www.timeanddate.com/news/time/mauritius-dst-will-not-repeat.html
# 

# From Arthur David Olson (2009-07-11):
# The "mauritius-dst-will-not-repeat" wrapup includes this:
# "The trial ended on March 29, 2009, when the clocks moved back by one hour
# at 2am (or 02:00) local time..."

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule Mauritius	1982	only	-	Oct	10	0:00	1:00	S
Rule Mauritius	1983	only	-	Mar	21	0:00	0	-
Rule Mauritius	2008	only	-	Oct	lastSun	2:00	1:00	S
Rule Mauritius	2009	only	-	Mar	lastSun	2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Indian/Mauritius	3:50:00 -	LMT	1907		# Port Louis
			4:00 Mauritius	MU%sT	# Mauritius Time
# Agalega Is, Rodriguez
# no information; probably like Indian/Mauritius

# Mayotte
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Indian/Mayotte	3:00:56 -	LMT	1911 Jul	# Mamoutzou
			3:00	-	EAT

# Morocco
# See the `europe' file for Spanish Morocco (Africa/Ceuta).

# From Alex Krivenyshev (2008-05-09):
# Here is an article that Morocco plan to introduce Daylight Saving Time between
# 1 June, 2008 and 27 September, 2008.
#
# "... Morocco is to save energy by adjusting its clock during summer so it will
# be one hour ahead of GMT between 1 June and 27 September, according to
# Communication Minister and Gov ernment Spokesman, Khalid Naciri...."
#
# 
# http://www.worldtimezone.net/dst_news/dst_news_morocco01.html
# 
# OR
# 
# http://en.afrik.com/news11892.html
# 

# From Alex Krivenyshev (2008-05-09):
# The Morocco time change can be confirmed on Morocco web site Maghreb Arabe Presse:
# 
# http://www.map.ma/eng/sections/box3/morocco_shifts_to_da/view
# 
#
# Morocco shifts to daylight time on June 1st through September 27, Govt.
# spokesman.

# From Patrice Scattolin (2008-05-09):
# According to this article:
# 
# http://www.avmaroc.com/actualite/heure-dete-comment-a127896.html
# 
# (and republished here:
# 
# http://www.actu.ma/heure-dete-comment_i127896_0.html
# 
# )
# the changes occurs at midnight:
#
# saturday night may 31st at midnight (which in french is to be
# intrepreted as the night between saturday and sunday)
# sunday night the 28th  at midnight
#
# Seeing that the 28th is monday, I am guessing that she intends to say
# the midnight of the 28th which is the midnight between sunday and
# monday, which jives with other sources that say that it's inclusive
# june1st to sept 27th.
#
# The decision was taken by decree *2-08-224 *but I can't find the decree
# published on the web.
#
# It's also confirmed here:
# 
# http://www.maroc.ma/NR/exeres/FACF141F-D910-44B0-B7FA-6E03733425D1.htm
# 
# on a government portal as being  between june 1st and sept 27th (not yet
# posted in english).
#
# The following google query will generate many relevant hits:
# 
# http://www.google.com/search?hl=en&q=Conseil+de+gouvernement+maroc+heure+avance&btnG=Search
# 

# From Alex Krivenyshev (2008-05-09):
# Is Western Sahara (part which administrated by Morocco) going to follow
# Morocco DST changes?  Any information?  What about other part of
# Western Sahara - under administration of POLISARIO Front (also named
# SADR Saharawi Arab Democratic Republic)?

# From Arthur David Olson (2008-05-09):
# XXX--guess that it is only Morocco for now; guess only 2008 for now.

# From Steffen Thorsen (2008-08-27):
# Morocco will change the clocks back on the midnight between August 31
# and September 1. They originally planned to observe DST to near the end
# of September:
#
# One article about it (in French):
# 
# http://www.menara.ma/fr/Actualites/Maroc/Societe/ci.retour_a_l_heure_gmt_a_partir_du_dimanche_31_aout_a_minuit_officiel_.default
# 
#
# We have some further details posted here:
# 
# http://www.timeanddate.com/news/time/morocco-ends-dst-early-2008.html
# 

# From Steffen Thorsen (2009-03-17):
# Morocco will observe DST from 2009-06-01 00:00 to 2009-08-21 00:00 according
# to many sources, such as
# 
# http://news.marweb.com/morocco/entertainment/morocco-daylight-saving.html
# 
# 
# http://www.medi1sat.ma/fr/depeche.aspx?idp=2312
# 
# (French)
#
# Our summary:
# 
# http://www.timeanddate.com/news/time/morocco-starts-dst-2009.html
# 

# From Alexander Krivenyshev (2009-03-17):
# Here is a link to official document from Royaume du Maroc Premier Ministre,
# Ministere de la Modernisation des Secteurs Publics
#
# Under Article 1 of Royal Decree No. 455-67 of Act 23 safar 1387 (2 june 1967)
# concerning the amendment of the legal time, the Ministry of Modernization of
# Public Sectors announced that the official time in the Kingdom will be
# advanced 60 minutes from Sunday 31 May 2009 at midnight.
#
# 
# http://www.mmsp.gov.ma/francais/Actualites_fr/PDF_Actualites_Fr/HeureEte_FR.pdf
# 
#
# 
# http://www.worldtimezone.com/dst_news/dst_news_morocco03.html
# 

# From Steffen Thorsen (2010-04-13):
# Several news media in Morocco report that the Ministry of Modernization
# of Public Sectors has announced that Morocco will have DST from
# 2010-05-02 to 2010-08-08.
#
# Example:
# 
# http://www.lavieeco.com/actualites/4099-le-maroc-passera-a-l-heure-d-ete-gmt1-le-2-mai.html
# 
# (French)
# Our page:
# 
# http://www.timeanddate.com/news/time/morocco-starts-dst-2010.html
# 

# From Dan Abitol (2011-03-30):
# ...Rules for Africa/Casablanca are the following (24h format)
# The 3rd april 2011 at 00:00:00, [it] will be 3rd april 1:00:00
# The 31th july 2011 at 00:59:59,  [it] will be 31th July 00:00:00
# ...Official links of change in morocco
# The change was broadcast on the FM Radio
# I ve called ANRT (telecom regulations in Morocco) at
# +212.537.71.84.00
# 
# http://www.anrt.net.ma/fr/
# 
# They said that
# 
# http://www.map.ma/fr/sections/accueil/l_heure_legale_au_ma/view
# 
# is the official publication to look at.
# They said that the decision was already taken.
#
# More articles in the press
# 
# http://www.yabiladi.com/articles/details/5058/secret-l-heure-d-ete-maroc-lev
# 
# e.html
# 
# http://www.lematin.ma/Actualite/Express/Article.asp?id=148923
# 
# 
# http://www.lavieeco.com/actualite/Le-Maroc-passe-sur-GMT%2B1-a-partir-de-dim
# anche-prochain-5538.html
# 

# From Petr Machata (2011-03-30):
# They have it written in English here:
# 
# http://www.map.ma/eng/sections/home/morocco_to_spring_fo/view
# 
#
# It says there that "Morocco will resume its standard time on July 31,
# 2011 at midnight." Now they don't say whether they mean midnight of
# wall clock time (i.e. 11pm UTC), but that's what I would assume. It has
# also been like that in the past.

# From Alexander Krivenyshev (2012-03-09):
# According to Infomédiaire web site from Morocco (infomediaire.ma),
# on March 9, 2012, (in French) Heure légale:
# Le Maroc adopte officiellement l'heure d'été
# 
# http://www.infomediaire.ma/news/maroc/heure-l%C3%A9gale-le-maroc-adopte-officiellement-lheure-d%C3%A9t%C3%A9
# 
# Governing Council adopted draft decree, that Morocco DST starts on
# the last Sunday of March (March 25, 2012) and ends on
# last Sunday of September (September 30, 2012)
# except the month of Ramadan.
# or (brief)
# 
# http://www.worldtimezone.com/dst_news/dst_news_morocco06.html
# 

# From Arthur David Olson (2012-03-10):
# The infomediaire.ma source indicates that the system is to be in
# effect every year. It gives 03H00 as the "fall back" time of day;
# it lacks a "spring forward" time of day; assume 2:00 XXX.
# Wait on specifying the Ramadan exception for details about
# start date, start time of day, end date, and end time of day XXX.

# From Christophe Tropamer (2012-03-16):
# Seen Morocco change again:
# 
# http://www.le2uminutes.com/actualite.php
# 
# "...à partir du dernier dimance d'avril et non fins mars,
# comme annoncé précédemment."

# From Milamber Space Network (2012-07-17):
# The official return to GMT is announced by the Moroccan government:
# 
# http://www.mmsp.gov.ma/fr/actualites.aspx?id=288 [in French]
# 
#
# Google translation, lightly edited:
# Back to the standard time of the Kingdom (GMT)
# Pursuant to Decree No. 2-12-126 issued on 26 Jumada (I) 1433 (April 18,
# 2012) and in accordance with the order of Mr. President of the
# Government No. 3-47-12 issued on 24 Sha'ban (11 July 2012), the Ministry
# of Public Service and Administration Modernization announces the return
# of the legal time of the Kingdom (GMT) from Friday, July 20, 2012 until
# Monday, August 20, 2012.  So the time will be delayed by 60 minutes from
# 3:00 am Friday, July 20, 2012 and will again be advanced by 60 minutes
# August 20, 2012 from 2:00 am.

# From Paul Eggert (2013-03-06):
# Morocco's daylight-saving transitions due to Ramadan seem to be
# announced a bit in advance.  On 2012-07-11 the Moroccan government
# announced that year's Ramadan daylight-saving transitions would be
# 2012-07-20 and 2012-08-20; see
# .

# From Andrew Paprocki (2013-07-02):
# Morocco announced that the year's Ramadan daylight-savings
# transitions would be 2013-07-07 and 2013-08-10; see:
# http://www.maroc.ma/en/news/morocco-suspends-daylight-saving-time-july-7-aug10

# From Paul Eggert (2013-07-03):
# To estimate what the Moroccan government will do in future years,
# transition dates for 2014 through 2021 were determined by running
# the following program under GNU Emacs 24.3:
#
# (let ((islamic-year 1435))
#   (while (< islamic-year 1444)
#     (let ((a
#	     (calendar-gregorian-from-absolute
#	      (calendar-islamic-to-absolute (list 9 1 islamic-year))))
#	    (b
#	     (calendar-gregorian-from-absolute
#	      (calendar-islamic-to-absolute (list 10 1 islamic-year)))))
#	(insert
#	 (format
#	  (concat "Rule\tMorocco\t%d\tonly\t-\t%s\t %2d\t 3:00\t0\t-\n"
#		  "Rule\tMorocco\t%d\tonly\t-\t%s\t %2d\t 2:00\t1:00\tS\n")
#	  (car (cdr (cdr a))) (calendar-month-name (car a) t) (car (cdr a))
#	  (car (cdr (cdr b))) (calendar-month-name (car b) t) (car (cdr b)))))
#     (setq islamic-year (+ 1 islamic-year))))
#
# with the results hand-edited for 2020-2022, when the normal spring-forward
# date falls during the estimated Ramadan.
#
# From 2023 through 2038 Ramadan is not predicted to overlap with
# daylight saving time.  Starting in 2039 there will be overlap again,
# but 32-bit time_t values roll around in 2038 so for now do not worry
# about dates after 2038.

# RULE	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S

Rule	Morocco	1939	only	-	Sep	12	 0:00	1:00	S
Rule	Morocco	1939	only	-	Nov	19	 0:00	0	-
Rule	Morocco	1940	only	-	Feb	25	 0:00	1:00	S
Rule	Morocco	1945	only	-	Nov	18	 0:00	0	-
Rule	Morocco	1950	only	-	Jun	11	 0:00	1:00	S
Rule	Morocco	1950	only	-	Oct	29	 0:00	0	-
Rule	Morocco	1967	only	-	Jun	 3	12:00	1:00	S
Rule	Morocco	1967	only	-	Oct	 1	 0:00	0	-
Rule	Morocco	1974	only	-	Jun	24	 0:00	1:00	S
Rule	Morocco	1974	only	-	Sep	 1	 0:00	0	-
Rule	Morocco	1976	1977	-	May	 1	 0:00	1:00	S
Rule	Morocco	1976	only	-	Aug	 1	 0:00	0	-
Rule	Morocco	1977	only	-	Sep	28	 0:00	0	-
Rule	Morocco	1978	only	-	Jun	 1	 0:00	1:00	S
Rule	Morocco	1978	only	-	Aug	 4	 0:00	0	-
Rule	Morocco	2008	only	-	Jun	 1	 0:00	1:00	S
Rule	Morocco	2008	only	-	Sep	 1	 0:00	0	-
Rule	Morocco	2009	only	-	Jun	 1	 0:00	1:00	S
Rule	Morocco	2009	only	-	Aug	 21	 0:00	0	-
Rule	Morocco	2010	only	-	May	 2	 0:00	1:00	S
Rule	Morocco	2010	only	-	Aug	 8	 0:00	0	-
Rule	Morocco	2011	only	-	Apr	 3	 0:00	1:00	S
Rule	Morocco	2011	only	-	Jul	 31	 0	0	-
Rule	Morocco	2012	2019	-	Apr	 lastSun 2:00	1:00	S
Rule	Morocco	2012	max	-	Sep	 lastSun 3:00	0	-
Rule	Morocco	2012	only	-	Jul	 20	 3:00	0	-
Rule	Morocco	2012	only	-	Aug	 20	 2:00	1:00	S
Rule	Morocco	2013	only	-	Jul	  7	 3:00	0	-
Rule	Morocco	2013	only	-	Aug	 10	 2:00	1:00	S
Rule	Morocco	2014	only	-	Jun	 29	 3:00	0	-
Rule	Morocco	2014	only	-	Jul	 29	 2:00	1:00	S
Rule	Morocco	2015	only	-	Jun	 18	 3:00	0	-
Rule	Morocco	2015	only	-	Jul	 18	 2:00	1:00	S
Rule	Morocco	2016	only	-	Jun	  7	 3:00	0	-
Rule	Morocco	2016	only	-	Jul	  7	 2:00	1:00	S
Rule	Morocco	2017	only	-	May	 27	 3:00	0	-
Rule	Morocco	2017	only	-	Jun	 26	 2:00	1:00	S
Rule	Morocco	2018	only	-	May	 16	 3:00	0	-
Rule	Morocco	2018	only	-	Jun	 15	 2:00	1:00	S
Rule	Morocco	2019	only	-	May	  6	 3:00	0	-
Rule	Morocco	2019	only	-	Jun	  5	 2:00	1:00	S
Rule	Morocco	2020	only	-	May	 24	 2:00	1:00	S
Rule	Morocco	2021	only	-	May	 13	 2:00	1:00	S
Rule	Morocco	2022	only	-	May	  3	 2:00	1:00	S
Rule	Morocco	2023	max	-	Apr	 lastSun 2:00	1:00	S

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Casablanca	-0:30:20 -	LMT	1913 Oct 26
			 0:00	Morocco	WE%sT	1984 Mar 16
			 1:00	-	CET	1986
			 0:00	Morocco	WE%sT
# Western Sahara
Zone Africa/El_Aaiun	-0:52:48 -	LMT	1934 Jan
			-1:00	-	WAT	1976 Apr 14
			 0:00	-	WET

# Mozambique
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Maputo	2:10:20 -	LMT	1903 Mar
			2:00	-	CAT

# Namibia
# The 1994-04-03 transition is from Shanks & Pottenger.
# Shanks & Pottenger report no DST after 1998-04; go with IATA.

# From Petronella Sibeene (2007-03-30) in
# :
# While the entire country changes its time, Katima Mulilo and other
# settlements in Caprivi unofficially will not because the sun there
# rises and sets earlier compared to other regions.  Chief of
# Forecasting Riaan van Zyl explained that the far eastern parts of
# the country are close to 40 minutes earlier in sunrise than the rest
# of the country.
#
# From Paul Eggert (2007-03-31):
# Apparently the Caprivi Strip informally observes Botswana time, but
# we have no details.  In the meantime people there can use Africa/Gaborone.

# RULE	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Namibia	1994	max	-	Sep	Sun>=1	2:00	1:00	S
Rule	Namibia	1995	max	-	Apr	Sun>=1	2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Windhoek	1:08:24 -	LMT	1892 Feb 8
			1:30	-	SWAT	1903 Mar	# SW Africa Time
			2:00	-	SAST	1942 Sep 20 2:00
			2:00	1:00	SAST	1943 Mar 21 2:00
			2:00	-	SAST	1990 Mar 21 # independence
			2:00	-	CAT	1994 Apr  3
			1:00	Namibia	WA%sT

# Niger
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Niamey	 0:08:28 -	LMT	1912
			-1:00	-	WAT	1934 Feb 26
			 0:00	-	GMT	1960
			 1:00	-	WAT

# Nigeria
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Lagos	0:13:36 -	LMT	1919 Sep
			1:00	-	WAT

# Reunion
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Indian/Reunion	3:41:52 -	LMT	1911 Jun	# Saint-Denis
			4:00	-	RET	# Reunion Time
#
# Scattered Islands (Iles Eparses) administered from Reunion are as follows.
# The following information about them is taken from
# Iles Eparses (www.outre-mer.gouv.fr/domtom/ile.htm, 1997-07-22, in French;
# no longer available as of 1999-08-17).
# We have no info about their time zone histories.
#
# Bassas da India - uninhabited
# Europa Island - inhabited from 1905 to 1910 by two families
# Glorioso Is - inhabited until at least 1958
# Juan de Nova - uninhabited
# Tromelin - inhabited until at least 1958

# Rwanda
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Kigali	2:00:16 -	LMT	1935 Jun
			2:00	-	CAT

# St Helena
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Atlantic/St_Helena	-0:22:48 -	LMT	1890		# Jamestown
			-0:22:48 -	JMT	1951	# Jamestown Mean Time
			 0:00	-	GMT
# The other parts of the St Helena territory are similar:
#	Tristan da Cunha: on GMT, say Whitman and the CIA
#	Ascension: on GMT, says usno1995 and the CIA
#	Gough (scientific station since 1955; sealers wintered previously):
#		on GMT, says the CIA
#	Inaccessible, Nightingale: no information, but probably GMT

# Sao Tome and Principe
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Sao_Tome	 0:26:56 -	LMT	1884
			-0:36:32 -	LMT	1912	# Lisbon Mean Time
			 0:00	-	GMT

# Senegal
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Dakar	-1:09:44 -	LMT	1912
			-1:00	-	WAT	1941 Jun
			 0:00	-	GMT

# Seychelles
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Indian/Mahe	3:41:48 -	LMT	1906 Jun	# Victoria
			4:00	-	SCT	# Seychelles Time
# From Paul Eggert (2001-05-30):
# Aldabra, Farquhar, and Desroches, originally dependencies of the
# Seychelles, were transferred to the British Indian Ocean Territory
# in 1965 and returned to Seychelles control in 1976.  We don't know
# whether this affected their time zone, so omit this for now.
# Possibly the islands were uninhabited.

# Sierra Leone
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# Whitman gives Mar 31 - Aug 31 for 1931 on; go with Shanks & Pottenger.
Rule	SL	1935	1942	-	Jun	 1	0:00	0:40	SLST
Rule	SL	1935	1942	-	Oct	 1	0:00	0	WAT
Rule	SL	1957	1962	-	Jun	 1	0:00	1:00	SLST
Rule	SL	1957	1962	-	Sep	 1	0:00	0	GMT
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Freetown	-0:53:00 -	LMT	1882
			-0:53:00 -	FMT	1913 Jun # Freetown Mean Time
			-1:00	SL	%s	1957
			 0:00	SL	%s

# Somalia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Mogadishu	3:01:28 -	LMT	1893 Nov
			3:00	-	EAT	1931
			2:30	-	BEAT	1957
			3:00	-	EAT

# South Africa
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	SA	1942	1943	-	Sep	Sun>=15	2:00	1:00	-
Rule	SA	1943	1944	-	Mar	Sun>=15	2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Johannesburg 1:52:00 -	LMT	1892 Feb 8
			1:30	-	SAST	1903 Mar
			2:00	SA	SAST
# Marion and Prince Edward Is
# scientific station since 1947
# no information

# Sudan
#
# From 
# Sudan News Agency (2000-01-13)
# , also reported by Michael De Beukelaer-Dossche via Steffen Thorsen:
# Clocks will be moved ahead for 60 minutes all over the Sudan as of noon
# Saturday....  This was announced Thursday by Caretaker State Minister for
# Manpower Abdul-Rahman Nur-Eddin.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Sudan	1970	only	-	May	 1	0:00	1:00	S
Rule	Sudan	1970	1985	-	Oct	15	0:00	0	-
Rule	Sudan	1971	only	-	Apr	30	0:00	1:00	S
Rule	Sudan	1972	1985	-	Apr	lastSun	0:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Khartoum	2:10:08 -	LMT	1931
			2:00	Sudan	CA%sT	2000 Jan 15 12:00
			3:00	-	EAT

# South Sudan
Zone	Africa/Juba	2:06:24 -	LMT	1931
			2:00	Sudan	CA%sT	2000 Jan 15 12:00
			3:00	-	EAT

# Swaziland
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Mbabane	2:04:24 -	LMT	1903 Mar
			2:00	-	SAST

# Tanzania
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Africa/Dar_es_Salaam 2:37:08 -	LMT	1931
			3:00	-	EAT	1948
			2:45	-	BEAUT	1961
			3:00	-	EAT

# Togo
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Lome	0:04:52 -	LMT	1893
			0:00	-	GMT

# Tunisia

# From Gwillim Law (2005-04-30):
# My correspondent, Risto Nykanen, has alerted me to another adoption of DST,
# this time in Tunisia.  According to Yahoo France News
# , in a story attributed to AP
# and dated 2005-04-26, "Tunisia has decided to advance its official time by
# one hour, starting on Sunday, May 1.  Henceforth, Tunisian time will be
# UTC+2 instead of UTC+1.  The change will take place at 23:00 UTC next
# Saturday."  (My translation)
#
# From Oscar van Vlijmen (2005-05-02):
# LaPresse, the first national daily newspaper ...
# 
# ... DST for 2005: on: Sun May 1 0h standard time, off: Fri Sept. 30,
# 1h standard time.
#
# From Atef Loukil (2006-03-28):
# The daylight saving time will be the same each year:
# Beginning      : the last Sunday of March at 02:00
# Ending         : the last Sunday of October at 03:00 ...
# http://www.tap.info.tn/en/index.php?option=com_content&task=view&id=1188&Itemid=50

# From Steffen Thorsen (2009-03-16):
# According to several news sources, Tunisia will not observe DST this year.
# (Arabic)
# 
# http://www.elbashayer.com/?page=viewn&nid=42546
# 
# 
# http://www.babnet.net/kiwidetail-15295.asp
# 
#
# We have also confirmed this with the US embassy in Tunisia.
# We have a wrap-up about this on the following page:
# 
# http://www.timeanddate.com/news/time/tunisia-cancels-dst-2009.html
# 

# From Alexander Krivenyshev (2009-03-17):
# Here is a link to Tunis Afrique Presse News Agency
#
# Standard time to be kept the whole year long (tap.info.tn):
#
# (in English)
# 
# http://www.tap.info.tn/en/index.php?option=com_content&task=view&id=26813&Itemid=157
# 
#
# (in Arabic)
# 
# http://www.tap.info.tn/ar/index.php?option=com_content&task=view&id=61240&Itemid=1
# 

# From Arthur David Olson (2009--3-18):
# The Tunis Afrique Presse News Agency notice contains this: "This measure is due to the fact
# that the fasting month of ramadan coincides with the period concerned by summer time.
# Therefore, the standard time will be kept unchanged the whole year long."
# So foregoing DST seems to be an exception (albeit one that may be repeated in the  future).

# From Alexander Krivenyshev (2010-03-27):
# According to some news reports Tunis confirmed not to use DST in 2010
#
# (translation):
# "The Tunisian government has decided to abandon DST, which was scheduled on
# Sunday...
# Tunisian authorities had suspended the DST for the first time last year also
# coincided with the month of Ramadan..."
#
# (in Arabic)
# 
# http://www.moheet.com/show_news.aspx?nid=358861&pg=1
# 
# http://www.almadenahnews.com/newss/news.php?c=118&id=38036
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_tunis02.html

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Tunisia	1939	only	-	Apr	15	23:00s	1:00	S
Rule	Tunisia	1939	only	-	Nov	18	23:00s	0	-
Rule	Tunisia	1940	only	-	Feb	25	23:00s	1:00	S
Rule	Tunisia	1941	only	-	Oct	 6	 0:00	0	-
Rule	Tunisia	1942	only	-	Mar	 9	 0:00	1:00	S
Rule	Tunisia	1942	only	-	Nov	 2	 3:00	0	-
Rule	Tunisia	1943	only	-	Mar	29	 2:00	1:00	S
Rule	Tunisia	1943	only	-	Apr	17	 2:00	0	-
Rule	Tunisia	1943	only	-	Apr	25	 2:00	1:00	S
Rule	Tunisia	1943	only	-	Oct	 4	 2:00	0	-
Rule	Tunisia	1944	1945	-	Apr	Mon>=1	 2:00	1:00	S
Rule	Tunisia	1944	only	-	Oct	 8	 0:00	0	-
Rule	Tunisia	1945	only	-	Sep	16	 0:00	0	-
Rule	Tunisia	1977	only	-	Apr	30	 0:00s	1:00	S
Rule	Tunisia	1977	only	-	Sep	24	 0:00s	0	-
Rule	Tunisia	1978	only	-	May	 1	 0:00s	1:00	S
Rule	Tunisia	1978	only	-	Oct	 1	 0:00s	0	-
Rule	Tunisia	1988	only	-	Jun	 1	 0:00s	1:00	S
Rule	Tunisia	1988	1990	-	Sep	lastSun	 0:00s	0	-
Rule	Tunisia	1989	only	-	Mar	26	 0:00s	1:00	S
Rule	Tunisia	1990	only	-	May	 1	 0:00s	1:00	S
Rule	Tunisia	2005	only	-	May	 1	 0:00s	1:00	S
Rule	Tunisia	2005	only	-	Sep	30	 1:00s	0	-
Rule	Tunisia	2006	2008	-	Mar	lastSun	 2:00s	1:00	S
Rule	Tunisia	2006	2008	-	Oct	lastSun	 2:00s	0	-

# Shanks & Pottenger give 0:09:20 for Paris Mean Time; go with Howse's
# more precise 0:09:21.
# Shanks & Pottenger say the 1911 switch was on Mar 9; go with Howse's Mar 11.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Tunis	0:40:44 -	LMT	1881 May 12
			0:09:21	-	PMT	1911 Mar 11    # Paris Mean Time
			1:00	Tunisia	CE%sT

# Uganda
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Kampala	2:09:40 -	LMT	1928 Jul
			3:00	-	EAT	1930
			2:30	-	BEAT	1948
			2:45	-	BEAUT	1957
			3:00	-	EAT

# Zambia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Lusaka	1:53:08 -	LMT	1903 Mar
			2:00	-	CAT

# Zimbabwe
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Africa/Harare	2:04:12 -	LMT	1903 Mar
			2:00	-	CAT
joda-time-2.3/src/main/java/org/joda/time/tz/src/asia0000644000175000017500000034437612200501234021747 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# This data is by no means authoritative; if you think you know better,
# go ahead and edit the file (and please send any changes to
# tz@iana.org for general use in the future).

# From Paul Eggert (2013-02-21):
#
# A good source for time zone historical data outside the U.S. is
# Thomas G. Shanks and Rique Pottenger, The International Atlas (6th edition),
# San Diego: ACS Publications, Inc. (2003).
#
# Gwillim Law writes that a good source
# for recent time zone data is the International Air Transport
# Association's Standard Schedules Information Manual (IATA SSIM),
# published semiannually.  Law sent in several helpful summaries
# of the IATA's data after 1990.
#
# Except where otherwise noted, Shanks & Pottenger is the source for
# entries through 1990, and IATA SSIM is the source for entries afterwards.
#
# Another source occasionally used is Edward W. Whitman, World Time Differences,
# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), which
# I found in the UCLA library.
#
# For data circa 1899, a common source is:
# Milne J. Civil time. Geogr J. 1899 Feb;13(2):173-94
# .
#
# A reliable and entertaining source about time zones is
# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997).
#
# I invented the abbreviations marked `*' in the following table;
# the rest are from earlier versions of this file, or from other sources.
# Corrections are welcome!
#	     std  dst
#	     LMT	Local Mean Time
#	2:00 EET  EEST	Eastern European Time
#	2:00 IST  IDT	Israel
#	3:00 AST  ADT	Arabia*
#	3:30 IRST IRDT	Iran
#	4:00 GST	Gulf*
#	5:30 IST	India
#	7:00 ICT	Indochina*
#	7:00 WIT	west Indonesia
#	8:00 CIT	central Indonesia
#	8:00 CST	China
#	9:00 CJT	Central Japanese Time (1896/1937)*
#	9:00 EIT	east Indonesia
#	9:00 JST  JDT	Japan
#	9:00 KST  KDT	Korea
#	9:30 CST	(Australian) Central Standard Time
#
# See the `europe' file for Russia and Turkey in Asia.

# From Guy Harris:
# Incorporates data for Singapore from Robert Elz' asia 1.1, as well as
# additional information from Tom Yap, Sun Microsystems Intercontinental
# Technical Support (including a page from the Official Airline Guide -
# Worldwide Edition).  The names for time zones are guesses.

###############################################################################

# These rules are stolen from the `europe' file.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	EUAsia	1981	max	-	Mar	lastSun	 1:00u	1:00	S
Rule	EUAsia	1979	1995	-	Sep	lastSun	 1:00u	0	-
Rule	EUAsia	1996	max	-	Oct	lastSun	 1:00u	0	-
Rule E-EurAsia	1981	max	-	Mar	lastSun	 0:00	1:00	S
Rule E-EurAsia	1979	1995	-	Sep	lastSun	 0:00	0	-
Rule E-EurAsia	1996	max	-	Oct	lastSun	 0:00	0	-
Rule RussiaAsia	1981	1984	-	Apr	1	 0:00	1:00	S
Rule RussiaAsia	1981	1983	-	Oct	1	 0:00	0	-
Rule RussiaAsia	1984	1991	-	Sep	lastSun	 2:00s	0	-
Rule RussiaAsia	1985	1991	-	Mar	lastSun	 2:00s	1:00	S
Rule RussiaAsia	1992	only	-	Mar	lastSat	23:00	1:00	S
Rule RussiaAsia	1992	only	-	Sep	lastSat	23:00	0	-
Rule RussiaAsia	1993	max	-	Mar	lastSun	 2:00s	1:00	S
Rule RussiaAsia	1993	1995	-	Sep	lastSun	 2:00s	0	-
Rule RussiaAsia	1996	max	-	Oct	lastSun	 2:00s	0	-

# Afghanistan
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Kabul	4:36:48 -	LMT	1890
			4:00	-	AFT	1945
			4:30	-	AFT

# Armenia
# From Paul Eggert (2006-03-22):
# Shanks & Pottenger have Yerevan switching to 3:00 (with Russian DST)
# in spring 1991, then to 4:00 with no DST in fall 1995, then
# readopting Russian DST in 1997.  Go with Shanks & Pottenger, even
# when they disagree with others.  Edgar Der-Danieliantz
# reported (1996-05-04) that Yerevan probably wouldn't use DST
# in 1996, though it did use DST in 1995.  IATA SSIM (1991/1998) reports that
# Armenia switched from 3:00 to 4:00 in 1998 and observed DST after 1991,
# but started switching at 3:00s in 1998.

# From Arthur David Olson (2011-06-15):
# While Russia abandoned DST in 2011, Armenia may choose to
# follow Russia's "old" rules.

# From Alexander Krivenyshev (2012-02-10):
# According to News Armenia, on Feb 9, 2012,
# http://newsarmenia.ru/society/20120209/42609695.html
#
# The Armenia National Assembly adopted final reading of Amendments to the
# Law "On procedure of calculation time on the territory of the Republic of
# Armenia" according to which Armenia [is] abolishing Daylight Saving Time.
# or
# (brief)
# http://www.worldtimezone.com/dst_news/dst_news_armenia03.html
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Yerevan	2:58:00 -	LMT	1924 May  2
			3:00	-	YERT	1957 Mar    # Yerevan Time
			4:00 RussiaAsia YER%sT	1991 Mar 31 2:00s
			3:00	1:00	YERST	1991 Sep 23 # independence
			3:00 RussiaAsia	AM%sT	1995 Sep 24 2:00s
			4:00	-	AMT	1997
			4:00 RussiaAsia	AM%sT	2012 Mar 25 2:00s
			4:00	-	AMT

# Azerbaijan
# From Rustam Aliyev of the Azerbaijan Internet Forum (2005-10-23):
# According to the resolution of Cabinet of Ministers, 1997
# Resolution available at: http://aif.az/docs/daylight_res.pdf
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Azer	1997	max	-	Mar	lastSun	 4:00	1:00	S
Rule	Azer	1997	max	-	Oct	lastSun	 5:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Baku	3:19:24 -	LMT	1924 May  2
			3:00	-	BAKT	1957 Mar    # Baku Time
			4:00 RussiaAsia BAK%sT	1991 Mar 31 2:00s
			3:00	1:00	BAKST	1991 Aug 30 # independence
			3:00 RussiaAsia	AZ%sT	1992 Sep lastSat 23:00
			4:00	-	AZT	1996 # Azerbaijan time
			4:00	EUAsia	AZ%sT	1997
			4:00	Azer	AZ%sT

# Bahrain
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Bahrain	3:22:20 -	LMT	1920		# Al Manamah
			4:00	-	GST	1972 Jun
			3:00	-	AST

# Bangladesh
# From Alexander Krivenyshev (2009-05-13):
# According to newspaper Asian Tribune (May 6, 2009) Bangladesh may introduce
# Daylight Saving Time from June 16 to Sept 30
#
# Bangladesh to introduce daylight saving time likely from June 16
# 
# http://www.asiantribune.com/?q=node/17288
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_bangladesh02.html
# 
#
# "... Bangladesh government has decided to switch daylight saving time from
# June
# 16 till September 30 in a bid to ensure maximum use of daylight to cope with
# crippling power crisis. "
#
# The switch will remain in effect from June 16 to Sept 30 (2009) but if
# implemented the next year, it will come in force from April 1, 2010

# From Steffen Thorsen (2009-06-02):
# They have finally decided now, but changed the start date to midnight between
# the 19th and 20th, and they have not set the end date yet.
#
# Some sources:
# 
# http://in.reuters.com/article/southAsiaNews/idINIndia-40017620090601
# 
# 
# http://bdnews24.com/details.php?id=85889&cid=2
# 
#
# Our wrap-up:
# 
# http://www.timeanddate.com/news/time/bangladesh-daylight-saving-2009.html
# 

# From A. N. M. Kamrus Saadat (2009-06-15):
# Finally we've got the official mail regarding DST start time where DST start
# time is mentioned as Jun 19 2009, 23:00 from BTRC (Bangladesh
# Telecommunication Regulatory Commission).
#
# No DST end date has been announced yet.

# From Alexander Krivenyshev (2009-09-25):
# Bangladesh won't go back to Standard Time from October 1, 2009,
# instead it will continue DST measure till the cabinet makes a fresh decision.
#
# Following report by same newspaper-"The Daily Star Friday":
# "DST change awaits cabinet decision-Clock won't go back by 1-hr from Oct 1"
# 
# http://www.thedailystar.net/newDesign/news-details.php?nid=107021
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_bangladesh04.html
# 

# From Steffen Thorsen (2009-10-13):
# IANS (Indo-Asian News Service) now reports:
# Bangladesh has decided that the clock advanced by an hour to make
# maximum use of daylight hours as an energy saving measure would
# "continue for an indefinite period."
#
# One of many places where it is published:
# 
# http://www.thaindian.com/newsportal/business/bangladesh-to-continue-indefinitely-with-advanced-time_100259987.html
# 

# From Alexander Krivenyshev (2009-12-24):
# According to Bangladesh newspaper "The Daily Star,"
# Bangladesh will change its clock back to Standard Time on Dec 31, 2009.
#
# Clock goes back 1-hr on Dec 31 night.
# 
# http://www.thedailystar.net/newDesign/news-details.php?nid=119228
# 
# and
# 
# http://www.worldtimezone.com/dst_news/dst_news_bangladesh05.html
# 
#
# "...The government yesterday decided to put the clock back by one hour
# on December 31 midnight and the new time will continue until March 31,
# 2010 midnight. The decision came at a cabinet meeting at the Prime
# Minister's Office last night..."

# From Alexander Krivenyshev (2010-03-22):
# According to Bangladesh newspaper "The Daily Star,"
# Cabinet cancels Daylight Saving Time
# 
# http://www.thedailystar.net/newDesign/latest_news.php?nid=22817
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_bangladesh06.html
# 

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Dhaka	2009	only	-	Jun	19	23:00	1:00	S
Rule	Dhaka	2009	only	-	Dec	31	23:59	0	-

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Dhaka	6:01:40 -	LMT	1890
			5:53:20	-	HMT	1941 Oct    # Howrah Mean Time?
			6:30	-	BURT	1942 May 15 # Burma Time
			5:30	-	IST	1942 Sep
			6:30	-	BURT	1951 Sep 30
			6:00	-	DACT	1971 Mar 26 # Dacca Time
			6:00	-	BDT	2009
			6:00	Dhaka	BD%sT

# Bhutan
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Thimphu	5:58:36 -	LMT	1947 Aug 15 # or Thimbu
			5:30	-	IST	1987 Oct
			6:00	-	BTT	# Bhutan Time

# British Indian Ocean Territory
# Whitman and the 1995 CIA time zone map say 5:00, but the
# 1997 and later maps say 6:00.  Assume the switch occurred in 1996.
# We have no information as to when standard time was introduced;
# assume it occurred in 1907, the same year as Mauritius (which
# then contained the Chagos Archipelago).
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Indian/Chagos	4:49:40	-	LMT	1907
			5:00	-	IOT	1996 # BIOT Time
			6:00	-	IOT

# Brunei
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Brunei	7:39:40 -	LMT	1926 Mar   # Bandar Seri Begawan
			7:30	-	BNT	1933
			8:00	-	BNT

# Burma / Myanmar

# Milne says 6:24:40 was the meridian of the time ball observatory at Rangoon.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Rangoon	6:24:40 -	LMT	1880		# or Yangon
			6:24:40	-	RMT	1920	   # Rangoon Mean Time?
			6:30	-	BURT	1942 May   # Burma Time
			9:00	-	JST	1945 May 3
			6:30	-	MMT		   # Myanmar Time

# Cambodia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Phnom_Penh	6:59:40 -	LMT	1906 Jun  9
			7:06:20	-	SMT	1911 Mar 11 0:01 # Saigon MT?
			7:00	-	ICT	1912 May
			8:00	-	ICT	1931 May
			7:00	-	ICT

# China

# From Guy Harris:
# People's Republic of China.  Yes, they really have only one time zone.

# From Bob Devine (1988-01-28):
# No they don't.  See TIME mag, 1986-02-17 p.52.  Even though
# China is across 4 physical time zones, before Feb 1, 1986 only the
# Peking (Bejing) time zone was recognized.  Since that date, China
# has two of 'em -- Peking's and Urumqi (named after the capital of
# the Xinjiang Uyghur Autonomous Region).  I don't know about DST for it.
#
# . . .I just deleted the DST table and this editor makes it too
# painful to suck in another copy..  So, here is what I have for
# DST start/end dates for Peking's time zone (info from AP):
#
#     1986 May 4 - Sept 14
#     1987 mid-April - ??

# From U. S. Naval Observatory (1989-01-19):
# CHINA               8 H  AHEAD OF UTC  ALL OF CHINA, INCL TAIWAN
# CHINA               9 H  AHEAD OF UTC  APR 17 - SEP 10

# From Paul Eggert (2006-03-22):
# Shanks & Pottenger write that China (except for Hong Kong and Macau)
# has had a single time zone since 1980 May 1, observing summer DST
# from 1986 through 1991; this contradicts Devine's
# note about Time magazine, though apparently _something_ happened in 1986.
# Go with Shanks & Pottenger for now.  I made up names for the other
# pre-1980 time zones.

# From Shanks & Pottenger:
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Shang	1940	only	-	Jun	 3	0:00	1:00	D
Rule	Shang	1940	1941	-	Oct	 1	0:00	0	S
Rule	Shang	1941	only	-	Mar	16	0:00	1:00	D
Rule	PRC	1986	only	-	May	 4	0:00	1:00	D
Rule	PRC	1986	1991	-	Sep	Sun>=11	0:00	0	S
Rule	PRC	1987	1991	-	Apr	Sun>=10	0:00	1:00	D

# From Anthony Fok (2001-12-20):
# BTW, I did some research on-line and found some info regarding these five
# historic timezones from some Taiwan websites.  And yes, there are official
# Chinese names for these locales (before 1949).
#
# From Jesper Norgaard Welen (2006-07-14):
# I have investigated the timezones around 1970 on the
# http://www.astro.com/atlas site [with provinces and county
# boundaries summarized below]....  A few other exceptions were two
# counties on the Sichuan side of the Xizang-Sichuan border,
# counties Dege and Baiyu which lies on the Sichuan side and are
# therefore supposed to be GMT+7, Xizang region being GMT+6, but Dege
# county is GMT+8 according to astro.com while Baiyu county is GMT+6
# (could be true), for the moment I am assuming that those two
# counties are mistakes in the astro.com data.

# From Paul Eggert (2008-02-11):
# I just now checked Google News for western news sources that talk
# about China's single time zone, and couldn't find anything before 1986
# talking about China being in one time zone.  (That article was: Jim
# Mann, "A clumsy embrace for another western custom: China on daylight
# time--sort of", Los Angeles Times, 1986-05-05.  By the way, this
# article confirms the tz database's data claiming that China began
# observing daylight saving time in 1986.
#
# From Thomas S. Mullaney (2008-02-11):
# I think you're combining two subjects that need to treated
# separately: daylight savings (which, you're correct, wasn't
# implemented until the 1980s) and the unified time zone centered near
# Beijing (which was implemented in 1949). Briefly, there was also a
# "Lhasa Time" in Tibet and "Urumqi Time" in Xinjiang. The first was
# ceased, and the second eventually recognized (again, in the 1980s).
#
# From Paul Eggert (2008-06-30):
# There seems to be a good chance China switched to a single time zone in 1949
# rather than in 1980 as Shanks & Pottenger have it, but we don't have a
# reliable documentary source saying so yet, so for now we still go with
# Shanks & Pottenger.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# Changbai Time ("Long-white Time", Long-white = Heilongjiang area)
# Heilongjiang (except Mohe county), Jilin
Zone	Asia/Harbin	8:26:44	-	LMT	1928 # or Haerbin
			8:30	-	CHAT	1932 Mar # Changbai Time
			8:00	-	CST	1940
			9:00	-	CHAT	1966 May
			8:30	-	CHAT	1980 May
			8:00	PRC	C%sT
# Zhongyuan Time ("Central plain Time")
# most of China
# Milne gives 8:05:56.7; round to nearest.
Zone	Asia/Shanghai	8:05:57	-	LMT	1928
			8:00	Shang	C%sT	1949
			8:00	PRC	C%sT
# Long-shu Time (probably due to Long and Shu being two names of that area)
# Guangxi, Guizhou, Hainan, Ningxia, Sichuan, Shaanxi, and Yunnan;
# most of Gansu; west Inner Mongolia; west Qinghai; and the Guangdong
# counties Deqing, Enping, Kaiping, Luoding, Taishan, Xinxing,
# Yangchun, Yangjiang, Yu'nan, and Yunfu.
Zone	Asia/Chongqing	7:06:20	-	LMT	1928 # or Chungking
			7:00	-	LONT	1980 May # Long-shu Time
			8:00	PRC	C%sT
# Xin-zang Time ("Xinjiang-Tibet Time")
# The Gansu counties Aksay, Anxi, Dunhuang, Subei; west Qinghai;
# the Guangdong counties  Xuwen, Haikang, Suixi, Lianjiang,
# Zhanjiang, Wuchuan, Huazhou, Gaozhou, Maoming, Dianbai, and Xinyi;
# east Tibet, including Lhasa, Chamdo, Shigaise, Jimsar, Shawan and Hutubi;
# east Xinjiang, including Urumqi, Turpan, Karamay, Korla, Minfeng, Jinghe,
# Wusu, Qiemo, Xinyan, Wulanwusu, Jinghe, Yumin, Tacheng, Tuoli, Emin,
# Shihezi, Changji, Yanqi, Heshuo, Tuokexun, Tulufan, Shanshan, Hami,
# Fukang, Kuitun, Kumukuli, Miquan, Qitai, and Turfan.
Zone	Asia/Urumqi	5:50:20	-	LMT	1928 # or Urumchi
			6:00	-	URUT	1980 May # Urumqi Time
			8:00	PRC	C%sT
# Kunlun Time
# West Tibet, including Pulan, Aheqi, Shufu, Shule;
# West Xinjiang, including Aksu, Atushi, Yining, Hetian, Cele, Luopu, Nileke,
# Zhaosu, Tekesi, Gongliu, Chabuchaer, Huocheng, Bole, Pishan, Suiding,
# and Yarkand.

# From Luther Ma (2009-10-17):
# Almost all (>99.9%) ethnic Chinese (properly ethnic Han) living in
# Xinjiang use Chinese Standard Time. Some are aware of Xinjiang time,
# but have no need of it. All planes, trains, and schools function on
# what is called "Beijing time." When Han make an appointment in Chinese
# they implicitly use Beijing time.
#
# On the other hand, ethnic Uyghurs, who make up about half the
# population of Xinjiang, typically use "Xinjiang time" which is two
# hours behind Beijing time, or UTC +0600. The government of the Xinjiang
# Uyghur Autonomous Region, (XAUR, or just Xinjiang for short) as well as
# local governments such as the Urumqi city government use both times in
# publications, referring to what is popularly called Xinjiang time as
# "Urumqi time." When Uyghurs make an appointment in the Uyghur language
# they almost invariably use Xinjiang time.
#
# (Their ethnic Han compatriots would typically have no clue of its
# widespread use, however, because so extremely few of them are fluent in
# Uyghur, comparable to the number of Anglo-Americans fluent in Navajo.)
#
# (...As with the rest of China there was a brief interval ending in 1990
# or 1991 when summer time was in use.  The confusion was severe, with
# the province not having dual times but four times in use at the same
# time. Some areas remained on standard Xinjiang time or Beijing time and
# others moving their clocks ahead.)
#
# ...an example of an official website using of Urumqi time.
#
# The first few lines of the Google translation of
# 
# http://www.fjysgl.gov.cn/show.aspx?id=2379&cid=39
# 
# (retrieved 2009-10-13)
# > Urumqi fire seven people are missing the alleged losses of at least
# > 500 million yuan
# >
# > (Reporter Dong Liu) the day before 20:20 or so (Urumqi Time 18:20),
# > Urumqi City Department of International Plaza Luther Qiantang River
# > burst fire. As of yesterday, 18:30, Urumqi City Fire officers and men
# > have worked continuously for 22 hours...

# From Luther Ma (2009-11-19):
# With the risk of being redundant to previous answers these are the most common
# English "transliterations" (w/o using non-English symbols):
#
# 1. Wulumuqi...
# 2. Kashi...
# 3. Urumqi...
# 4. Kashgar...
# ...
# 5. It seems that Uyghurs in Urumqi has been using Xinjiang since at least the
# 1960's. I know of one Han, now over 50, who grew up in the surrounding
# countryside and used Xinjiang time as a child.
#
# 6. Likewise for Kashgar and the rest of south Xinjiang I don't know of any
# start date for Xinjiang time.
#
# Without having access to local historical records, nor the ability to legally
# publish them, I would go with October 1, 1949, when Xinjiang became the Uyghur
# Autonomous Region under the PRC. (Before that Uyghurs, of course, would also
# not be using Beijing time, but some local time.)

Zone	Asia/Kashgar	5:03:56	-	LMT	1928 # or Kashi or Kaxgar
			5:30	-	KAST	1940	 # Kashgar Time
			5:00	-	KAST	1980 May
			8:00	PRC	C%sT


# Hong Kong (Xianggang)

# Milne gives 7:36:41.7; round this.

# From Lee Yiu Chung (2009-10-24):
# I found there are some mistakes for the...DST rule for Hong
# Kong. [According] to the DST record from Hong Kong Observatory (actually,
# it is not [an] observatory, but the official meteorological agency of HK,
# and also serves as the official timing agency), there are some missing
# and incorrect rules. Although the exact switch over time is missing, I
# think 3:30 is correct. The official DST record for Hong Kong can be
# obtained from
# 
# http://www.hko.gov.hk/gts/time/Summertime.htm
# .

# From Arthur David Olson (2009-10-28):
# Here are the dates given at
# 
# http://www.hko.gov.hk/gts/time/Summertime.htm
# 
# as of 2009-10-28:
# Year        Period
# 1941        1 Apr to 30 Sep
# 1942        Whole year
# 1943        Whole year
# 1944        Whole year
# 1945        Whole year
# 1946        20 Apr to 1 Dec
# 1947        13 Apr to 30 Dec
# 1948        2 May to 31 Oct
# 1949        3 Apr to 30 Oct
# 1950        2 Apr to 29 Oct
# 1951        1 Apr to 28 Oct
# 1952        6 Apr to 25 Oct
# 1953        5 Apr to 1 Nov
# 1954        21 Mar to 31 Oct
# 1955        20 Mar to 6 Nov
# 1956        18 Mar to 4 Nov
# 1957        24 Mar to 3 Nov
# 1958        23 Mar to 2 Nov
# 1959        22 Mar to 1 Nov
# 1960        20 Mar to 6 Nov
# 1961        19 Mar to 5 Nov
# 1962        18 Mar to 4 Nov
# 1963        24 Mar to 3 Nov
# 1964        22 Mar to 1 Nov
# 1965        18 Apr to 17 Oct
# 1966        17 Apr to 16 Oct
# 1967        16 Apr to 22 Oct
# 1968        21 Apr to 20 Oct
# 1969        20 Apr to 19 Oct
# 1970        19 Apr to 18 Oct
# 1971        18 Apr to 17 Oct
# 1972        16 Apr to 22 Oct
# 1973        22 Apr to 21 Oct
# 1973/74     30 Dec 73 to 20 Oct 74
# 1975        20 Apr to 19 Oct
# 1976        18 Apr to 17 Oct
# 1977        Nil
# 1978        Nil
# 1979        13 May to 21 Oct
# 1980 to Now Nil
# The page does not give start or end times of day.
# The page does not give a start date for 1942.
# The page does not givw an end date for 1945.
# The Japanese occupation of Hong Kong began on 1941-12-25.
# The Japanese surrender of Hong Kong was signed 1945-09-15.
# For lack of anything better, use start of those days as the transition times.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	HK	1941	only	-	Apr	1	3:30	1:00	S
Rule	HK	1941	only	-	Sep	30	3:30	0	-
Rule	HK	1946	only	-	Apr	20	3:30	1:00	S
Rule	HK	1946	only	-	Dec	1	3:30	0	-
Rule	HK	1947	only	-	Apr	13	3:30	1:00	S
Rule	HK	1947	only	-	Dec	30	3:30	0	-
Rule	HK	1948	only	-	May	2	3:30	1:00	S
Rule	HK	1948	1951	-	Oct	lastSun	3:30	0	-
Rule	HK	1952	only	-	Oct	25	3:30	0	-
Rule	HK	1949	1953	-	Apr	Sun>=1	3:30	1:00	S
Rule	HK	1953	only	-	Nov	1	3:30	0	-
Rule	HK	1954	1964	-	Mar	Sun>=18	3:30	1:00	S
Rule	HK	1954	only	-	Oct	31	3:30	0	-
Rule	HK	1955	1964	-	Nov	Sun>=1	3:30	0	-
Rule	HK	1965	1976	-	Apr	Sun>=16	3:30	1:00	S
Rule	HK	1965	1976	-	Oct	Sun>=16	3:30	0	-
Rule	HK	1973	only	-	Dec	30	3:30	1:00	S
Rule	HK	1979	only	-	May	Sun>=8	3:30	1:00	S
Rule	HK	1979	only	-	Oct	Sun>=16	3:30	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Hong_Kong	7:36:42 -	LMT	1904 Oct 30
			8:00	HK	HK%sT	1941 Dec 25
			9:00	-	JST	1945 Sep 15
			8:00	HK	HK%sT

###############################################################################

# Taiwan

# Shanks & Pottenger write that Taiwan observed DST during 1945, when it
# was still controlled by Japan.  This is hard to believe, but we don't
# have any other information.

# From smallufo (2010-04-03):
# According to Taiwan's CWB,
# 
# http://www.cwb.gov.tw/V6/astronomy/cdata/summert.htm
# 
# Taipei has DST in 1979 between July 1st and Sep 30.

# From Arthur David Olson (2010-04-07):
# Here's Google's translation of the table at the bottom of the "summert.htm" page:
# Decade 	                                                    Name                      Start and end date
# Republic of China 34 years to 40 years (AD 1945-1951 years) Summer Time               May 1 to September 30
# 41 years of the Republic of China (AD 1952)                 Daylight Saving Time      March 1 to October 31
# Republic of China 42 years to 43 years (AD 1953-1954 years) Daylight Saving Time      April 1 to October 31
# In the 44 years to 45 years (AD 1955-1956 years)            Daylight Saving Time      April 1 to September 30
# Republic of China 46 years to 48 years (AD 1957-1959)       Summer Time               April 1 to September 30
# Republic of China 49 years to 50 years (AD 1960-1961)       Summer Time               June 1 to September 30
# Republic of China 51 years to 62 years (AD 1962-1973 years) Stop Summer Time
# Republic of China 63 years to 64 years (1974-1975 AD)       Daylight Saving Time      April 1 to September 30
# Republic of China 65 years to 67 years (1976-1978 AD)       Stop Daylight Saving Time
# Republic of China 68 years (AD 1979)                        Daylight Saving Time      July 1 to September 30
# Republic of China since 69 years (AD 1980)                  Stop Daylight Saving Time

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Taiwan	1945	1951	-	May	1	0:00	1:00	D
Rule	Taiwan	1945	1951	-	Oct	1	0:00	0	S
Rule	Taiwan	1952	only	-	Mar	1	0:00	1:00	D
Rule	Taiwan	1952	1954	-	Nov	1	0:00	0	S
Rule	Taiwan	1953	1959	-	Apr	1	0:00	1:00	D
Rule	Taiwan	1955	1961	-	Oct	1	0:00	0	S
Rule	Taiwan	1960	1961	-	Jun	1	0:00	1:00	D
Rule	Taiwan	1974	1975	-	Apr	1	0:00	1:00	D
Rule	Taiwan	1974	1975	-	Oct	1	0:00	0	S
Rule	Taiwan	1979	only	-	Jun	30	0:00	1:00	D
Rule	Taiwan	1979	only	-	Sep	30	0:00	0	S

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Taipei	8:06:00 -	LMT	1896 # or Taibei or T'ai-pei
			8:00	Taiwan	C%sT

# Macau (Macao, Aomen)
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Macau	1961	1962	-	Mar	Sun>=16	3:30	1:00	S
Rule	Macau	1961	1964	-	Nov	Sun>=1	3:30	0	-
Rule	Macau	1963	only	-	Mar	Sun>=16	0:00	1:00	S
Rule	Macau	1964	only	-	Mar	Sun>=16	3:30	1:00	S
Rule	Macau	1965	only	-	Mar	Sun>=16	0:00	1:00	S
Rule	Macau	1965	only	-	Oct	31	0:00	0	-
Rule	Macau	1966	1971	-	Apr	Sun>=16	3:30	1:00	S
Rule	Macau	1966	1971	-	Oct	Sun>=16	3:30	0	-
Rule	Macau	1972	1974	-	Apr	Sun>=15	0:00	1:00	S
Rule	Macau	1972	1973	-	Oct	Sun>=15	0:00	0	-
Rule	Macau	1974	1977	-	Oct	Sun>=15	3:30	0	-
Rule	Macau	1975	1977	-	Apr	Sun>=15	3:30	1:00	S
Rule	Macau	1978	1980	-	Apr	Sun>=15	0:00	1:00	S
Rule	Macau	1978	1980	-	Oct	Sun>=15	0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Macau	7:34:20 -	LMT	1912
			8:00	Macau	MO%sT	1999 Dec 20 # return to China
			8:00	PRC	C%sT


###############################################################################

# Cyprus
#
# Milne says the Eastern Telegraph Company used 2:14:00.  Stick with LMT.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Cyprus	1975	only	-	Apr	13	0:00	1:00	S
Rule	Cyprus	1975	only	-	Oct	12	0:00	0	-
Rule	Cyprus	1976	only	-	May	15	0:00	1:00	S
Rule	Cyprus	1976	only	-	Oct	11	0:00	0	-
Rule	Cyprus	1977	1980	-	Apr	Sun>=1	0:00	1:00	S
Rule	Cyprus	1977	only	-	Sep	25	0:00	0	-
Rule	Cyprus	1978	only	-	Oct	2	0:00	0	-
Rule	Cyprus	1979	1997	-	Sep	lastSun	0:00	0	-
Rule	Cyprus	1981	1998	-	Mar	lastSun	0:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Nicosia	2:13:28 -	LMT	1921 Nov 14
			2:00	Cyprus	EE%sT	1998 Sep
			2:00	EUAsia	EE%sT
# IATA SSIM (1998-09) has Cyprus using EU rules for the first time.

# Classically, Cyprus belongs to Asia; e.g. see Herodotus, Histories, I.72.
# However, for various reasons many users expect to find it under Europe.
Link	Asia/Nicosia	Europe/Nicosia

# Georgia
# From Paul Eggert (1994-11-19):
# Today's _Economist_ (p 60) reports that Georgia moved its clocks forward
# an hour recently, due to a law proposed by Zurab Murvanidze,
# an MP who went on a hunger strike for 11 days to force discussion about it!
# We have no details, but we'll guess they didn't move the clocks back in fall.
#
# From Mathew Englander, quoting AP (1996-10-23 13:05-04):
# Instead of putting back clocks at the end of October, Georgia
# will stay on daylight savings time this winter to save energy,
# President Eduard Shevardnadze decreed Wednesday.
#
# From the BBC via Joseph S. Myers (2004-06-27):
#
# Georgia moved closer to Western Europe on Sunday...  The former Soviet
# republic has changed its time zone back to that of Moscow.  As a result it
# is now just four hours ahead of Greenwich Mean Time, rather than five hours
# ahead.  The switch was decreed by the pro-Western president of Georgia,
# Mikhail Saakashvili, who said the change was partly prompted by the process
# of integration into Europe.

# From Teimuraz Abashidze (2005-11-07):
# Government of Georgia ... decided to NOT CHANGE daylight savings time on
# [Oct.] 30, as it was done before during last more than 10 years.
# Currently, we are in fact GMT +4:00, as before 30 October it was GMT
# +3:00.... The problem is, there is NO FORMAL LAW or governmental document
# about it.  As far as I can find, I was told, that there is no document,
# because we just DIDN'T ISSUE document about switching to winter time....
# I don't know what can be done, especially knowing that some years ago our
# DST rules where changed THREE TIMES during one month.


# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Tbilisi	2:59:16 -	LMT	1880
			2:59:16	-	TBMT	1924 May  2 # Tbilisi Mean Time
			3:00	-	TBIT	1957 Mar    # Tbilisi Time
			4:00 RussiaAsia TBI%sT	1991 Mar 31 2:00s
			3:00	1:00	TBIST	1991 Apr  9 # independence
			3:00 RussiaAsia GE%sT	1992 # Georgia Time
			3:00 E-EurAsia	GE%sT	1994 Sep lastSun
			4:00 E-EurAsia	GE%sT	1996 Oct lastSun
			4:00	1:00	GEST	1997 Mar lastSun
			4:00 E-EurAsia	GE%sT	2004 Jun 27
			3:00 RussiaAsia	GE%sT	2005 Mar lastSun 2:00
			4:00	-	GET

# East Timor

# See Indonesia for the 1945 transition.

# From Joao Carrascalao, brother of the former governor of East Timor, in
# 
# East Timor may be late for its millennium
#  (1999-12-26/31):
# Portugal tried to change the time forward in 1974 because the sun
# rises too early but the suggestion raised a lot of problems with the
# Timorese and I still don't think it would work today because it
# conflicts with their way of life.

# From Paul Eggert (2000-12-04):
# We don't have any record of the above attempt.
# Most likely our records are incomplete, but we have no better data.

# 
# From Manoel de Almeida e Silva, Deputy Spokesman for the UN Secretary-General
# (2000-08-16):
# The Cabinet of the East Timor Transition Administration decided
# today to advance East Timor's time by one hour.  The time change,
# which will be permanent, with no seasonal adjustment, will happen at
# midnight on Saturday, September 16.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Dili	8:22:20 -	LMT	1912
			8:00	-	TLT	1942 Feb 21 23:00 # E Timor Time
			9:00	-	JST	1945 Sep 23
			9:00	-	TLT	1976 May  3
			8:00	-	CIT	2000 Sep 17 00:00
			9:00	-	TLT

# India
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Kolkata	5:53:28 -	LMT	1880	# Kolkata
			5:53:20	-	HMT	1941 Oct    # Howrah Mean Time?
			6:30	-	BURT	1942 May 15 # Burma Time
			5:30	-	IST	1942 Sep
			5:30	1:00	IST	1945 Oct 15
			5:30	-	IST
# The following are like Asia/Kolkata:
#	Andaman Is
#	Lakshadweep (Laccadive, Minicoy and Amindivi Is)
#	Nicobar Is

# Indonesia
#
# From Gwillim Law (2001-05-28), overriding Shanks & Pottenger:
# 
# says that Indonesia's time zones changed on 1988-01-01.  Looking at some
# time zone maps, I think that must refer to Western Borneo (Kalimantan Barat
# and Kalimantan Tengah) switching from UTC+8 to UTC+7.
#
# From Paul Eggert (2007-03-10):
# Here is another correction to Shanks & Pottenger.
# JohnTWB writes that Japanese forces did not surrender control in
# Indonesia until 1945-09-01 00:00 at the earliest (in Jakarta) and
# other formal surrender ceremonies were September 9, 11, and 13, plus
# September 12 for the regional surrender to Mountbatten in Singapore.
# These would be the earliest possible times for a change.
# Regimes horaires pour le monde entier, by Henri Le Corre, (Editions
# Traditionnelles, 1987, Paris) says that Java and Madura switched
# from JST to UTC+07:30 on 1945-09-23, and gives 1944-09-01 for Jayapura
# (Hollandia).  For now, assume all Indonesian locations other than Jayapura
# switched on 1945-09-23.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Asia/Jakarta	7:07:12 -	LMT	1867 Aug 10
# Shanks & Pottenger say the next transition was at 1924 Jan 1 0:13,
# but this must be a typo.
			7:07:12	-	JMT	1923 Dec 31 23:47:12 # Jakarta
			7:20	-	JAVT	1932 Nov	 # Java Time
			7:30	-	WIT	1942 Mar 23
			9:00	-	JST	1945 Sep 23
			7:30	-	WIT	1948 May
			8:00	-	WIT	1950 May
			7:30	-	WIT	1964
			7:00	-	WIT
Zone Asia/Pontianak	7:17:20	-	LMT	1908 May
			7:17:20	-	PMT	1932 Nov    # Pontianak MT
			7:30	-	WIT	1942 Jan 29
			9:00	-	JST	1945 Sep 23
			7:30	-	WIT	1948 May
			8:00	-	WIT	1950 May
			7:30	-	WIT	1964
			8:00	-	CIT	1988 Jan  1
			7:00	-	WIT
Zone Asia/Makassar	7:57:36 -	LMT	1920
			7:57:36	-	MMT	1932 Nov    # Macassar MT
			8:00	-	CIT	1942 Feb  9
			9:00	-	JST	1945 Sep 23
			8:00	-	CIT
Zone Asia/Jayapura	9:22:48 -	LMT	1932 Nov
			9:00	-	EIT	1944 Sep  1
			9:30	-	CST	1964
			9:00	-	EIT

# Iran

# From Roozbeh Pournader (2003-03-15):
# This is an English translation of what I just found (originally in Persian).
# The Gregorian dates in brackets are mine:
#
#	Official Newspaper No. 13548-1370/6/25 [1991-09-16]
#	No. 16760/T233 H				1370/6/10 [1991-09-01]
#
#	The Rule About Change of the Official Time of the Country
#
#	The Board of Ministers, in the meeting dated 1370/5/23 [1991-08-14],
#	based on the suggestion number 2221/D dated 1370/4/22 [1991-07-13]
#	of the Country's Organization for Official and Employment Affairs,
#	and referring to the law for equating the working hours of workers
#	and officers in the whole country dated 1359/4/23 [1980-07-14], and
#	for synchronizing the official times of the country, agreed that:
#
#	The official time of the country will should move forward one hour
#	at the 24[:00] hours of the first day of Farvardin and should return
#	to its previous state at the 24[:00] hours of the 30th day of
#	Shahrivar.
#
#	First Deputy to the President - Hassan Habibi
#
# From personal experience, that agrees with what has been followed
# for at least the last 5 years.  Before that, for a few years, the
# date used was the first Thursday night of Farvardin and the last
# Thursday night of Shahrivar, but I can't give exact dates....
# I have also changed the abbreviations to what is considered correct
# here in Iran, IRST for regular time and IRDT for daylight saving time.
#
# From Roozbeh Pournader (2005-04-05):
# The text of the Iranian law, in effect since 1925, clearly mentions
# that the true solar year is the measure, and there is no arithmetic
# leap year calculation involved.  There has never been any serious
# plan to change that law....
#
# From Paul Eggert (2006-03-22):
# Go with Shanks & Pottenger before Sept. 1991, and with Pournader thereafter.
# I used Ed Reingold's cal-persia in GNU Emacs 21.2 to check Persian dates,
# stopping after 2037 when 32-bit time_t's overflow.
# That cal-persia used Birashk's approximation, which disagrees with the solar
# calendar predictions for the year 2025, so I corrected those dates by hand.
#
# From Oscar van Vlijmen (2005-03-30), writing about future
# discrepancies between cal-persia and the Iranian calendar:
# For 2091 solar-longitude-after yields 2091-03-20 08:40:07.7 UT for
# the vernal equinox and that gets so close to 12:00 some local
# Iranian time that the definition of the correct location needs to be
# known exactly, amongst other factors.  2157 is even closer:
# 2157-03-20 08:37:15.5 UT.  But the Gregorian year 2025 should give
# no interpretation problem whatsoever.  By the way, another instant
# in the near future where there will be a discrepancy between
# arithmetical and astronomical Iranian calendars will be in 2058:
# vernal equinox on 2058-03-20 09:03:05.9 UT.  The Java version of
# Reingold's/Dershowitz' calculator gives correctly the Gregorian date
# 2058-03-21 for 1 Farvardin 1437 (astronomical).
#
# From Steffen Thorsen (2006-03-22):
# Several of my users have reported that Iran will not observe DST anymore:
# http://www.irna.ir/en/news/view/line-17/0603193812164948.htm
#
# From Reuters (2007-09-16), with a heads-up from Jesper Norgaard Welen:
# ... the Guardian Council ... approved a law on Sunday to re-introduce
# daylight saving time ...
# http://uk.reuters.com/article/oilRpt/idUKBLA65048420070916
#
# From Roozbeh Pournader (2007-11-05):
# This is quoted from Official Gazette of the Islamic Republic of
# Iran, Volume 63, Number 18242, dated Tuesday 1386/6/24
# [2007-10-16]. I am doing the best translation I can:...
# The official time of the country will be moved forward for one hour
# on the 24 hours of the first day of the month of Farvardin and will
# be changed back to its previous state on the 24 hours of the
# thirtieth day of Shahrivar.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Iran	1978	1980	-	Mar	21	0:00	1:00	D
Rule	Iran	1978	only	-	Oct	21	0:00	0	S
Rule	Iran	1979	only	-	Sep	19	0:00	0	S
Rule	Iran	1980	only	-	Sep	23	0:00	0	S
Rule	Iran	1991	only	-	May	 3	0:00	1:00	D
Rule	Iran	1992	1995	-	Mar	22	0:00	1:00	D
Rule	Iran	1991	1995	-	Sep	22	0:00	0	S
Rule	Iran	1996	only	-	Mar	21	0:00	1:00	D
Rule	Iran	1996	only	-	Sep	21	0:00	0	S
Rule	Iran	1997	1999	-	Mar	22	0:00	1:00	D
Rule	Iran	1997	1999	-	Sep	22	0:00	0	S
Rule	Iran	2000	only	-	Mar	21	0:00	1:00	D
Rule	Iran	2000	only	-	Sep	21	0:00	0	S
Rule	Iran	2001	2003	-	Mar	22	0:00	1:00	D
Rule	Iran	2001	2003	-	Sep	22	0:00	0	S
Rule	Iran	2004	only	-	Mar	21	0:00	1:00	D
Rule	Iran	2004	only	-	Sep	21	0:00	0	S
Rule	Iran	2005	only	-	Mar	22	0:00	1:00	D
Rule	Iran	2005	only	-	Sep	22	0:00	0	S
Rule	Iran	2008	only	-	Mar	21	0:00	1:00	D
Rule	Iran	2008	only	-	Sep	21	0:00	0	S
Rule	Iran	2009	2011	-	Mar	22	0:00	1:00	D
Rule	Iran	2009	2011	-	Sep	22	0:00	0	S
Rule	Iran	2012	only	-	Mar	21	0:00	1:00	D
Rule	Iran	2012	only	-	Sep	21	0:00	0	S
Rule	Iran	2013	2015	-	Mar	22	0:00	1:00	D
Rule	Iran	2013	2015	-	Sep	22	0:00	0	S
Rule	Iran	2016	only	-	Mar	21	0:00	1:00	D
Rule	Iran	2016	only	-	Sep	21	0:00	0	S
Rule	Iran	2017	2019	-	Mar	22	0:00	1:00	D
Rule	Iran	2017	2019	-	Sep	22	0:00	0	S
Rule	Iran	2020	only	-	Mar	21	0:00	1:00	D
Rule	Iran	2020	only	-	Sep	21	0:00	0	S
Rule	Iran	2021	2023	-	Mar	22	0:00	1:00	D
Rule	Iran	2021	2023	-	Sep	22	0:00	0	S
Rule	Iran	2024	only	-	Mar	21	0:00	1:00	D
Rule	Iran	2024	only	-	Sep	21	0:00	0	S
Rule	Iran	2025	2027	-	Mar	22	0:00	1:00	D
Rule	Iran	2025	2027	-	Sep	22	0:00	0	S
Rule	Iran	2028	2029	-	Mar	21	0:00	1:00	D
Rule	Iran	2028	2029	-	Sep	21	0:00	0	S
Rule	Iran	2030	2031	-	Mar	22	0:00	1:00	D
Rule	Iran	2030	2031	-	Sep	22	0:00	0	S
Rule	Iran	2032	2033	-	Mar	21	0:00	1:00	D
Rule	Iran	2032	2033	-	Sep	21	0:00	0	S
Rule	Iran	2034	2035	-	Mar	22	0:00	1:00	D
Rule	Iran	2034	2035	-	Sep	22	0:00	0	S
Rule	Iran	2036	2037	-	Mar	21	0:00	1:00	D
Rule	Iran	2036	2037	-	Sep	21	0:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Tehran	3:25:44	-	LMT	1916
			3:25:44	-	TMT	1946	# Tehran Mean Time
			3:30	-	IRST	1977 Nov
			4:00	Iran	IR%sT	1979
			3:30	Iran	IR%sT


# Iraq
#
# From Jonathan Lennox (2000-06-12):
# An article in this week's Economist ("Inside the Saddam-free zone", p. 50 in
# the U.S. edition) on the Iraqi Kurds contains a paragraph:
# "The three northern provinces ... switched their clocks this spring and
# are an hour ahead of Baghdad."
#
# But Rives McDow (2000-06-18) quotes a contact in Iraqi-Kurdistan as follows:
# In the past, some Kurdish nationalists, as a protest to the Iraqi
# Government, did not adhere to daylight saving time.  They referred
# to daylight saving as Saddam time.  But, as of today, the time zone
# in Iraqi-Kurdistan is on standard time with Baghdad, Iraq.
#
# So we'll ignore the Economist's claim.

# From Steffen Thorsen (2008-03-10):
# The cabinet in Iraq abolished DST last week, according to the following
# news sources (in Arabic):
# 
# http://www.aljeeran.net/wesima_articles/news-20080305-98602.html
# 
# 
# http://www.aswataliraq.info/look/article.tpl?id=2047&IdLanguage=17&IdPublication=4&NrArticle=71743&NrIssue=1&NrSection=10
# 
#
# We have published a short article in English about the change:
# 
# http://www.timeanddate.com/news/time/iraq-dumps-daylight-saving.html
# 

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Iraq	1982	only	-	May	1	0:00	1:00	D
Rule	Iraq	1982	1984	-	Oct	1	0:00	0	S
Rule	Iraq	1983	only	-	Mar	31	0:00	1:00	D
Rule	Iraq	1984	1985	-	Apr	1	0:00	1:00	D
Rule	Iraq	1985	1990	-	Sep	lastSun	1:00s	0	S
Rule	Iraq	1986	1990	-	Mar	lastSun	1:00s	1:00	D
# IATA SSIM (1991/1996) says Apr 1 12:01am UTC; guess the `:01' is a typo.
# Shanks & Pottenger say Iraq did not observe DST 1992/1997; ignore this.
#
Rule	Iraq	1991	2007	-	Apr	 1	3:00s	1:00	D
Rule	Iraq	1991	2007	-	Oct	 1	3:00s	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Baghdad	2:57:40	-	LMT	1890
			2:57:36	-	BMT	1918	    # Baghdad Mean Time?
			3:00	-	AST	1982 May
			3:00	Iraq	A%sT


###############################################################################

# Israel

# From Ephraim Silverberg (2001-01-11):
#
# I coined "IST/IDT" circa 1988.  Until then there were three
# different abbreviations in use:
#
# JST  Jerusalem Standard Time [Danny Braniss, Hebrew University]
# IZT  Israel Zonal (sic) Time [Prof. Haim Papo, Technion]
# EEST Eastern Europe Standard Time [used by almost everyone else]
#
# Since timezones should be called by country and not capital cities,
# I ruled out JST.  As Israel is in Asia Minor and not Eastern Europe,
# EEST was equally unacceptable.  Since "zonal" was not compatible with
# any other timezone abbreviation, I felt that 'IST' was the way to go
# and, indeed, it has received almost universal acceptance in timezone
# settings in Israeli computers.
#
# In any case, I am happy to share timezone abbreviations with India,
# high on my favorite-country list (and not only because my wife's
# family is from India).

# From Shanks & Pottenger:
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Zion	1940	only	-	Jun	 1	0:00	1:00	D
Rule	Zion	1942	1944	-	Nov	 1	0:00	0	S
Rule	Zion	1943	only	-	Apr	 1	2:00	1:00	D
Rule	Zion	1944	only	-	Apr	 1	0:00	1:00	D
Rule	Zion	1945	only	-	Apr	16	0:00	1:00	D
Rule	Zion	1945	only	-	Nov	 1	2:00	0	S
Rule	Zion	1946	only	-	Apr	16	2:00	1:00	D
Rule	Zion	1946	only	-	Nov	 1	0:00	0	S
Rule	Zion	1948	only	-	May	23	0:00	2:00	DD
Rule	Zion	1948	only	-	Sep	 1	0:00	1:00	D
Rule	Zion	1948	1949	-	Nov	 1	2:00	0	S
Rule	Zion	1949	only	-	May	 1	0:00	1:00	D
Rule	Zion	1950	only	-	Apr	16	0:00	1:00	D
Rule	Zion	1950	only	-	Sep	15	3:00	0	S
Rule	Zion	1951	only	-	Apr	 1	0:00	1:00	D
Rule	Zion	1951	only	-	Nov	11	3:00	0	S
Rule	Zion	1952	only	-	Apr	20	2:00	1:00	D
Rule	Zion	1952	only	-	Oct	19	3:00	0	S
Rule	Zion	1953	only	-	Apr	12	2:00	1:00	D
Rule	Zion	1953	only	-	Sep	13	3:00	0	S
Rule	Zion	1954	only	-	Jun	13	0:00	1:00	D
Rule	Zion	1954	only	-	Sep	12	0:00	0	S
Rule	Zion	1955	only	-	Jun	11	2:00	1:00	D
Rule	Zion	1955	only	-	Sep	11	0:00	0	S
Rule	Zion	1956	only	-	Jun	 3	0:00	1:00	D
Rule	Zion	1956	only	-	Sep	30	3:00	0	S
Rule	Zion	1957	only	-	Apr	29	2:00	1:00	D
Rule	Zion	1957	only	-	Sep	22	0:00	0	S
Rule	Zion	1974	only	-	Jul	 7	0:00	1:00	D
Rule	Zion	1974	only	-	Oct	13	0:00	0	S
Rule	Zion	1975	only	-	Apr	20	0:00	1:00	D
Rule	Zion	1975	only	-	Aug	31	0:00	0	S
Rule	Zion	1985	only	-	Apr	14	0:00	1:00	D
Rule	Zion	1985	only	-	Sep	15	0:00	0	S
Rule	Zion	1986	only	-	May	18	0:00	1:00	D
Rule	Zion	1986	only	-	Sep	 7	0:00	0	S
Rule	Zion	1987	only	-	Apr	15	0:00	1:00	D
Rule	Zion	1987	only	-	Sep	13	0:00	0	S
Rule	Zion	1988	only	-	Apr	 9	0:00	1:00	D
Rule	Zion	1988	only	-	Sep	 3	0:00	0	S

# From Ephraim Silverberg
# (1997-03-04, 1998-03-16, 1998-12-28, 2000-01-17, 2000-07-25, 2004-12-22,
# and 2005-02-17):

# According to the Office of the Secretary General of the Ministry of
# Interior, there is NO set rule for Daylight-Savings/Standard time changes.
# One thing is entrenched in law, however: that there must be at least 150
# days of daylight savings time annually.  From 1993-1998, the change to
# daylight savings time was on a Friday morning from midnight IST to
# 1 a.m IDT; up until 1998, the change back to standard time was on a
# Saturday night from midnight daylight savings time to 11 p.m. standard
# time.  1996 is an exception to this rule where the change back to standard
# time took place on Sunday night instead of Saturday night to avoid
# conflicts with the Jewish New Year.  In 1999, the change to
# daylight savings time was still on a Friday morning but from
# 2 a.m. IST to 3 a.m. IDT; furthermore, the change back to standard time
# was also on a Friday morning from 2 a.m. IDT to 1 a.m. IST for
# 1999 only.  In the year 2000, the change to daylight savings time was
# similar to 1999, but although the change back will be on a Friday, it
# will take place from 1 a.m. IDT to midnight IST.  Starting in 2001, all
# changes to/from will take place at 1 a.m. old time, but now there is no
# rule as to what day of the week it will take place in as the start date
# (except in 2003) is the night after the Passover Seder (i.e. the eve
# of the 16th of Nisan in the lunar Hebrew calendar) and the end date
# (except in 2002) is three nights before Yom Kippur [Day of Atonement]
# (the eve of the 7th of Tishrei in the lunar Hebrew calendar).

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Zion	1989	only	-	Apr	30	0:00	1:00	D
Rule	Zion	1989	only	-	Sep	 3	0:00	0	S
Rule	Zion	1990	only	-	Mar	25	0:00	1:00	D
Rule	Zion	1990	only	-	Aug	26	0:00	0	S
Rule	Zion	1991	only	-	Mar	24	0:00	1:00	D
Rule	Zion	1991	only	-	Sep	 1	0:00	0	S
Rule	Zion	1992	only	-	Mar	29	0:00	1:00	D
Rule	Zion	1992	only	-	Sep	 6	0:00	0	S
Rule	Zion	1993	only	-	Apr	 2	0:00	1:00	D
Rule	Zion	1993	only	-	Sep	 5	0:00	0	S

# The dates for 1994-1995 were obtained from Office of the Spokeswoman for the
# Ministry of Interior, Jerusalem, Israel.  The spokeswoman can be reached by
# calling the office directly at 972-2-6701447 or 972-2-6701448.

# Rule	NAME    FROM    TO      TYPE    IN      ON      AT      SAVE    LETTER/S
Rule	Zion	1994	only	-	Apr	 1	0:00	1:00	D
Rule	Zion	1994	only	-	Aug	28	0:00	0	S
Rule	Zion	1995	only	-	Mar	31	0:00	1:00	D
Rule	Zion	1995	only	-	Sep	 3	0:00	0	S

# The dates for 1996 were determined by the Minister of Interior of the
# time, Haim Ramon.  The official announcement regarding 1996-1998
# (with the dates for 1997-1998 no longer being relevant) can be viewed at:
#
#   ftp://ftp.cs.huji.ac.il/pub/tz/announcements/1996-1998.ramon.ps.gz
#
# The dates for 1997-1998 were altered by his successor, Rabbi Eli Suissa.
#
# The official announcements for the years 1997-1999 can be viewed at:
#
#   ftp://ftp.cs.huji.ac.il/pub/tz/announcements/YYYY.ps.gz
#
#       where YYYY is the relevant year.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Zion	1996	only	-	Mar	15	0:00	1:00	D
Rule	Zion	1996	only	-	Sep	16	0:00	0	S
Rule	Zion	1997	only	-	Mar	21	0:00	1:00	D
Rule	Zion	1997	only	-	Sep	14	0:00	0	S
Rule	Zion	1998	only	-	Mar	20	0:00	1:00	D
Rule	Zion	1998	only	-	Sep	 6	0:00	0	S
Rule	Zion	1999	only	-	Apr	 2	2:00	1:00	D
Rule	Zion	1999	only	-	Sep	 3	2:00	0	S

# The Knesset Interior Committee has changed the dates for 2000 for
# the third time in just over a year and have set new dates for the
# years 2001-2004 as well.
#
# The official announcement for the start date of 2000 can be viewed at:
#
#	ftp://ftp.cs.huji.ac.il/pub/tz/announcements/2000-start.ps.gz
#
# The official announcement for the end date of 2000 and the dates
# for the years 2001-2004 can be viewed at:
#
#	ftp://ftp.cs.huji.ac.il/pub/tz/announcements/2000-2004.ps.gz

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Zion	2000	only	-	Apr	14	2:00	1:00	D
Rule	Zion	2000	only	-	Oct	 6	1:00	0	S
Rule	Zion	2001	only	-	Apr	 9	1:00	1:00	D
Rule	Zion	2001	only	-	Sep	24	1:00	0	S
Rule	Zion	2002	only	-	Mar	29	1:00	1:00	D
Rule	Zion	2002	only	-	Oct	 7	1:00	0	S
Rule	Zion	2003	only	-	Mar	28	1:00	1:00	D
Rule	Zion	2003	only	-	Oct	 3	1:00	0	S
Rule	Zion	2004	only	-	Apr	 7	1:00	1:00	D
Rule	Zion	2004	only	-	Sep	22	1:00	0	S

# The proposed law agreed upon by the Knesset Interior Committee on
# 2005-02-14 is that, for 2005 and beyond, DST starts at 02:00 the
# last Friday before April 2nd (i.e. the last Friday in March or April
# 1st itself if it falls on a Friday) and ends at 02:00 on the Saturday
# night _before_ the fast of Yom Kippur.
#
# Those who can read Hebrew can view the announcement at:
#
#	ftp://ftp.cs.huji.ac.il/pub/tz/announcements/2005+beyond.ps

# From Paul Eggert (2012-10-26):
# I used Ephraim Silverberg's dst-israel.el program
#  (2005-02-20)
# along with Ed Reingold's cal-hebrew in GNU Emacs 21.4,
# to generate the transitions from 2005 through 2012.
# (I replaced "lastFri" with "Fri>=26" by hand.)
# The spring transitions all correspond to the following Rule:
#
# Rule	Zion	2005	2012	-	Mar	Fri>=26	2:00	1:00	D
#
# but older zic implementations (e.g., Solaris 8) do not support
# "Fri>=26" to mean April 1 in years like 2005, so for now we list the
# springtime transitions explicitly.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Zion	2005	only	-	Apr	 1	2:00	1:00	D
Rule	Zion	2005	only	-	Oct	 9	2:00	0	S
Rule	Zion	2006	2010	-	Mar	Fri>=26	2:00	1:00	D
Rule	Zion	2006	only	-	Oct	 1	2:00	0	S
Rule	Zion	2007	only	-	Sep	16	2:00	0	S
Rule	Zion	2008	only	-	Oct	 5	2:00	0	S
Rule	Zion	2009	only	-	Sep	27	2:00	0	S
Rule	Zion	2010	only	-	Sep	12	2:00	0	S
Rule	Zion	2011	only	-	Apr	 1	2:00	1:00	D
Rule	Zion	2011	only	-	Oct	 2	2:00	0	S
Rule	Zion	2012	only	-	Mar	Fri>=26	2:00	1:00	D
Rule	Zion	2012	only	-	Sep	23	2:00	0	S

# From Ephraim Silverberg (2013-06-27):
# On June 23, 2013, the Israeli government approved changes to the
# Time Decree Law.  The next day, the changes passed the First Reading
# in the Knesset.  The law is expected to pass the Second and Third
# (final) Readings by the beginning of September 2013.
#
# As of 2013, DST starts at 02:00 on the Friday before the last Sunday
# in March.  DST ends at 02:00 on the last Sunday of October.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Zion	2013	max	-	Mar	Fri>=23	2:00	1:00	D
Rule	Zion	2013	max	-	Oct	lastSun	2:00	0	S

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Jerusalem	2:20:54 -	LMT	1880
			2:20:40	-	JMT	1918	# Jerusalem Mean Time?
			2:00	Zion	I%sT



###############################################################################

# Japan

# `9:00' and `JST' is from Guy Harris.

# From Paul Eggert (1995-03-06):
# Today's _Asahi Evening News_ (page 4) reports that Japan had
# daylight saving between 1948 and 1951, but ``the system was discontinued
# because the public believed it would lead to longer working hours.''

# From Mayumi Negishi in the 2005-08-10 Japan Times
# :
# Occupation authorities imposed daylight-saving time on Japan on
# [1948-05-01]....  But lack of prior debate and the execution of
# daylight-saving time just three days after the bill was passed generated
# deep hatred of the concept....  The Diet unceremoniously passed a bill to
# dump the unpopular system in October 1951, less than a month after the San
# Francisco Peace Treaty was signed.  (A government poll in 1951 showed 53%
# of the Japanese wanted to scrap daylight-saving time, as opposed to 30% who
# wanted to keep it.)

# From Paul Eggert (2006-03-22):
# Shanks & Pottenger write that DST in Japan during those years was as follows:
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Japan	1948	only	-	May	Sun>=1	2:00	1:00	D
Rule	Japan	1948	1951	-	Sep	Sat>=8	2:00	0	S
Rule	Japan	1949	only	-	Apr	Sun>=1	2:00	1:00	D
Rule	Japan	1950	1951	-	May	Sun>=1	2:00	1:00	D
# but the only locations using it (for birth certificates, presumably, since
# their audience is astrologers) were US military bases.  For now, assume
# that for most purposes daylight-saving time was observed; otherwise, what
# would have been the point of the 1951 poll?

# From Hideyuki Suzuki (1998-11-09):
# 'Tokyo' usually stands for the former location of Tokyo Astronomical
# Observatory: E 139 44' 40".90 (9h 18m 58s.727), N 35 39' 16".0.
# This data is from 'Rika Nenpyou (Chronological Scientific Tables) 1996'
# edited by National Astronomical Observatory of Japan....
# JST (Japan Standard Time) has been used since 1888-01-01 00:00 (JST).
# The law is enacted on 1886-07-07.

# From Hideyuki Suzuki (1998-11-16):
# The ordinance No. 51 (1886) established "standard time" in Japan,
# which stands for the time on E 135 degree.
# In the ordinance No. 167 (1895), "standard time" was renamed to "central
# standard time".  And the same ordinance also established "western standard
# time", which stands for the time on E 120 degree....  But "western standard
# time" was abolished in the ordinance No. 529 (1937).  In the ordinance No.
# 167, there is no mention regarding for what place western standard time is
# standard....
#
# I wrote "ordinance" above, but I don't know how to translate.
# In Japanese it's "chokurei", which means ordinance from emperor.

# Shanks & Pottenger claim JST in use since 1896, and that a few
# places (e.g. Ishigaki) use +0800; go with Suzuki.  Guess that all
# ordinances took effect on Jan 1.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Tokyo	9:18:59	-	LMT	1887 Dec 31 15:00u
			9:00	-	JST	1896
			9:00	-	CJT	1938
			9:00	Japan	J%sT
# Since 1938, all Japanese possessions have been like Asia/Tokyo.

# Jordan
#
# From 
# Jordan Week (1999-07-01)  via Steffen Thorsen (1999-09-09):
# Clocks in Jordan were forwarded one hour on Wednesday at midnight,
# in accordance with the government's decision to implement summer time
# all year round.
#
# From 
# Jordan Week (1999-09-30)  via Steffen Thorsen (1999-11-09):
# Winter time starts today Thursday, 30 September. Clocks will be turned back
# by one hour.  This is the latest government decision and it's final!
# The decision was taken because of the increase in working hours in
# government's departments from six to seven hours.
#
# From Paul Eggert (2005-11-22):
# Starting 2003 transitions are from Steffen Thorsen's web site timeanddate.com.
#
# From Steffen Thorsen (2005-11-23):
# For Jordan I have received multiple independent user reports every year
# about DST end dates, as the end-rule is different every year.
#
# From Steffen Thorsen (2006-10-01), after a heads-up from Hilal Malawi:
# http://www.petranews.gov.jo/nepras/2006/Sep/05/4000.htm
# "Jordan will switch to winter time on Friday, October 27".
#

# From Phil Pizzey (2009-04-02):
# ...I think I may have spotted an error in the timezone data for
# Jordan.
# The current (2009d) asia file shows Jordan going to daylight
# saving
# time on the last Thursday in March.
#
# Rule  Jordan      2000  max	-  Mar   lastThu     0:00s 1:00  S
#
# However timeanddate.com, which I usually find reliable, shows Jordan
# going to daylight saving time on the last Friday in March since 2002.
# Please see
# 
# http://www.timeanddate.com/worldclock/timezone.html?n=11
# 

# From Steffen Thorsen (2009-04-02):
# This single one might be good enough, (2009-03-24, Arabic):
# 
# http://petra.gov.jo/Artical.aspx?Lng=2&Section=8&Artical=95279
# 
#
# Google's translation:
#
# > The Council of Ministers decided in 2002 to adopt the principle of timely
# > submission of the summer at 60 minutes as of midnight on the last Thursday
# > of the month of March of each year.
#
# So - this means the midnight between Thursday and Friday since 2002.

# From Arthur David Olson (2009-04-06):
# We still have Jordan switching to DST on Thursdays in 2000 and 2001.

# From Steffen Thorsen (2012-10-25):
# Yesterday the government in Jordan announced that they will not
# switch back to standard time this winter, so the will stay on DST
# until about the same time next year (at least).
# http://www.petra.gov.jo/Public_News/Nws_NewsDetails.aspx?NewsID=88950
#
# From Paul Eggert (2012-10-25):
# For now, assume this is just a one-year measure.  If it becomes
# permanent, we should move Jordan from EET to AST effective tomorrow.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Jordan	1973	only	-	Jun	6	0:00	1:00	S
Rule	Jordan	1973	1975	-	Oct	1	0:00	0	-
Rule	Jordan	1974	1977	-	May	1	0:00	1:00	S
Rule	Jordan	1976	only	-	Nov	1	0:00	0	-
Rule	Jordan	1977	only	-	Oct	1	0:00	0	-
Rule	Jordan	1978	only	-	Apr	30	0:00	1:00	S
Rule	Jordan	1978	only	-	Sep	30	0:00	0	-
Rule	Jordan	1985	only	-	Apr	1	0:00	1:00	S
Rule	Jordan	1985	only	-	Oct	1	0:00	0	-
Rule	Jordan	1986	1988	-	Apr	Fri>=1	0:00	1:00	S
Rule	Jordan	1986	1990	-	Oct	Fri>=1	0:00	0	-
Rule	Jordan	1989	only	-	May	8	0:00	1:00	S
Rule	Jordan	1990	only	-	Apr	27	0:00	1:00	S
Rule	Jordan	1991	only	-	Apr	17	0:00	1:00	S
Rule	Jordan	1991	only	-	Sep	27	0:00	0	-
Rule	Jordan	1992	only	-	Apr	10	0:00	1:00	S
Rule	Jordan	1992	1993	-	Oct	Fri>=1	0:00	0	-
Rule	Jordan	1993	1998	-	Apr	Fri>=1	0:00	1:00	S
Rule	Jordan	1994	only	-	Sep	Fri>=15	0:00	0	-
Rule	Jordan	1995	1998	-	Sep	Fri>=15	0:00s	0	-
Rule	Jordan	1999	only	-	Jul	 1	0:00s	1:00	S
Rule	Jordan	1999	2002	-	Sep	lastFri	0:00s	0	-
Rule	Jordan	2000	2001	-	Mar	lastThu	0:00s	1:00	S
Rule	Jordan	2002	max	-	Mar	lastThu	24:00	1:00	S
Rule	Jordan	2003	only	-	Oct	24	0:00s	0	-
Rule	Jordan	2004	only	-	Oct	15	0:00s	0	-
Rule	Jordan	2005	only	-	Sep	lastFri	0:00s	0	-
Rule	Jordan	2006	2011	-	Oct	lastFri	0:00s	0	-
Rule	Jordan	2013	max	-	Oct	lastFri	0:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Amman	2:23:44 -	LMT	1931
			2:00	Jordan	EE%sT


# Kazakhstan

# From Paul Eggert (1996-11-22):
# Andrew Evtichov (1996-04-13) writes that Kazakhstan
# stayed in sync with Moscow after 1990, and that Aqtobe (formerly Aktyubinsk)
# and Aqtau (formerly Shevchenko) are the largest cities in their zones.
# Guess that Aqtau and Aqtobe diverged in 1995, since that's the first time
# IATA SSIM mentions a third time zone in Kazakhstan.

# From Paul Eggert (2006-03-22):
# German Iofis, ELSI, Almaty (2001-10-09) reports that Kazakhstan uses
# RussiaAsia rules, instead of switching at 00:00 as the IATA has it.
# Go with Shanks & Pottenger, who have them always using RussiaAsia rules.
# Also go with the following claims of Shanks & Pottenger:
#
# - Kazakhstan did not observe DST in 1991.
# - Qyzylorda switched from +5:00 to +6:00 on 1992-01-19 02:00.
# - Oral switched from +5:00 to +4:00 in spring 1989.

# 
# From Kazakhstan Embassy's News Bulletin #11 (2005-03-21):
# 
# The Government of Kazakhstan passed a resolution March 15 abolishing
# daylight saving time citing lack of economic benefits and health
# complications coupled with a decrease in productivity.
#
# From Branislav Kojic (in Astana) via Gwillim Law (2005-06-28):
# ... what happened was that the former Kazakhstan Eastern time zone
# was "blended" with the Central zone.  Therefore, Kazakhstan now has
# two time zones, and difference between them is one hour.  The zone
# closer to UTC is the former Western zone (probably still called the
# same), encompassing four provinces in the west: Aqtobe, Atyrau,
# Mangghystau, and West Kazakhstan.  The other zone encompasses
# everything else....  I guess that would make Kazakhstan time zones
# de jure UTC+5 and UTC+6 respectively.

#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
#
# Almaty (formerly Alma-Ata), representing most locations in Kazakhstan
Zone	Asia/Almaty	5:07:48 -	LMT	1924 May  2 # or Alma-Ata
			5:00	-	ALMT	1930 Jun 21 # Alma-Ata Time
			6:00 RussiaAsia ALM%sT	1991
			6:00	-	ALMT	1992
			6:00 RussiaAsia	ALM%sT	2005 Mar 15
			6:00	-	ALMT
# Qyzylorda (aka Kyzylorda, Kizilorda, Kzyl-Orda, etc.)
Zone	Asia/Qyzylorda	4:21:52 -	LMT	1924 May  2
			4:00	-	KIZT	1930 Jun 21 # Kizilorda Time
			5:00	-	KIZT	1981 Apr  1
			5:00	1:00	KIZST	1981 Oct  1
			6:00	-	KIZT	1982 Apr  1
			5:00 RussiaAsia	KIZ%sT	1991
			5:00	-	KIZT	1991 Dec 16 # independence
			5:00	-	QYZT	1992 Jan 19 2:00
			6:00 RussiaAsia	QYZ%sT	2005 Mar 15
			6:00	-	QYZT
# Aqtobe (aka Aktobe, formerly Akt'ubinsk)
Zone	Asia/Aqtobe	3:48:40	-	LMT	1924 May  2
			4:00	-	AKTT	1930 Jun 21 # Aktyubinsk Time
			5:00	-	AKTT	1981 Apr  1
			5:00	1:00	AKTST	1981 Oct  1
			6:00	-	AKTT	1982 Apr  1
			5:00 RussiaAsia	AKT%sT	1991
			5:00	-	AKTT	1991 Dec 16 # independence
			5:00 RussiaAsia	AQT%sT	2005 Mar 15 # Aqtobe Time
			5:00	-	AQTT
# Mangghystau
# Aqtau was not founded until 1963, but it represents an inhabited region,
# so include time stamps before 1963.
Zone	Asia/Aqtau	3:21:04	-	LMT	1924 May  2
			4:00	-	FORT	1930 Jun 21 # Fort Shevchenko T
			5:00	-	FORT	1963
			5:00	-	SHET	1981 Oct  1 # Shevchenko Time
			6:00	-	SHET	1982 Apr  1
			5:00 RussiaAsia	SHE%sT	1991
			5:00	-	SHET	1991 Dec 16 # independence
			5:00 RussiaAsia	AQT%sT	1995 Mar lastSun 2:00 # Aqtau Time
			4:00 RussiaAsia	AQT%sT	2005 Mar 15
			5:00	-	AQTT
# West Kazakhstan
Zone	Asia/Oral	3:25:24	-	LMT	1924 May  2 # or Ural'sk
			4:00	-	URAT	1930 Jun 21 # Ural'sk time
			5:00	-	URAT	1981 Apr  1
			5:00	1:00	URAST	1981 Oct  1
			6:00	-	URAT	1982 Apr  1
			5:00 RussiaAsia	URA%sT	1989 Mar 26 2:00
			4:00 RussiaAsia	URA%sT	1991
			4:00	-	URAT	1991 Dec 16 # independence
			4:00 RussiaAsia	ORA%sT	2005 Mar 15 # Oral Time
			5:00	-	ORAT

# Kyrgyzstan (Kirgizstan)
# Transitions through 1991 are from Shanks & Pottenger.

# From Paul Eggert (2005-08-15):
# According to an article dated today in the Kyrgyzstan Development Gateway
# 
# Kyrgyzstan is canceling the daylight saving time system.  I take the article
# to mean that they will leave their clocks at 6 hours ahead of UTC.
# From Malik Abdugaliev (2005-09-21):
# Our government cancels daylight saving time 6th of August 2005.
# From 2005-08-12 our GMT-offset is +6, w/o any daylight saving.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Kyrgyz	1992	1996	-	Apr	Sun>=7	0:00s	1:00	S
Rule	Kyrgyz	1992	1996	-	Sep	lastSun	0:00	0	-
Rule	Kyrgyz	1997	2005	-	Mar	lastSun	2:30	1:00	S
Rule	Kyrgyz	1997	2004	-	Oct	lastSun	2:30	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Bishkek	4:58:24 -	LMT	1924 May  2
			5:00	-	FRUT	1930 Jun 21 # Frunze Time
			6:00 RussiaAsia FRU%sT	1991 Mar 31 2:00s
			5:00	1:00	FRUST	1991 Aug 31 2:00 # independence
			5:00	Kyrgyz	KG%sT	2005 Aug 12    # Kyrgyzstan Time
			6:00	-	KGT

###############################################################################

# Korea (North and South)

# From Annie I. Bang (2006-07-10) in
# :
# The Ministry of Commerce, Industry and Energy has already
# commissioned a research project [to reintroduce DST] and has said
# the system may begin as early as 2008....  Korea ran a daylight
# saving program from 1949-61 but stopped it during the 1950-53 Korean War.

# From Shanks & Pottenger:
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	ROK	1960	only	-	May	15	0:00	1:00	D
Rule	ROK	1960	only	-	Sep	13	0:00	0	S
Rule	ROK	1987	1988	-	May	Sun>=8	0:00	1:00	D
Rule	ROK	1987	1988	-	Oct	Sun>=8	0:00	0	S

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Seoul	8:27:52	-	LMT	1890
			8:30	-	KST	1904 Dec
			9:00	-	KST	1928
			8:30	-	KST	1932
			9:00	-	KST	1954 Mar 21
			8:00	ROK	K%sT	1961 Aug 10
			8:30	-	KST	1968 Oct
			9:00	ROK	K%sT
Zone	Asia/Pyongyang	8:23:00 -	LMT	1890
			8:30	-	KST	1904 Dec
			9:00	-	KST	1928
			8:30	-	KST	1932
			9:00	-	KST	1954 Mar 21
			8:00	-	KST	1961 Aug 10
			9:00	-	KST

###############################################################################

# Kuwait
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# From the Arab Times (2007-03-14):
# The Civil Service Commission (CSC) has approved a proposal forwarded
# by MP Ahmad Baqer on implementing the daylight saving time (DST) in
# Kuwait starting from April until the end of Sept this year, reports Al-Anba.
# .
# From Paul Eggert (2007-03-29):
# We don't know the details, or whether the approval means it'll happen,
# so for now we assume no DST.
Zone	Asia/Kuwait	3:11:56 -	LMT	1950
			3:00	-	AST

# Laos
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Vientiane	6:50:24 -	LMT	1906 Jun  9 # or Viangchan
			7:06:20	-	SMT	1911 Mar 11 0:01 # Saigon MT?
			7:00	-	ICT	1912 May
			8:00	-	ICT	1931 May
			7:00	-	ICT

# Lebanon
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Lebanon	1920	only	-	Mar	28	0:00	1:00	S
Rule	Lebanon	1920	only	-	Oct	25	0:00	0	-
Rule	Lebanon	1921	only	-	Apr	3	0:00	1:00	S
Rule	Lebanon	1921	only	-	Oct	3	0:00	0	-
Rule	Lebanon	1922	only	-	Mar	26	0:00	1:00	S
Rule	Lebanon	1922	only	-	Oct	8	0:00	0	-
Rule	Lebanon	1923	only	-	Apr	22	0:00	1:00	S
Rule	Lebanon	1923	only	-	Sep	16	0:00	0	-
Rule	Lebanon	1957	1961	-	May	1	0:00	1:00	S
Rule	Lebanon	1957	1961	-	Oct	1	0:00	0	-
Rule	Lebanon	1972	only	-	Jun	22	0:00	1:00	S
Rule	Lebanon	1972	1977	-	Oct	1	0:00	0	-
Rule	Lebanon	1973	1977	-	May	1	0:00	1:00	S
Rule	Lebanon	1978	only	-	Apr	30	0:00	1:00	S
Rule	Lebanon	1978	only	-	Sep	30	0:00	0	-
Rule	Lebanon	1984	1987	-	May	1	0:00	1:00	S
Rule	Lebanon	1984	1991	-	Oct	16	0:00	0	-
Rule	Lebanon	1988	only	-	Jun	1	0:00	1:00	S
Rule	Lebanon	1989	only	-	May	10	0:00	1:00	S
Rule	Lebanon	1990	1992	-	May	1	0:00	1:00	S
Rule	Lebanon	1992	only	-	Oct	4	0:00	0	-
Rule	Lebanon	1993	max	-	Mar	lastSun	0:00	1:00	S
Rule	Lebanon	1993	1998	-	Sep	lastSun	0:00	0	-
Rule	Lebanon	1999	max	-	Oct	lastSun	0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Beirut	2:22:00 -	LMT	1880
			2:00	Lebanon	EE%sT

# Malaysia
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	NBorneo	1935	1941	-	Sep	14	0:00	0:20	TS # one-Third Summer
Rule	NBorneo	1935	1941	-	Dec	14	0:00	0	-
#
# peninsular Malaysia
# The data here are taken from Mok Ly Yng (2003-10-30)
# .
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Asia/Kuala_Lumpur	6:46:46 -	LMT	1901 Jan  1
			6:55:25	-	SMT	1905 Jun  1 # Singapore M.T.
			7:00	-	MALT	1933 Jan  1 # Malaya Time
			7:00	0:20	MALST	1936 Jan  1
			7:20	-	MALT	1941 Sep  1
			7:30	-	MALT	1942 Feb 16
			9:00	-	JST	1945 Sep 12
			7:30	-	MALT	1982 Jan  1
			8:00	-	MYT	# Malaysia Time
# Sabah & Sarawak
# From Paul Eggert (2006-03-22):
# The data here are mostly from Shanks & Pottenger, but the 1942, 1945 and 1982
# transition dates are from Mok Ly Yng.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Asia/Kuching	7:21:20	-	LMT	1926 Mar
			7:30	-	BORT	1933	# Borneo Time
			8:00	NBorneo	BOR%sT	1942 Feb 16
			9:00	-	JST	1945 Sep 12
			8:00	-	BORT	1982 Jan  1
			8:00	-	MYT

# Maldives
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Indian/Maldives	4:54:00 -	LMT	1880	# Male
			4:54:00	-	MMT	1960	# Male Mean Time
			5:00	-	MVT		# Maldives Time

# Mongolia

# Shanks & Pottenger say that Mongolia has three time zones, but
# usno1995 and the CIA map Standard Time Zones of the World (2005-03)
# both say that it has just one.

# From Oscar van Vlijmen (1999-12-11):
# 
# General Information Mongolia
#  (1999-09)
# "Time: Mongolia has two time zones. Three westernmost provinces of
# Bayan-Ulgii, Uvs, and Hovd are one hour earlier than the capital city, and
# the rest of the country follows the Ulaanbaatar time, which is UTC/GMT plus
# eight hours."

# From Rives McDow (1999-12-13):
# Mongolia discontinued the use of daylight savings time in 1999; 1998
# being the last year it was implemented.  The dates of implementation I am
# unsure of, but most probably it was similar to Russia, except for the time
# of implementation may have been different....
# Some maps in the past have indicated that there was an additional time
# zone in the eastern part of Mongolia, including the provinces of Dornod,
# Suhbaatar, and possibly Khentij.

# From Paul Eggert (1999-12-15):
# Naming and spelling is tricky in Mongolia.
# We'll use Hovd (also spelled Chovd and Khovd) to represent the west zone;
# the capital of the Hovd province is sometimes called Hovd, sometimes Dund-Us,
# and sometimes Jirgalanta (with variant spellings), but the name Hovd
# is good enough for our purposes.

# From Rives McDow (2001-05-13):
# In addition to Mongolia starting daylight savings as reported earlier
# (adopted DST on 2001-04-27 02:00 local time, ending 2001-09-28),
# there are three time zones.
#
# Provinces [at 7:00]: Bayan-ulgii, Uvs, Khovd, Zavkhan, Govi-Altai
# Provinces [at 8:00]: Khovsgol, Bulgan, Arkhangai, Khentii, Tov,
#	Bayankhongor, Ovorkhangai, Dundgovi, Dornogovi, Omnogovi
# Provinces [at 9:00]: Dornod, Sukhbaatar
#
# [The province of Selenge is omitted from the above lists.]

# From Ganbold Ts., Ulaanbaatar (2004-04-17):
# Daylight saving occurs at 02:00 local time last Saturday of March.
# It will change back to normal at 02:00 local time last Saturday of
# September.... As I remember this rule was changed in 2001.
#
# From Paul Eggert (2004-04-17):
# For now, assume Rives McDow's informant got confused about Friday vs
# Saturday, and that his 2001 dates should have 1 added to them.

# From Paul Eggert (2005-07-26):
# We have wildly conflicting information about Mongolia's time zones.
# Bill Bonnet (2005-05-19) reports that the US Embassy in Ulaanbaatar says
# there is only one time zone and that DST is observed, citing Microsoft
# Windows XP as the source.  Risto Nykanen (2005-05-16) reports that
# travelmongolia.org says there are two time zones (UTC+7, UTC+8) with no DST.
# Oscar van Vlijmen (2005-05-20) reports that the Mongolian Embassy in
# Washington, DC says there are two time zones, with DST observed.
# He also found
# 
# which also says that there is DST, and which has a comment by "Toddius"
# (2005-03-31 06:05 +0700) saying "Mongolia actually has 3.5 time zones.
# The West (OLGII) is +7 GMT, most of the country is ULAT is +8 GMT
# and some Eastern provinces are +9 GMT but Sukhbaatar Aimag is SUHK +8.5 GMT.
# The SUKH timezone is new this year, it is one of the few things the
# parliament passed during the tumultuous winter session."
# For now, let's ignore this information, until we have more confirmation.

# From Ganbold Ts. (2007-02-26):
# Parliament of Mongolia has just changed the daylight-saving rule in February.
# They decided not to adopt daylight-saving time....
# http://www.mongolnews.mn/index.php?module=unuudur&sec=view&id=15742

# From Deborah Goldsmith (2008-03-30):
# We received a bug report claiming that the tz database UTC offset for
# Asia/Choibalsan (GMT+09:00) is incorrect, and that it should be GMT
# +08:00 instead. Different sources appear to disagree with the tz
# database on this, e.g.:
#
# 
# http://www.timeanddate.com/worldclock/city.html?n=1026
# 
# 
# http://www.worldtimeserver.com/current_time_in_MN.aspx
# 
#
# both say GMT+08:00.

# From Steffen Thorsen (2008-03-31):
# eznis airways, which operates several domestic flights, has a flight
# schedule here:
# 
# http://www.eznis.com/Container.jsp?id=112
# 
# (click the English flag for English)
#
# There it appears that flights between Choibalsan and Ulaanbatar arrive
# about 1:35 - 1:50 hours later in local clock time, no matter the
# direction, while Ulaanbaatar-Khvod takes 2 hours in the Eastern
# direction and 3:35 back, which indicates that Ulaanbatar and Khvod are
# in different time zones (like we know about), while Choibalsan and
# Ulaanbatar are in the same time zone (correction needed).

# From Arthur David Olson (2008-05-19):
# Assume that Choibalsan is indeed offset by 8:00.
# XXX--in the absence of better information, assume that transition
# was at the start of 2008-03-31 (the day of Steffen Thorsen's report);
# this is almost surely wrong.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Mongol	1983	1984	-	Apr	1	0:00	1:00	S
Rule	Mongol	1983	only	-	Oct	1	0:00	0	-
# Shanks & Pottenger and IATA SSIM say 1990s switches occurred at 00:00,
# but McDow says the 2001 switches occurred at 02:00.  Also, IATA SSIM
# (1996-09) says 1996-10-25.  Go with Shanks & Pottenger through 1998.
#
# Shanks & Pottenger say that the Sept. 1984 through Sept. 1990 switches
# in Choibalsan (more precisely, in Dornod and Sukhbaatar) took place
# at 02:00 standard time, not at 00:00 local time as in the rest of
# the country.  That would be odd, and possibly is a result of their
# correction of 02:00 (in the previous edition) not being done correctly
# in the latest edition; so ignore it for now.

Rule	Mongol	1985	1998	-	Mar	lastSun	0:00	1:00	S
Rule	Mongol	1984	1998	-	Sep	lastSun	0:00	0	-
# IATA SSIM (1999-09) says Mongolia no longer observes DST.
Rule	Mongol	2001	only	-	Apr	lastSat	2:00	1:00	S
Rule	Mongol	2001	2006	-	Sep	lastSat	2:00	0	-
Rule	Mongol	2002	2006	-	Mar	lastSat	2:00	1:00	S

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# Hovd, a.k.a. Chovd, Dund-Us, Dzhargalant, Khovd, Jirgalanta
Zone	Asia/Hovd	6:06:36 -	LMT	1905 Aug
			6:00	-	HOVT	1978	# Hovd Time
			7:00	Mongol	HOV%sT
# Ulaanbaatar, a.k.a. Ulan Bataar, Ulan Bator, Urga
Zone	Asia/Ulaanbaatar 7:07:32 -	LMT	1905 Aug
			7:00	-	ULAT	1978	# Ulaanbaatar Time
			8:00	Mongol	ULA%sT
# Choibalsan, a.k.a. Bajan Tuemen, Bajan Tumen, Chojbalsan,
# Choybalsan, Sanbejse, Tchoibalsan
Zone	Asia/Choibalsan	7:38:00 -	LMT	1905 Aug
			7:00	-	ULAT	1978
			8:00	-	ULAT	1983 Apr
			9:00	Mongol	CHO%sT	2008 Mar 31 # Choibalsan Time
			8:00	Mongol	CHO%sT

# Nepal
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Kathmandu	5:41:16 -	LMT	1920
			5:30	-	IST	1986
			5:45	-	NPT	# Nepal Time

# Oman

# Milne says 3:54:24 was the meridian of the Muscat Tidal Observatory.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Muscat	3:54:24 -	LMT	1920
			4:00	-	GST

# Pakistan

# From Rives McDow (2002-03-13):
# I have been advised that Pakistan has decided to adopt dst on a
# TRIAL basis for one year, starting 00:01 local time on April 7, 2002
# and ending at 00:01 local time October 6, 2002.  This is what I was
# told, but I believe that the actual time of change may be 00:00; the
# 00:01 was to make it clear which day it was on.

# From Paul Eggert (2002-03-15):
# Jesper Norgaard found this URL:
# http://www.pak.gov.pk/public/news/app/app06_dec.htm
# (dated 2001-12-06) which says that the Cabinet adopted a scheme "to
# advance the clocks by one hour on the night between the first
# Saturday and Sunday of April and revert to the original position on
# 15th October each year".  This agrees with McDow's 04-07 at 00:00,
# but disagrees about the October transition, and makes it sound like
# it's not on a trial basis.  Also, the "between the first Saturday
# and Sunday of April" phrase, if taken literally, means that the
# transition takes place at 00:00 on the first Sunday on or after 04-02.

# From Paul Eggert (2003-02-09):
# DAWN  reported on 2002-10-05
# that 2002 DST ended that day at midnight.  Go with McDow for now.

# From Steffen Thorsen (2003-03-14):
# According to http://www.dawn.com/2003/03/07/top15.htm
# there will be no DST in Pakistan this year:
#
# ISLAMABAD, March 6: Information and Media Development Minister Sheikh
# Rashid Ahmed on Thursday said the cabinet had reversed a previous
# decision to advance clocks by one hour in summer and put them back by
# one hour in winter with the aim of saving light hours and energy.
#
# The minister told a news conference that the experiment had rather
# shown 8 per cent higher consumption of electricity.

# From Alex Krivenyshev (2008-05-15):
#
# Here is an article that Pakistan plan to introduce Daylight Saving Time
# on June 1, 2008 for 3 months.
#
# "... The federal cabinet on Wednesday announced a new conservation plan to help
# reduce load shedding by approving the closure of commercial centres at 9pm and
# moving clocks forward by one hour for the next three months.
# ...."
#
# 
# http://www.worldtimezone.net/dst_news/dst_news_pakistan01.html
# 
# OR
# 
# http://www.dailytimes.com.pk/default.asp?page=2008%5C05%5C15%5Cstory_15-5-2008_pg1_4
# 

# From Arthur David Olson (2008-05-19):
# XXX--midnight transitions is a guess; 2008 only is a guess.

# From Alexander Krivenyshev (2008-08-28):
# Pakistan government has decided to keep the watches one-hour advanced
# for another 2 months--plan to return to Standard Time on October 31
# instead of August 31.
#
# 
# http://www.worldtimezone.com/dst_news/dst_news_pakistan02.html
# 
# OR
# 
# http://dailymailnews.com/200808/28/news/dmbrn03.html
# 

# From Alexander Krivenyshev (2009-04-08):
# Based on previous media reports that "... proposed plan to
# advance clocks by one hour from May 1 will cause disturbance
# to the working schedules rather than bringing discipline in
# official working."
# 
# http://www.thenews.com.pk/daily_detail.asp?id=171280
# 
#
# recent news that instead of May 2009 - Pakistan plan to
# introduce DST from April 15, 2009
#
# FYI: Associated Press Of Pakistan
# April 08, 2009
# Cabinet okays proposal to advance clocks by one hour from April 15
# 
# http://www.app.com.pk/en_/index.php?option=com_content&task=view&id=73043&Itemid=1
# 
#
# or
#
# 
# http://www.worldtimezone.com/dst_news/dst_news_pakistan05.html
# 
#
# ....
# The Federal Cabinet on Wednesday approved the proposal to
# advance clocks in the country by one hour from April 15 to
# conserve energy"

# From Steffen Thorsen (2009-09-17):
# "The News International," Pakistan reports that: "The Federal
# Government has decided to restore the previous time by moving the
# clocks backward by one hour from October 1. A formal announcement to
# this effect will be made after the Prime Minister grants approval in
# this regard."
# 
# http://www.thenews.com.pk/updates.asp?id=87168
# 

# From Alexander Krivenyshev (2009-09-28):
# According to Associated Press Of Pakistan, it is confirmed that
# Pakistan clocks across the country would be turned back by an hour from October
# 1, 2009.
#
# "Clocks to go back one hour from 1 Oct"
# 
# http://www.app.com.pk/en_/index.php?option=com_content&task=view&id=86715&Itemid=2
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_pakistan07.htm
# 

# From Steffen Thorsen (2009-09-29):
# Alexander Krivenyshev wrote:
# > According to Associated Press Of Pakistan, it is confirmed that
# > Pakistan clocks across the country would be turned back by an hour from October
# > 1, 2009.
#
# Now they seem to have changed their mind, November 1 is the new date:
# 
# http://www.thenews.com.pk/top_story_detail.asp?Id=24742
# 
# "The country's clocks will be reversed by one hour on November 1.
# Officials of Federal Ministry for Interior told this to Geo News on
# Monday."
#
# And more importantly, it seems that these dates will be kept every year:
# "It has now been decided that clocks will be wound forward by one hour
# on April 15 and reversed by an hour on November 1 every year without
# obtaining prior approval, the officials added."
#
# We have confirmed this year's end date with both with the Ministry of
# Water and Power and the Pakistan Electric Power Company:
# 
# http://www.timeanddate.com/news/time/pakistan-ends-dst09.html
# 

# From Christoph Goehre (2009-10-01):
# [T]he German Consulate General in Karachi reported me today that Pakistan
# will go back to standard time on 1st of November.

# From Steffen Thorsen (2010-03-26):
# Steffen Thorsen wrote:
# > On Thursday (2010-03-25) it was announced that DST would start in
# > Pakistan on 2010-04-01.
# >
# > Then today, the president said that they might have to revert the
# > decision if it is not supported by the parliament. So at the time
# > being, it seems unclear if DST will be actually observed or not - but
# > April 1 could be a more likely date than April 15.
# Now, it seems that the decision to not observe DST in final:
#
# "Govt Withdraws Plan To Advance Clocks"
# 
# http://www.apakistannews.com/govt-withdraws-plan-to-advance-clocks-172041
# 
#
# "People laud PM's announcement to end DST"
# 
# http://www.app.com.pk/en_/index.php?option=com_content&task=view&id=99374&Itemid=2
# 

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule Pakistan	2002	only	-	Apr	Sun>=2	0:01	1:00	S
Rule Pakistan	2002	only	-	Oct	Sun>=2	0:01	0	-
Rule Pakistan	2008	only	-	Jun	1	0:00	1:00	S
Rule Pakistan	2008	only	-	Nov	1	0:00	0	-
Rule Pakistan	2009	only	-	Apr	15	0:00	1:00	S
Rule Pakistan	2009	only	-	Nov	1	0:00	0	-

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Karachi	4:28:12 -	LMT	1907
			5:30	-	IST	1942 Sep
			5:30	1:00	IST	1945 Oct 15
			5:30	-	IST	1951 Sep 30
			5:00	-	KART	1971 Mar 26 # Karachi Time
			5:00 Pakistan	PK%sT	# Pakistan Time

# Palestine

# From Amos Shapir (1998-02-15):
#
# From 1917 until 1948-05-15, all of Palestine, including the parts now
# known as the Gaza Strip and the West Bank, was under British rule.
# Therefore the rules given for Israel for that period, apply there too...
#
# The Gaza Strip was under Egyptian rule between 1948-05-15 until 1967-06-05
# (except a short occupation by Israel from 1956-11 till 1957-03, but no
# time zone was affected then).  It was never formally annexed to Egypt,
# though.
#
# The rest of Palestine was under Jordanian rule at that time, formally
# annexed in 1950 as the West Bank (and the word "Trans" was dropped from
# the country's previous name of "the Hashemite Kingdom of the
# Trans-Jordan").  So the rules for Jordan for that time apply.  Major
# towns in that area are Nablus (Shchem), El-Halil (Hebron), Ramallah, and
# East Jerusalem.
#
# Both areas were occupied by Israel in June 1967, but not annexed (except
# for East Jerusalem).  They were on Israel time since then; there might
# have been a Military Governor's order about time zones, but I'm not aware
# of any (such orders may have been issued semi-annually whenever summer
# time was in effect, but maybe the legal aspect of time was just neglected).
#
# The Palestinian Authority was established in 1993, and got hold of most
# towns in the West Bank and Gaza by 1995.  I know that in order to
# demonstrate...independence, they have been switching to
# summer time and back on a different schedule than Israel's, but I don't
# know when this was started, or what algorithm is used (most likely the
# Jordanian one).
#
# To summarize, the table should probably look something like that:
#
# Area \ when | 1918-1947 | 1948-1967 | 1967-1995 | 1996-
# ------------+-----------+-----------+-----------+-----------
# Israel      | Zion      | Zion      | Zion      | Zion
# West bank   | Zion      | Jordan    | Zion      | Jordan
# Gaza        | Zion      | Egypt     | Zion      | Jordan
#
# I guess more info may be available from the PA's web page (if/when they
# have one).

# From Paul Eggert (2006-03-22):
# Shanks & Pottenger write that Gaza did not observe DST until 1957, but go
# with Shapir and assume that it observed DST from 1940 through 1947,
# and that it used Jordanian rules starting in 1996.
# We don't yet need a separate entry for the West Bank, since
# the only differences between it and Gaza that we know about
# occurred before our cutoff date of 1970.
# However, as we get more information, we may need to add entries
# for parts of the West Bank as they transitioned from Israel's rules
# to Palestine's rules.

# From IINS News Service - Israel - 1998-03-23 10:38:07 Israel time,
# forwarded by Ephraim Silverberg:
#
# Despite the fact that Israel changed over to daylight savings time
# last week, the PLO Authority (PA) has decided not to turn its clocks
# one-hour forward at this time.  As a sign of independence from Israeli rule,
# the PA has decided to implement DST in April.

# From Paul Eggert (1999-09-20):
# Daoud Kuttab writes in
# 
# Holiday havoc
#  (Jerusalem Post, 1999-04-22) that
# the Palestinian National Authority changed to DST on 1999-04-15.
# I vaguely recall that they switch back in October (sorry, forgot the source).
# For now, let's assume that the spring switch was at 24:00,
# and that they switch at 0:00 on the 3rd Fridays of April and October.

# From Paul Eggert (2005-11-22):
# Starting 2004 transitions are from Steffen Thorsen's web site timeanddate.com.

# From Steffen Thorsen (2005-11-23):
# A user from Gaza reported that Gaza made the change early because of
# the Ramadan.  Next year Ramadan will be even earlier, so I think
# there is a good chance next year's end date will be around two weeks
# earlier--the same goes for Jordan.

# From Steffen Thorsen (2006-08-17):
# I was informed by a user in Bethlehem that in Bethlehem it started the
# same day as Israel, and after checking with other users in the area, I
# was informed that they started DST one day after Israel.  I was not
# able to find any authoritative sources at the time, nor details if
# Gaza changed as well, but presumed Gaza to follow the same rules as
# the West Bank.

# From Steffen Thorsen (2006-09-26):
# according to the Palestine News Network (2006-09-19):
# http://english.pnn.ps/index.php?option=com_content&task=view&id=596&Itemid=5
# > The Council of Ministers announced that this year its winter schedule
# > will begin early, as of midnight Thursday.  It is also time to turn
# > back the clocks for winter.  Friday will begin an hour late this week.
# I guess it is likely that next year's date will be moved as well,
# because of the Ramadan.

# From Jesper Norgaard Welen (2007-09-18):
# According to Steffen Thorsen's web site the Gaza Strip and the rest of the
# Palestinian territories left DST early on 13.th. of September at 2:00.

# From Paul Eggert (2007-09-20):
# My understanding is that Gaza and the West Bank disagree even over when
# the weekend is (Thursday+Friday versus Friday+Saturday), so I'd be a bit
# surprised if they agreed about DST.  But for now, assume they agree.
# For lack of better information, predict that future changes will be
# the 2nd Thursday of September at 02:00.

# From Alexander Krivenyshev (2008-08-28):
# Here is an article, that Mideast running on different clocks at Ramadan.
#
# Gaza Strip (as Egypt) ended DST at midnight Thursday (Aug 28, 2008), while
# the West Bank will end Daylight Saving Time at midnight Sunday (Aug 31, 2008).
#
# 
# http://www.guardian.co.uk/world/feedarticle/7759001
# 
# 
# http://www.abcnews.go.com/International/wireStory?id=5676087
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_gazastrip01.html
# 

# From Alexander Krivenyshev (2009-03-26):
# According to the Palestine News Network (arabic.pnn.ps), Palestinian
# government decided to start Daylight Time on Thursday night March
# 26 and continue until the night of 27 September 2009.
#
# (in Arabic)
# 
# http://arabic.pnn.ps/index.php?option=com_content&task=view&id=50850
# 
#
# or
# (English translation)
# 
# http://www.worldtimezone.com/dst_news/dst_news_westbank01.html
# 

# From Steffen Thorsen (2009-08-31):
# Palestine's Council of Ministers announced that they will revert back to
# winter time on Friday, 2009-09-04.
#
# One news source:
# 
# http://www.safa.ps/ara/?action=showdetail&seid=4158
# 
# (Palestinian press agency, Arabic),
# Google translate: "Decided that the Palestinian government in Ramallah
# headed by Salam Fayyad, the start of work in time for the winter of
# 2009, starting on Friday approved the fourth delay Sept. clock sixty
# minutes per hour as of Friday morning."
#
# We are not sure if Gaza will do the same, last year they had a different
# end date, we will keep this page updated:
# 
# http://www.timeanddate.com/news/time/westbank-gaza-dst-2009.html
# 

# From Alexander Krivenyshev (2009-09-02):
# Seems that Gaza Strip will go back to Winter Time same date as West Bank.
#
# According to Palestinian Ministry Of Interior, West Bank and Gaza Strip plan
# to change time back to Standard time on September 4, 2009.
#
# "Winter time unite the West Bank and Gaza"
# (from Palestinian National Authority):
# 
# http://www.worldtimezone.com/dst_news/dst_news_gazastrip02.html
# 

# From Alexander Krivenyshev (2010-03-19):
# According to Voice of Palestine DST will last for 191 days, from March
# 26, 2010 till "the last Sunday before the tenth day of Tishri
# (October), each year" (October 03, 2010?)
#
# 
# http://palvoice.org/forums/showthread.php?t=245697
# 
# (in Arabic)
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_westbank03.html
# 

# From Steffen Thorsen (2010-03-24):
# ...Ma'an News Agency reports that Hamas cabinet has decided it will
# start one day later, at 12:01am. Not sure if they really mean 12:01am or
# noon though:
#
# 
# http://www.maannews.net/eng/ViewDetails.aspx?ID=271178
# 
# (Ma'an News Agency)
# "At 12:01am Friday, clocks in Israel and the West Bank will change to
# 1:01am, while Gaza clocks will change at 12:01am Saturday morning."

# From Steffen Thorsen (2010-08-11):
# According to several sources, including
# 
# http://www.maannews.net/eng/ViewDetails.aspx?ID=306795
# 
# the clocks were set back one hour at 2010-08-11 00:00:00 local time in
# Gaza and the West Bank.
# Some more background info:
# 
# http://www.timeanddate.com/news/time/westbank-gaza-end-dst-2010.html
# 

# From Steffen Thorsen (2011-08-26):
# Gaza and the West Bank did go back to standard time in the beginning of
# August, and will now enter daylight saving time again on 2011-08-30
# 00:00 (so two periods of DST in 2011). The pause was because of
# Ramadan.
#
# 
# http://www.maannews.net/eng/ViewDetails.aspx?ID=416217
# 
# Additional info:
# 
# http://www.timeanddate.com/news/time/palestine-dst-2011.html
# 

# From Alexander Krivenyshev (2011-08-27):
# According to the article in The Jerusalem Post:
# "...Earlier this month, the Palestinian government in the West Bank decided to
# move to standard time for 30 days, during Ramadan. The Palestinians in the
# Gaza Strip accepted the change and also moved their clocks one hour back.
# The Hamas government said on Saturday that it won't observe summertime after
# the Muslim feast of Id al-Fitr, which begins on Tuesday..."
# ...
# 
# http://www.jpost.com/MiddleEast/Article.aspx?id=235650
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_gazastrip05.html
# 
# The rules for Egypt are stolen from the `africa' file.

# From Steffen Thorsen (2011-09-30):
# West Bank did end Daylight Saving Time this morning/midnight (2011-09-30
# 00:00).
# So West Bank and Gaza now have the same time again.
#
# Many sources, including:
# 
# http://www.maannews.net/eng/ViewDetails.aspx?ID=424808
# 

# From Steffen Thorsen (2012-03-26):
# Palestinian news sources tell that both Gaza and West Bank will start DST
# on Friday (Thursday midnight, 2012-03-29 24:00).
# Some of many sources in Arabic:
# 
# http://www.samanews.com/index.php?act=Show&id=122638
# 
#
# 
# http://safa.ps/details/news/74352/%D8%A8%D8%AF%D8%A1-%D8%A7%D9%84%D8%AA%D9%88%D9%82%D9%8A%D8%AA-%D8%A7%D9%84%D8%B5%D9%8A%D9%81%D9%8A-%D8%A8%D8%A7%D9%84%D8%B6%D9%81%D8%A9-%D9%88%D8%BA%D8%B2%D8%A9-%D9%84%D9%8A%D9%84%D8%A9-%D8%A7%D9%84%D8%AC%D9%85%D8%B9%D8%A9.html
# 
#
# Our brief summary:
# 
# http://www.timeanddate.com/news/time/gaza-west-bank-dst-2012.html
# 

# From Steffen Thorsen (2013-03-26):
# The following news sources tells that Palestine will "start daylight saving
# time from midnight on Friday, March 29, 2013" (translated).
# [These are in Arabic and are for Gaza and for Ramallah, respectively.]
# http://www.samanews.com/index.php?act=Show&id=154120
# http://safa.ps/details/news/99844/%D8%B1%D8%A7%D9%85-%D8%A7%D9%84%D9%84%D9%87-%D8%A8%D8%AF%D8%A1-%D8%A7%D9%84%D8%AA%D9%88%D9%82%D9%8A%D8%AA-%D8%A7%D9%84%D8%B5%D9%8A%D9%81%D9%8A-29-%D8%A7%D9%84%D8%AC%D8%A7%D8%B1%D9%8A.html

# From Paul Eggert (2013-04-15):
# For future dates, guess the last Thursday in March at 24:00 through
# the first Friday on or after September 21 at 01:00.  This is consistent with
# the predictions in today's editions of the following URLs,
# which are for Gaza and Hebron respectively:
# http://www.timeanddate.com/worldclock/timezone.html?n=702
# http://www.timeanddate.com/worldclock/timezone.html?n=2364

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule EgyptAsia	1957	only	-	May	10	0:00	1:00	S
Rule EgyptAsia	1957	1958	-	Oct	 1	0:00	0	-
Rule EgyptAsia	1958	only	-	May	 1	0:00	1:00	S
Rule EgyptAsia	1959	1967	-	May	 1	1:00	1:00	S
Rule EgyptAsia	1959	1965	-	Sep	30	3:00	0	-
Rule EgyptAsia	1966	only	-	Oct	 1	3:00	0	-

Rule Palestine	1999	2005	-	Apr	Fri>=15	0:00	1:00	S
Rule Palestine	1999	2003	-	Oct	Fri>=15	0:00	0	-
Rule Palestine	2004	only	-	Oct	 1	1:00	0	-
Rule Palestine	2005	only	-	Oct	 4	2:00	0	-
Rule Palestine	2006	2007	-	Apr	 1	0:00	1:00	S
Rule Palestine	2006	only	-	Sep	22	0:00	0	-
Rule Palestine	2007	only	-	Sep	Thu>=8	2:00	0	-
Rule Palestine	2008	2009	-	Mar	lastFri	0:00	1:00	S
Rule Palestine	2008	only	-	Sep	 1	0:00	0	-
Rule Palestine	2009	only	-	Sep	Fri>=1	1:00	0	-
Rule Palestine	2010	only	-	Mar	26	0:00	1:00	S
Rule Palestine	2010	only	-	Aug	11	0:00	0	-
Rule Palestine	2011	only	-	Apr	 1	0:01	1:00	S
Rule Palestine	2011	only	-	Aug	 1	0:00	0	-
Rule Palestine	2011	only	-	Aug	30	0:00	1:00	S
Rule Palestine	2011	only	-	Sep	30	0:00	0	-
Rule Palestine	2012	max	-	Mar	lastThu	24:00	1:00	S
Rule Palestine	2012	max	-	Sep	Fri>=21	1:00	0	-

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Gaza	2:17:52	-	LMT	1900 Oct
			2:00	Zion	EET	1948 May 15
			2:00 EgyptAsia	EE%sT	1967 Jun  5
			2:00	Zion	I%sT	1996
			2:00	Jordan	EE%sT	1999
			2:00 Palestine	EE%sT	2008 Aug 29 0:00
			2:00	-	EET	2008 Sep
			2:00 Palestine	EE%sT	2010
			2:00	-	EET	2010 Mar 27 0:01
			2:00 Palestine	EE%sT	2011 Aug  1
			2:00	-	EET	2012
			2:00 Palestine	EE%sT

Zone	Asia/Hebron	2:20:23	-	LMT	1900 Oct
			2:00	Zion	EET	1948 May 15
			2:00 EgyptAsia	EE%sT	1967 Jun  5
			2:00	Zion	I%sT	1996
			2:00	Jordan	EE%sT	1999
			2:00 Palestine	EE%sT

# Paracel Is
# no information

# Philippines
# On 1844-08-16, Narciso Claveria, governor-general of the
# Philippines, issued a proclamation announcing that 1844-12-30 was to
# be immediately followed by 1845-01-01.  Robert H. van Gent has a
# transcript of the decree in .
# The rest of the data are from Shanks & Pottenger.

# From Paul Eggert (2006-04-25):
# Tomorrow's Manila Standard reports that the Philippines Department of
# Trade and Industry is considering adopting DST this June when the
# rainy season begins.  See
# .
# For now, we'll ignore this, since it's not definite and we lack details.
#
# From Jesper Norgaard Welen (2006-04-26):
# ... claims that Philippines had DST last time in 1990:
# http://story.philippinetimes.com/p.x/ct/9/id/145be20cc6b121c0/cid/3e5bbccc730d258c/
# [a story dated 2006-04-25 by Cris Larano of Dow Jones Newswires,
# but no details]

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Phil	1936	only	-	Nov	1	0:00	1:00	S
Rule	Phil	1937	only	-	Feb	1	0:00	0	-
Rule	Phil	1954	only	-	Apr	12	0:00	1:00	S
Rule	Phil	1954	only	-	Jul	1	0:00	0	-
Rule	Phil	1978	only	-	Mar	22	0:00	1:00	S
Rule	Phil	1978	only	-	Sep	21	0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Manila	-15:56:00 -	LMT	1844 Dec 31
			8:04:00 -	LMT	1899 May 11
			8:00	Phil	PH%sT	1942 May
			9:00	-	JST	1944 Nov
			8:00	Phil	PH%sT

# Qatar
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Qatar	3:26:08 -	LMT	1920	# Al Dawhah / Doha
			4:00	-	GST	1972 Jun
			3:00	-	AST

# Saudi Arabia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Riyadh	3:06:52 -	LMT	1950
			3:00	-	AST

# Singapore
# The data here are taken from Mok Ly Yng (2003-10-30)
# .
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Singapore	6:55:25 -	LMT	1901 Jan  1
			6:55:25	-	SMT	1905 Jun  1 # Singapore M.T.
			7:00	-	MALT	1933 Jan  1 # Malaya Time
			7:00	0:20	MALST	1936 Jan  1
			7:20	-	MALT	1941 Sep  1
			7:30	-	MALT	1942 Feb 16
			9:00	-	JST	1945 Sep 12
			7:30	-	MALT	1965 Aug  9 # independence
			7:30	-	SGT	1982 Jan  1 # Singapore Time
			8:00	-	SGT

# Spratly Is
# no information

# Sri Lanka

# From Paul Eggert (2013-02-21):
# Milne says "Madras mean time use from May 1, 1898.  Prior to this Colombo
# mean time, 5h. 4m. 21.9s. F., was used."  But 5:04:21.9 differs considerably
# from Colombo's meridian 5:19:24, so for now ignore Milne and stick with
# Shanks and Pottenger.

# From Paul Eggert (1996-09-03):
# "Sri Lanka advances clock by an hour to avoid blackout"
# (www.virtual-pc.com/lankaweb/news/items/240596-2.html, 1996-05-24,
# no longer available as of 1999-08-17)
# reported ``the country's standard time will be put forward by one hour at
# midnight Friday (1830 GMT) `in the light of the present power crisis'.''
#
# From Dharmasiri Senanayake, Sri Lanka Media Minister (1996-10-24), as quoted
# by Shamindra in
# 
# Daily News - Hot News Section (1996-10-26)
# :
# With effect from 12.30 a.m. on 26th October 1996
# Sri Lanka will be six (06) hours ahead of GMT.

# From Jesper Norgaard Welen (2006-04-14), quoting Sri Lanka News Online
#  (2006-04-13):
# 0030 hrs on April 15, 2006 (midnight of April 14, 2006 +30 minutes)
# at present, become 2400 hours of April 14, 2006 (midnight of April 14, 2006).

# From Peter Apps and Ranga Sirila of Reuters (2006-04-12) in:
# 
# [The Tamil Tigers] never accepted the original 1996 time change and simply
# kept their clocks set five and a half hours ahead of Greenwich Mean
# Time (GMT), in line with neighbor India.
# From Paul Eggert (2006-04-18):
# People who live in regions under Tamil control can use [TZ='Asia/Kolkata'],
# as that zone has agreed with the Tamil areas since our cutoff date of 1970.

# From K Sethu (2006-04-25):
# I think the abbreviation LKT originated from the world of computers at
# the time of or subsequent to the time zone changes by SL Government
# twice in 1996 and probably SL Government or its standardization
# agencies never declared an abbreviation as a national standard.
#
# I recollect before the recent change the government annoucemments
# mentioning it as simply changing Sri Lanka Standard Time or Sri Lanka
# Time and no mention was made about the abbreviation.
#
# If we look at Sri Lanka Department of Government's "Official News
# Website of Sri Lanka" ... http://www.news.lk/ we can see that they
# use SLT as abbreviation in time stamp at the beginning of each news
# item....
#
# Within Sri Lanka I think LKT is well known among computer users and
# adminsitrators.  In my opinion SLT may not be a good choice because the
# nation's largest telcom / internet operator Sri Lanka Telcom is well
# known by that abbreviation - simply as SLT (there IP domains are
# slt.lk and sltnet.lk).
#
# But if indeed our government has adopted SLT as standard abbreviation
# (that we have not known so far) then  it is better that it be used for
# all computers.

# From Paul Eggert (2006-04-25):
# One possibility is that we wait for a bit for the dust to settle down
# and then see what people actually say in practice.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Colombo	5:19:24 -	LMT	1880
			5:19:32	-	MMT	1906	# Moratuwa Mean Time
			5:30	-	IST	1942 Jan  5
			5:30	0:30	IHST	1942 Sep
			5:30	1:00	IST	1945 Oct 16 2:00
			5:30	-	IST	1996 May 25 0:00
			6:30	-	LKT	1996 Oct 26 0:30
			6:00	-	LKT	2006 Apr 15 0:30
			5:30	-	IST

# Syria
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Syria	1920	1923	-	Apr	Sun>=15	2:00	1:00	S
Rule	Syria	1920	1923	-	Oct	Sun>=1	2:00	0	-
Rule	Syria	1962	only	-	Apr	29	2:00	1:00	S
Rule	Syria	1962	only	-	Oct	1	2:00	0	-
Rule	Syria	1963	1965	-	May	1	2:00	1:00	S
Rule	Syria	1963	only	-	Sep	30	2:00	0	-
Rule	Syria	1964	only	-	Oct	1	2:00	0	-
Rule	Syria	1965	only	-	Sep	30	2:00	0	-
Rule	Syria	1966	only	-	Apr	24	2:00	1:00	S
Rule	Syria	1966	1976	-	Oct	1	2:00	0	-
Rule	Syria	1967	1978	-	May	1	2:00	1:00	S
Rule	Syria	1977	1978	-	Sep	1	2:00	0	-
Rule	Syria	1983	1984	-	Apr	9	2:00	1:00	S
Rule	Syria	1983	1984	-	Oct	1	2:00	0	-
Rule	Syria	1986	only	-	Feb	16	2:00	1:00	S
Rule	Syria	1986	only	-	Oct	9	2:00	0	-
Rule	Syria	1987	only	-	Mar	1	2:00	1:00	S
Rule	Syria	1987	1988	-	Oct	31	2:00	0	-
Rule	Syria	1988	only	-	Mar	15	2:00	1:00	S
Rule	Syria	1989	only	-	Mar	31	2:00	1:00	S
Rule	Syria	1989	only	-	Oct	1	2:00	0	-
Rule	Syria	1990	only	-	Apr	1	2:00	1:00	S
Rule	Syria	1990	only	-	Sep	30	2:00	0	-
Rule	Syria	1991	only	-	Apr	 1	0:00	1:00	S
Rule	Syria	1991	1992	-	Oct	 1	0:00	0	-
Rule	Syria	1992	only	-	Apr	 8	0:00	1:00	S
Rule	Syria	1993	only	-	Mar	26	0:00	1:00	S
Rule	Syria	1993	only	-	Sep	25	0:00	0	-
# IATA SSIM (1998-02) says 1998-04-02;
# (1998-09) says 1999-03-29 and 1999-09-29; (1999-02) says 1999-04-02,
# 2000-04-02, and 2001-04-02; (1999-09) says 2000-03-31 and 2001-03-31;
# (2006) says 2006-03-31 and 2006-09-22;
# for now ignore all these claims and go with Shanks & Pottenger,
# except for the 2006-09-22 claim (which seems right for Ramadan).
Rule	Syria	1994	1996	-	Apr	 1	0:00	1:00	S
Rule	Syria	1994	2005	-	Oct	 1	0:00	0	-
Rule	Syria	1997	1998	-	Mar	lastMon	0:00	1:00	S
Rule	Syria	1999	2006	-	Apr	 1	0:00	1:00	S
# From Stephen Colebourne (2006-09-18):
# According to IATA data, Syria will change DST on 21st September [21:00 UTC]
# this year [only]....  This is probably related to Ramadan, like Egypt.
Rule	Syria	2006	only	-	Sep	22	0:00	0	-
# From Paul Eggert (2007-03-29):
# Today the AP reported "Syria will switch to summertime at midnight Thursday."
# http://www.iht.com/articles/ap/2007/03/29/africa/ME-GEN-Syria-Time-Change.php
Rule	Syria	2007	only	-	Mar	lastFri	0:00	1:00	S
# From Jesper Norgard (2007-10-27):
# The sister center ICARDA of my work CIMMYT is confirming that Syria DST will
# not take place 1st November at 0:00 o'clock but 1st November at 24:00 or
# rather Midnight between Thursday and Friday. This does make more sense than
# having it between Wednesday and Thursday (two workdays in Syria) since the
# weekend in Syria is not Saturday and Sunday, but Friday and Saturday. So now
# it is implemented at midnight of the last workday before weekend...
#
# From Steffen Thorsen (2007-10-27):
# Jesper Norgaard Welen wrote:
#
# > "Winter local time in Syria will be observed at midnight of Thursday 1
# > November 2007, and the clock will be put back 1 hour."
#
# I found confirmation on this in this gov.sy-article (Arabic):
# http://wehda.alwehda.gov.sy/_print_veiw.asp?FileName=12521710520070926111247
#
# which using Google's translate tools says:
# Council of Ministers also approved the commencement of work on
# identifying the winter time as of Friday, 2/11/2007 where the 60th
# minute delay at midnight Thursday 1/11/2007.
Rule	Syria	2007	only	-	Nov	 Fri>=1	0:00	0	-

# From Stephen Colebourne (2008-03-17):
# For everyone's info, I saw an IATA time zone change for [Syria] for
# this month (March 2008) in the last day or so...This is the data IATA
# are now using:
# Country     Time Standard   --- DST Start ---   --- DST End ---  DST
# Name        Zone Variation   Time    Date        Time    Date
# Variation
# Syrian Arab
# Republic    SY    +0200      2200  03APR08       2100  30SEP08   +0300
#                              2200  02APR09       2100  30SEP09   +0300
#                              2200  01APR10       2100  30SEP10   +0300

# From Arthur David Olson (2008-03-17):
# Here's a link to English-language coverage by the Syrian Arab News
# Agency (SANA)...
# 
# http://www.sana.sy/eng/21/2008/03/11/165173.htm
# ...which reads (in part) "The Cabinet approved the suggestion of the
# Ministry of Electricity to begin daylight savings time on Friday April
# 4th, advancing clocks one hour ahead on midnight of Thursday April 3rd."
# Since Syria is two hours east of UTC, the 2200 and 2100 transition times
# shown above match up with midnight in Syria.

# From Arthur David Olson (2008-03-18):
# My buest guess at a Syrian rule is "the Friday nearest April 1";
# coding that involves either using a "Mar Fri>=29" construct that old time zone
# compilers can't handle  or having multiple Rules (a la Israel).
# For now, use "Apr Fri>=1", and go with IATA on a uniform Sep 30 end.

# From Steffen Thorsen (2008-10-07):
# Syria has now officially decided to end DST on 2008-11-01 this year,
# according to the following article in the Syrian Arab News Agency (SANA).
#
# The article is in Arabic, and seems to tell that they will go back to
# winter time on 2008-11-01 at 00:00 local daylight time (delaying/setting
# clocks back 60 minutes).
#
# 
# http://sana.sy/ara/2/2008/10/07/195459.htm
# 

# From Steffen Thorsen (2009-03-19):
# Syria will start DST on 2009-03-27 00:00 this year according to many sources,
# two examples:
#
# 
# http://www.sana.sy/eng/21/2009/03/17/217563.htm
# 
# (English, Syrian Arab News # Agency)
# 
# http://thawra.alwehda.gov.sy/_View_news2.asp?FileName=94459258720090318012209
# 
# (Arabic, gov-site)
#
# We have not found any sources saying anything about when DST ends this year.
#
# Our summary
# 
# http://www.timeanddate.com/news/time/syria-dst-starts-march-27-2009.html
# 

# From Steffen Thorsen (2009-10-27):
# The Syrian Arab News Network on 2009-09-29 reported that Syria will
# revert back to winter (standard) time on midnight between Thursday
# 2009-10-29 and Friday 2009-10-30:
# 
# http://www.sana.sy/ara/2/2009/09/29/247012.htm (Arabic)
# 

# From Arthur David Olson (2009-10-28):
# We'll see if future DST switching times turn out to be end of the last
# Thursday of the month or the start of the last Friday of the month or
# something else. For now, use the start of the last Friday.

# From Steffen Thorsen (2010-03-17):
# The "Syrian News Station" reported on 2010-03-16 that the Council of
# Ministers has decided that Syria will start DST on midnight Thursday
# 2010-04-01: (midnight between Thursday and Friday):
# 
# http://sns.sy/sns/?path=news/read/11421 (Arabic)
# 

# From Steffen Thorsen (2012-03-26):
# Today, Syria's government announced that they will start DST early on Friday
# (00:00). This is a bit earlier than the past two years.
#
# From Syrian Arab News Agency, in Arabic:
# 
# http://www.sana.sy/ara/2/2012/03/26/408215.htm
# 
#
# Our brief summary:
# 
# http://www.timeanddate.com/news/time/syria-dst-2012.html
# 

# From Arthur David Olson (2012-03-27):
# Assume last Friday in March going forward XXX.

Rule	Syria	2008	only	-	Apr	Fri>=1	0:00	1:00	S
Rule	Syria	2008	only	-	Nov	1	0:00	0	-
Rule	Syria	2009	only	-	Mar	lastFri	0:00	1:00	S
Rule	Syria	2010	2011	-	Apr	Fri>=1	0:00	1:00	S
Rule	Syria	2012	max	-	Mar	lastFri	0:00	1:00	S
Rule	Syria	2009	max	-	Oct	lastFri	0:00	0	-

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Damascus	2:25:12 -	LMT	1920	# Dimashq
			2:00	Syria	EE%sT

# Tajikistan
# From Shanks & Pottenger.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Dushanbe	4:35:12 -	LMT	1924 May  2
			5:00	-	DUST	1930 Jun 21 # Dushanbe Time
			6:00 RussiaAsia DUS%sT	1991 Mar 31 2:00s
			5:00	1:00	DUSST	1991 Sep  9 2:00s
			5:00	-	TJT		    # Tajikistan Time

# Thailand
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Bangkok	6:42:04	-	LMT	1880
			6:42:04	-	BMT	1920 Apr # Bangkok Mean Time
			7:00	-	ICT

# Turkmenistan
# From Shanks & Pottenger.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Ashgabat	3:53:32 -	LMT	1924 May  2 # or Ashkhabad
			4:00	-	ASHT	1930 Jun 21 # Ashkhabad Time
			5:00 RussiaAsia	ASH%sT	1991 Mar 31 2:00
			4:00 RussiaAsia	ASH%sT	1991 Oct 27 # independence
			4:00 RussiaAsia	TM%sT	1992 Jan 19 2:00
			5:00	-	TMT

# United Arab Emirates
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Dubai	3:41:12 -	LMT	1920
			4:00	-	GST

# Uzbekistan
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Samarkand	4:27:12 -	LMT	1924 May  2
			4:00	-	SAMT	1930 Jun 21 # Samarkand Time
			5:00	-	SAMT	1981 Apr  1
			5:00	1:00	SAMST	1981 Oct  1
			6:00	-	TAST	1982 Apr  1 # Tashkent Time
			5:00 RussiaAsia	SAM%sT	1991 Sep  1 # independence
			5:00 RussiaAsia	UZ%sT	1992
			5:00	-	UZT
Zone	Asia/Tashkent	4:37:12 -	LMT	1924 May  2
			5:00	-	TAST	1930 Jun 21 # Tashkent Time
			6:00 RussiaAsia	TAS%sT	1991 Mar 31 2:00
			5:00 RussiaAsia	TAS%sT	1991 Sep  1 # independence
			5:00 RussiaAsia	UZ%sT	1992
			5:00	-	UZT

# Vietnam

# From Paul Eggert (2013-02-21):
# Milne gives 7:16:56 for the meridian of Saigon in 1899, as being
# used in Lower Laos, Cambodia, and Annam.  But this is quite a ways
# from Saigon's location.  For now, ignore this and stick with Shanks
# and Pottenger.

# From Arthur David Olson (2008-03-18):
# The English-language name of Vietnam's most populous city is "Ho Chi Min City";
# we use Ho_Chi_Minh below to avoid a name of more than 14 characters.

# From Shanks & Pottenger:
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Ho_Chi_Minh	7:06:40 -	LMT	1906 Jun  9
			7:06:20	-	SMT	1911 Mar 11 0:01 # Saigon MT?
			7:00	-	ICT	1912 May
			8:00	-	ICT	1931 May
			7:00	-	ICT

# Yemen

# Milne says 2:59:54 was the meridian of the saluting battery at Aden,
# and that Yemen was at 1:55:56, the meridian of the Hagia Sophia.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Asia/Aden	2:59:54	-	LMT	1950
			3:00	-	AST
joda-time-2.3/src/main/java/org/joda/time/tz/src/australasia0000644000175000017500000021543012200501234023327 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# This file also includes Pacific islands.

# Notes are at the end of this file

###############################################################################

# Australia

# Please see the notes below for the controversy about "EST" versus "AEST" etc.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Aus	1917	only	-	Jan	 1	0:01	1:00	-
Rule	Aus	1917	only	-	Mar	25	2:00	0	-
Rule	Aus	1942	only	-	Jan	 1	2:00	1:00	-
Rule	Aus	1942	only	-	Mar	29	2:00	0	-
Rule	Aus	1942	only	-	Sep	27	2:00	1:00	-
Rule	Aus	1943	1944	-	Mar	lastSun	2:00	0	-
Rule	Aus	1943	only	-	Oct	 3	2:00	1:00	-
# Go with Whitman and the Australian National Standards Commission, which
# says W Australia didn't use DST in 1943/1944.  Ignore Whitman's claim that
# 1944/1945 was just like 1943/1944.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# Northern Territory
Zone Australia/Darwin	 8:43:20 -	LMT	1895 Feb
			 9:00	-	CST	1899 May
			 9:30	Aus	CST
# Western Australia
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	AW	1974	only	-	Oct	lastSun	2:00s	1:00	-
Rule	AW	1975	only	-	Mar	Sun>=1	2:00s	0	-
Rule	AW	1983	only	-	Oct	lastSun	2:00s	1:00	-
Rule	AW	1984	only	-	Mar	Sun>=1	2:00s	0	-
Rule	AW	1991	only	-	Nov	17	2:00s	1:00	-
Rule	AW	1992	only	-	Mar	Sun>=1	2:00s	0	-
Rule	AW	2006	only	-	Dec	 3	2:00s	1:00	-
Rule	AW	2007	2009	-	Mar	lastSun	2:00s	0	-
Rule	AW	2007	2008	-	Oct	lastSun	2:00s	1:00	-
Zone Australia/Perth	 7:43:24 -	LMT	1895 Dec
			 8:00	Aus	WST	1943 Jul
			 8:00	AW	WST
Zone Australia/Eucla	 8:35:28 -	LMT	1895 Dec
			 8:45	Aus	CWST	1943 Jul
			 8:45	AW	CWST

# Queensland
#
# From Alex Livingston (1996-11-01):
# I have heard or read more than once that some resort islands off the coast
# of Queensland chose to keep observing daylight-saving time even after
# Queensland ceased to.
#
# From Paul Eggert (1996-11-22):
# IATA SSIM (1993-02/1994-09) say that the Holiday Islands (Hayman, Lindeman,
# Hamilton) observed DST for two years after the rest of Queensland stopped.
# Hamilton is the largest, but there is also a Hamilton in Victoria,
# so use Lindeman.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	AQ	1971	only	-	Oct	lastSun	2:00s	1:00	-
Rule	AQ	1972	only	-	Feb	lastSun	2:00s	0	-
Rule	AQ	1989	1991	-	Oct	lastSun	2:00s	1:00	-
Rule	AQ	1990	1992	-	Mar	Sun>=1	2:00s	0	-
Rule	Holiday	1992	1993	-	Oct	lastSun	2:00s	1:00	-
Rule	Holiday	1993	1994	-	Mar	Sun>=1	2:00s	0	-
Zone Australia/Brisbane	10:12:08 -	LMT	1895
			10:00	Aus	EST	1971
			10:00	AQ	EST
Zone Australia/Lindeman  9:55:56 -	LMT	1895
			10:00	Aus	EST	1971
			10:00	AQ	EST	1992 Jul
			10:00	Holiday	EST

# South Australia
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	AS	1971	1985	-	Oct	lastSun	2:00s	1:00	-
Rule	AS	1986	only	-	Oct	19	2:00s	1:00	-
Rule	AS	1987	2007	-	Oct	lastSun	2:00s	1:00	-
Rule	AS	1972	only	-	Feb	27	2:00s	0	-
Rule	AS	1973	1985	-	Mar	Sun>=1	2:00s	0	-
Rule	AS	1986	1990	-	Mar	Sun>=15	2:00s	0	-
Rule	AS	1991	only	-	Mar	3	2:00s	0	-
Rule	AS	1992	only	-	Mar	22	2:00s	0	-
Rule	AS	1993	only	-	Mar	7	2:00s	0	-
Rule	AS	1994	only	-	Mar	20	2:00s	0	-
Rule	AS	1995	2005	-	Mar	lastSun	2:00s	0	-
Rule	AS	2006	only	-	Apr	2	2:00s	0	-
Rule	AS	2007	only	-	Mar	lastSun	2:00s	0	-
Rule	AS	2008	max	-	Apr	Sun>=1	2:00s	0	-
Rule	AS	2008	max	-	Oct	Sun>=1	2:00s	1:00	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Australia/Adelaide	9:14:20 -	LMT	1895 Feb
			9:00	-	CST	1899 May
			9:30	Aus	CST	1971
			9:30	AS	CST

# Tasmania
#
# From Paul Eggert (2005-08-16):
# 
# says King Island didn't observe DST from WWII until late 1971.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	AT	1967	only	-	Oct	Sun>=1	2:00s	1:00	-
Rule	AT	1968	only	-	Mar	lastSun	2:00s	0	-
Rule	AT	1968	1985	-	Oct	lastSun	2:00s	1:00	-
Rule	AT	1969	1971	-	Mar	Sun>=8	2:00s	0	-
Rule	AT	1972	only	-	Feb	lastSun	2:00s	0	-
Rule	AT	1973	1981	-	Mar	Sun>=1	2:00s	0	-
Rule	AT	1982	1983	-	Mar	lastSun	2:00s	0	-
Rule	AT	1984	1986	-	Mar	Sun>=1	2:00s	0	-
Rule	AT	1986	only	-	Oct	Sun>=15	2:00s	1:00	-
Rule	AT	1987	1990	-	Mar	Sun>=15	2:00s	0	-
Rule	AT	1987	only	-	Oct	Sun>=22	2:00s	1:00	-
Rule	AT	1988	1990	-	Oct	lastSun	2:00s	1:00	-
Rule	AT	1991	1999	-	Oct	Sun>=1	2:00s	1:00	-
Rule	AT	1991	2005	-	Mar	lastSun	2:00s	0	-
Rule	AT	2000	only	-	Aug	lastSun	2:00s	1:00	-
Rule	AT	2001	max	-	Oct	Sun>=1	2:00s	1:00	-
Rule	AT	2006	only	-	Apr	Sun>=1	2:00s	0	-
Rule	AT	2007	only	-	Mar	lastSun	2:00s	0	-
Rule	AT	2008	max	-	Apr	Sun>=1	2:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Australia/Hobart	9:49:16	-	LMT	1895 Sep
			10:00	-	EST	1916 Oct 1 2:00
			10:00	1:00	EST	1917 Feb
			10:00	Aus	EST	1967
			10:00	AT	EST
Zone Australia/Currie	9:35:28	-	LMT	1895 Sep
			10:00	-	EST	1916 Oct 1 2:00
			10:00	1:00	EST	1917 Feb
			10:00	Aus	EST	1971 Jul
			10:00	AT	EST

# Victoria
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	AV	1971	1985	-	Oct	lastSun	2:00s	1:00	-
Rule	AV	1972	only	-	Feb	lastSun	2:00s	0	-
Rule	AV	1973	1985	-	Mar	Sun>=1	2:00s	0	-
Rule	AV	1986	1990	-	Mar	Sun>=15	2:00s	0	-
Rule	AV	1986	1987	-	Oct	Sun>=15	2:00s	1:00	-
Rule	AV	1988	1999	-	Oct	lastSun	2:00s	1:00	-
Rule	AV	1991	1994	-	Mar	Sun>=1	2:00s	0	-
Rule	AV	1995	2005	-	Mar	lastSun	2:00s	0	-
Rule	AV	2000	only	-	Aug	lastSun	2:00s	1:00	-
Rule	AV	2001	2007	-	Oct	lastSun	2:00s	1:00	-
Rule	AV	2006	only	-	Apr	Sun>=1	2:00s	0	-
Rule	AV	2007	only	-	Mar	lastSun	2:00s	0	-
Rule	AV	2008	max	-	Apr	Sun>=1	2:00s	0	-
Rule	AV	2008	max	-	Oct	Sun>=1	2:00s	1:00	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Australia/Melbourne 9:39:52 -	LMT	1895 Feb
			10:00	Aus	EST	1971
			10:00	AV	EST

# New South Wales
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	AN	1971	1985	-	Oct	lastSun	2:00s	1:00	-
Rule	AN	1972	only	-	Feb	27	2:00s	0	-
Rule	AN	1973	1981	-	Mar	Sun>=1	2:00s	0	-
Rule	AN	1982	only	-	Apr	Sun>=1	2:00s	0	-
Rule	AN	1983	1985	-	Mar	Sun>=1	2:00s	0	-
Rule	AN	1986	1989	-	Mar	Sun>=15	2:00s	0	-
Rule	AN	1986	only	-	Oct	19	2:00s	1:00	-
Rule	AN	1987	1999	-	Oct	lastSun	2:00s	1:00	-
Rule	AN	1990	1995	-	Mar	Sun>=1	2:00s	0	-
Rule	AN	1996	2005	-	Mar	lastSun	2:00s	0	-
Rule	AN	2000	only	-	Aug	lastSun	2:00s	1:00	-
Rule	AN	2001	2007	-	Oct	lastSun	2:00s	1:00	-
Rule	AN	2006	only	-	Apr	Sun>=1	2:00s	0	-
Rule	AN	2007	only	-	Mar	lastSun	2:00s	0	-
Rule	AN	2008	max	-	Apr	Sun>=1	2:00s	0	-
Rule	AN	2008	max	-	Oct	Sun>=1	2:00s	1:00	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Australia/Sydney	10:04:52 -	LMT	1895 Feb
			10:00	Aus	EST	1971
			10:00	AN	EST
Zone Australia/Broken_Hill 9:25:48 -	LMT	1895 Feb
			10:00	-	EST	1896 Aug 23
			9:00	-	CST	1899 May
			9:30	Aus	CST	1971
			9:30	AN	CST	2000
			9:30	AS	CST

# Lord Howe Island
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	LH	1981	1984	-	Oct	lastSun	2:00	1:00	-
Rule	LH	1982	1985	-	Mar	Sun>=1	2:00	0	-
Rule	LH	1985	only	-	Oct	lastSun	2:00	0:30	-
Rule	LH	1986	1989	-	Mar	Sun>=15	2:00	0	-
Rule	LH	1986	only	-	Oct	19	2:00	0:30	-
Rule	LH	1987	1999	-	Oct	lastSun	2:00	0:30	-
Rule	LH	1990	1995	-	Mar	Sun>=1	2:00	0	-
Rule	LH	1996	2005	-	Mar	lastSun	2:00	0	-
Rule	LH	2000	only	-	Aug	lastSun	2:00	0:30	-
Rule	LH	2001	2007	-	Oct	lastSun	2:00	0:30	-
Rule	LH	2006	only	-	Apr	Sun>=1	2:00	0	-
Rule	LH	2007	only	-	Mar	lastSun	2:00	0	-
Rule	LH	2008	max	-	Apr	Sun>=1	2:00	0	-
Rule	LH	2008	max	-	Oct	Sun>=1	2:00	0:30	-
Zone Australia/Lord_Howe 10:36:20 -	LMT	1895 Feb
			10:00	-	EST	1981 Mar
			10:30	LH	LHST

# Australian miscellany
#
# Ashmore Is, Cartier
# no indigenous inhabitants; only seasonal caretakers
# no times are set
#
# Coral Sea Is
# no indigenous inhabitants; only meteorologists
# no times are set
#
# Macquarie
# Permanent occupation (scientific station) 1911-1915 and since 25 March 1948;
# sealing and penguin oil station operated Nov 1899 to Apr 1919.  See the
# Tasmania Parks & Wildlife Service history of sealing at Macquarie Island
# 
# .
# Guess that it was like Australia/Hobart while inhabited before 2010.
#
# From Steffen Thorsen (2010-03-10):
# We got these changes from the Australian Antarctic Division:
# - Macquarie Island will stay on UTC+11 for winter and therefore not
# switch back from daylight savings time when other parts of Australia do
# on 4 April.
#
# From Arthur David Olson (2013-05-23):
# The 1919 transition is overspecified below so pre-2013 zics
# will produce a binary file with an EST-type as the first 32-bit type;
# this is required for correct handling of times before 1916 by
# pre-2013 versions of localtime.
Zone Antarctica/Macquarie 0	-	zzz	1899 Nov
			10:00	-	EST	1916 Oct 1 2:00
			10:00	1:00	EST	1917 Feb
			10:00	Aus	EST	1919 Apr 1 0:00s
			0	-	zzz	1948 Mar 25
			10:00	Aus	EST	1967
			10:00	AT	EST	2010 Apr 4 3:00
			11:00	-	MIST	# Macquarie I Standard Time

# Christmas
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Indian/Christmas	7:02:52 -	LMT	1895 Feb
			7:00	-	CXT	# Christmas Island Time

# Cook Is
# From Shanks & Pottenger:
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Cook	1978	only	-	Nov	12	0:00	0:30	HS
Rule	Cook	1979	1991	-	Mar	Sun>=1	0:00	0	-
Rule	Cook	1979	1990	-	Oct	lastSun	0:00	0:30	HS
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Rarotonga	-10:39:04 -	LMT	1901		# Avarua
			-10:30	-	CKT	1978 Nov 12	# Cook Is Time
			-10:00	Cook	CK%sT

# Cocos
# These islands were ruled by the Ross family from about 1830 to 1978.
# We don't know when standard time was introduced; for now, we guess 1900.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Indian/Cocos	6:27:40	-	LMT	1900
			6:30	-	CCT	# Cocos Islands Time

# Fiji

# Milne gives 11:55:44 for Suva.

# From Alexander Krivenyshev (2009-11-10):
# According to Fiji Broadcasting Corporation,  Fiji plans to re-introduce DST
# from November 29th 2009  to April 25th 2010.
#
# "Daylight savings to commence this month"
# 
# http://www.radiofiji.com.fj/fullstory.php?id=23719
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_fiji01.html
# 

# From Steffen Thorsen (2009-11-10):
# The Fiji Government has posted some more details about the approved
# amendments:
# 
# http://www.fiji.gov.fj/publish/page_16198.shtml
# 

# From Steffen Thorsen (2010-03-03):
# The Cabinet in Fiji has decided to end DST about a month early, on
# 2010-03-28 at 03:00.
# The plan is to observe DST again, from 2010-10-24 to sometime in March
# 2011 (last Sunday a good guess?).
#
# Official source:
# 
# http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=1096:3310-cabinet-approves-change-in-daylight-savings-dates&catid=49:cabinet-releases&Itemid=166
# 
#
# A bit more background info here:
# 
# http://www.timeanddate.com/news/time/fiji-dst-ends-march-2010.html
# 

# From Alexander Krivenyshev (2010-10-24):
# According to Radio Fiji and Fiji Times online, Fiji will end DST 3
# weeks earlier than expected - on March 6, 2011, not March 27, 2011...
# Here is confirmation from Government of the Republic of the Fiji Islands,
# Ministry of Information (fiji.gov.fj) web site:
# 
# http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=2608:daylight-savings&catid=71:press-releases&Itemid=155
# 
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_fiji04.html
# 

# From Steffen Thorsen (2011-10-03):
# Now the dates have been confirmed, and at least our start date
# assumption was correct (end date was one week wrong).
#
# 
# www.fiji.gov.fj/index.php?option=com_content&view=article&id=4966:daylight-saving-starts-in-fiji&catid=71:press-releases&Itemid=155
# 
# which says
# Members of the public are reminded to change their time to one hour in
# advance at 2am to 3am on October 23, 2011 and one hour back at 3am to
# 2am on February 26 next year.

# From Ken Rylander (2011-10-24)
# Another change to the Fiji DST end date. In the TZ database the end date for
# Fiji DST 2012, is currently Feb 26. This has been changed to Jan 22.
#
# 
# http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=5017:amendments-to-daylight-savings&catid=71:press-releases&Itemid=155
# 
# states:
#
# The end of daylight saving scheduled initially for the 26th of February 2012
# has been brought forward to the 22nd of January 2012.
# The commencement of daylight saving will remain unchanged and start
# on the  23rd of October, 2011.

# From the Fiji Government Online Portal (2012-08-21) via Steffen Thorsen:
# The Minister for Labour, Industrial Relations and Employment Mr Jone Usamate
# today confirmed that Fiji will start daylight savings at 2 am on Sunday 21st
# October 2012 and end at 3 am on Sunday 20th January 2013.
# http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=6702&catid=71&Itemid=155
#
# From Paul Eggert (2012-08-31):
# For now, guess a pattern of the penultimate Sundays in October and January.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Fiji	1998	1999	-	Nov	Sun>=1	2:00	1:00	S
Rule	Fiji	1999	2000	-	Feb	lastSun	3:00	0	-
Rule	Fiji	2009	only	-	Nov	29	2:00	1:00	S
Rule	Fiji	2010	only	-	Mar	lastSun	3:00	0	-
Rule	Fiji	2010	max	-	Oct	Sun>=18	2:00	1:00	S
Rule	Fiji	2011	only	-	Mar	Sun>=1	3:00	0	-
Rule	Fiji	2012	max	-	Jan	Sun>=18	3:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Fiji	11:55:44 -	LMT	1915 Oct 26	# Suva
			12:00	Fiji	FJ%sT	# Fiji Time

# French Polynesia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Gambier	 -8:59:48 -	LMT	1912 Oct	# Rikitea
			 -9:00	-	GAMT	# Gambier Time
Zone	Pacific/Marquesas -9:18:00 -	LMT	1912 Oct
			 -9:30	-	MART	# Marquesas Time
Zone	Pacific/Tahiti	 -9:58:16 -	LMT	1912 Oct	# Papeete
			-10:00	-	TAHT	# Tahiti Time
# Clipperton (near North America) is administered from French Polynesia;
# it is uninhabited.

# Guam
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Guam	-14:21:00 -	LMT	1844 Dec 31
			 9:39:00 -	LMT	1901		# Agana
			10:00	-	GST	2000 Dec 23	# Guam
			10:00	-	ChST	# Chamorro Standard Time

# Kiribati
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Tarawa	 11:32:04 -	LMT	1901		# Bairiki
			 12:00	-	GILT		 # Gilbert Is Time
Zone Pacific/Enderbury	-11:24:20 -	LMT	1901
			-12:00	-	PHOT	1979 Oct # Phoenix Is Time
			-11:00	-	PHOT	1995
			 13:00	-	PHOT
Zone Pacific/Kiritimati	-10:29:20 -	LMT	1901
			-10:40	-	LINT	1979 Oct # Line Is Time
			-10:00	-	LINT	1995
			 14:00	-	LINT

# N Mariana Is
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Saipan	-14:17:00 -	LMT	1844 Dec 31
			 9:43:00 -	LMT	1901
			 9:00	-	MPT	1969 Oct # N Mariana Is Time
			10:00	-	MPT	2000 Dec 23
			10:00	-	ChST	# Chamorro Standard Time

# Marshall Is
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Majuro	11:24:48 -	LMT	1901
			11:00	-	MHT	1969 Oct # Marshall Islands Time
			12:00	-	MHT
Zone Pacific/Kwajalein	11:09:20 -	LMT	1901
			11:00	-	MHT	1969 Oct
			-12:00	-	KWAT	1993 Aug 20	# Kwajalein Time
			12:00	-	MHT

# Micronesia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Chuuk	10:07:08 -	LMT	1901
			10:00	-	CHUT			# Chuuk Time
Zone Pacific/Pohnpei	10:32:52 -	LMT	1901		# Kolonia
			11:00	-	PONT			# Pohnpei Time
Zone Pacific/Kosrae	10:51:56 -	LMT	1901
			11:00	-	KOST	1969 Oct	# Kosrae Time
			12:00	-	KOST	1999
			11:00	-	KOST

# Nauru
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Nauru	11:07:40 -	LMT	1921 Jan 15	# Uaobe
			11:30	-	NRT	1942 Mar 15	# Nauru Time
			9:00	-	JST	1944 Aug 15
			11:30	-	NRT	1979 May
			12:00	-	NRT

# New Caledonia
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	NC	1977	1978	-	Dec	Sun>=1	0:00	1:00	S
Rule	NC	1978	1979	-	Feb	27	0:00	0	-
Rule	NC	1996	only	-	Dec	 1	2:00s	1:00	S
# Shanks & Pottenger say the following was at 2:00; go with IATA.
Rule	NC	1997	only	-	Mar	 2	2:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Noumea	11:05:48 -	LMT	1912 Jan 13
			11:00	NC	NC%sT


###############################################################################

# New Zealand

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	NZ	1927	only	-	Nov	 6	2:00	1:00	S
Rule	NZ	1928	only	-	Mar	 4	2:00	0	M
Rule	NZ	1928	1933	-	Oct	Sun>=8	2:00	0:30	S
Rule	NZ	1929	1933	-	Mar	Sun>=15	2:00	0	M
Rule	NZ	1934	1940	-	Apr	lastSun	2:00	0	M
Rule	NZ	1934	1940	-	Sep	lastSun	2:00	0:30	S
Rule	NZ	1946	only	-	Jan	 1	0:00	0	S
# Since 1957 Chatham has been 45 minutes ahead of NZ, but there's no
# convenient notation for this so we must duplicate the Rule lines.
Rule	NZ	1974	only	-	Nov	Sun>=1	2:00s	1:00	D
Rule	Chatham	1974	only	-	Nov	Sun>=1	2:45s	1:00	D
Rule	NZ	1975	only	-	Feb	lastSun	2:00s	0	S
Rule	Chatham	1975	only	-	Feb	lastSun	2:45s	0	S
Rule	NZ	1975	1988	-	Oct	lastSun	2:00s	1:00	D
Rule	Chatham	1975	1988	-	Oct	lastSun	2:45s	1:00	D
Rule	NZ	1976	1989	-	Mar	Sun>=1	2:00s	0	S
Rule	Chatham	1976	1989	-	Mar	Sun>=1	2:45s	0	S
Rule	NZ	1989	only	-	Oct	Sun>=8	2:00s	1:00	D
Rule	Chatham	1989	only	-	Oct	Sun>=8	2:45s	1:00	D
Rule	NZ	1990	2006	-	Oct	Sun>=1	2:00s	1:00	D
Rule	Chatham	1990	2006	-	Oct	Sun>=1	2:45s	1:00	D
Rule	NZ	1990	2007	-	Mar	Sun>=15	2:00s	0	S
Rule	Chatham	1990	2007	-	Mar	Sun>=15	2:45s	0	S
Rule	NZ	2007	max	-	Sep	lastSun	2:00s	1:00	D
Rule	Chatham	2007	max	-	Sep	lastSun	2:45s	1:00	D
Rule	NZ	2008	max	-	Apr	Sun>=1	2:00s	0	S
Rule	Chatham	2008	max	-	Apr	Sun>=1	2:45s	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Auckland	11:39:04 -	LMT	1868 Nov  2
			11:30	NZ	NZ%sT	1946 Jan  1
			12:00	NZ	NZ%sT
Zone Pacific/Chatham	12:13:48 -	LMT	1957 Jan  1
			12:45	Chatham	CHA%sT


# Auckland Is
# uninhabited; Maori and Moriori, colonial settlers, pastoralists, sealers,
# and scientific personnel have wintered

# Campbell I
# minor whaling stations operated 1909/1914
# scientific station operated 1941/1995;
# previously whalers, sealers, pastoralists, and scientific personnel wintered
# was probably like Pacific/Auckland

###############################################################################


# Niue
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Niue	-11:19:40 -	LMT	1901		# Alofi
			-11:20	-	NUT	1951	# Niue Time
			-11:30	-	NUT	1978 Oct 1
			-11:00	-	NUT

# Norfolk
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Norfolk	11:11:52 -	LMT	1901		# Kingston
			11:12	-	NMT	1951	# Norfolk Mean Time
			11:30	-	NFT		# Norfolk Time

# Palau (Belau)
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Palau	8:57:56 -	LMT	1901		# Koror
			9:00	-	PWT	# Palau Time

# Papua New Guinea
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Port_Moresby 9:48:40 -	LMT	1880
			9:48:32	-	PMMT	1895	# Port Moresby Mean Time
			10:00	-	PGT		# Papua New Guinea Time

# Pitcairn
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Pitcairn	-8:40:20 -	LMT	1901		# Adamstown
			-8:30	-	PNT	1998 Apr 27 00:00
			-8:00	-	PST	# Pitcairn Standard Time

# American Samoa
Zone Pacific/Pago_Pago	 12:37:12 -	LMT	1879 Jul  5
			-11:22:48 -	LMT	1911
			-11:30	-	SAMT	1950		# Samoa Time
			-11:00	-	NST	1967 Apr	# N=Nome
			-11:00	-	BST	1983 Nov 30	# B=Bering
			-11:00	-	SST			# S=Samoa

# Samoa

# From Steffen Thorsen (2009-10-16):
# We have been in contact with the government of Samoa again, and received
# the following info:
#
# "Cabinet has now approved Daylight Saving to be effected next year
# commencing from the last Sunday of September 2010 and conclude first
# Sunday of April 2011."
#
# Background info:
# 
# http://www.timeanddate.com/news/time/samoa-dst-plan-2009.html
# 
#
# Samoa's Daylight Saving Time Act 2009 is available here, but does not
# contain any dates:
# 
# http://www.parliament.gov.ws/documents/acts/Daylight%20Saving%20Act%20%202009%20%28English%29%20-%20Final%207-7-091.pdf
# 

# From Laupue Raymond Hughes (2010-10-07):
# Please see
# 
# http://www.mcil.gov.ws
# ,
# the Ministry of Commerce, Industry and Labour (sideframe) "Last Sunday
# September 2010 (26/09/10) - adjust clocks forward from 12:00 midnight
# to 01:00am and First Sunday April 2011 (03/04/11) - adjust clocks
# backwards from 1:00am to 12:00am"

# From Laupue Raymond Hughes (2011-03-07):
# I believe this will be posted shortly on the website
# 
# www.mcil.gov.ws
# 
#
# PUBLIC NOTICE ON DAYLIGHT SAVING TIME
#
# Pursuant to the Daylight Saving Act 2009 and Cabinets decision,
# businesses and the general public are hereby advised that daylight
# saving time is on the first Saturday of April 2011 (02/04/11).
#
# The public is therefore advised that when the standard time strikes
# the hour of four oclock (4.00am or 0400 Hours) on the 2nd April 2011,
# then all instruments used to measure standard time are to be
# adjusted/changed to three oclock (3:00am or 0300Hrs).
#
# Margaret Fruean ACTING CHIEF EXECUTIVE OFFICER MINISTRY OF COMMERCE,
# INDUSTRY AND LABOUR 28th February 2011

# From David Zuelke (2011-05-09):
# Subject: Samoa to move timezone from east to west of international date line
#
# 
# http://www.morningstar.co.uk/uk/markets/newsfeeditem.aspx?id=138501958347963
# 

# From Mark Sim-Smith (2011-08-17):
# I have been in contact with Leilani Tuala Warren from the Samoa Law
# Reform Commission, and she has sent me a copy of the Bill that she
# confirmed has been passed...Most of the sections are about maps rather
# than the time zone change, but I'll paste the relevant bits below. But
# the essence is that at midnight 29 Dec (UTC-11 I suppose), Samoa
# changes from UTC-11 to UTC+13:
#
# International Date Line Bill 2011
#
# AN ACT to provide for the change to standard time in Samoa and to make
# consequential amendments to the position of the International Date
# Line, and for related purposes.
#
# BE IT ENACTED by the Legislative Assembly of Samoa in Parliament
# assembled as follows:
#
# 1. Short title and commencement-(1) This Act may be cited as the
# International Date Line Act 2011. (2) Except for section 5(3) this Act
# commences at 12 o'clock midnight, on Thursday 29th December 2011. (3)
# Section 5(3) commences on the date of assent by the Head of State.
#
# [snip]
#
# 3. Interpretation - [snip] "Samoa standard time" in this Act and any
# other statute of Samoa which refers to 'Samoa standard time' means the
# time 13 hours in advance of Co-ordinated Universal Time.
#
# 4. Samoa standard time - (1) Upon the commencement of this Act, Samoa
# standard time shall be set at 13 hours in advance of Co-ordinated
# Universal Time for the whole of Samoa. (2) All references to Samoa's
# time zone and to Samoa standard time in Samoa in all legislation and
# instruments after the commencement of this Act shall be references to
# Samoa standard time as provided for in this Act. (3) Nothing in this
# Act affects the provisions of the Daylight Saving Act 2009, except that
# it defines Samoa standard time....

# From Laupue Raymond Hughes (2011-09-02):
# 
# http://www.mcil.gov.ws/mcil_publications.html
# 
#
# here is the official website publication for Samoa DST and dateline change
#
# DST
# Year	End	Time	Start	Time
# 2011	- - -	- - -	24 September	3:00am to 4:00am
# 2012	01 April	4:00am to 3:00am	- - -	- - -
#
# Dateline Change skip Friday 30th Dec 2011
# Thursday 29th December 2011	23:59:59 Hours
# Saturday 31st December 2011	00:00:00 Hours
#
# Clarification by Tim Parenti (2012-01-03):
# Although Samoa has used Daylight Saving Time in the 2010-2011 and 2011-2012
# seasons, there is not yet any indication that this trend will continue on
# a regular basis. For now, we have explicitly listed the transitions below.
#
# From Nicky (2012-09-10):
# Daylight Saving Time commences on Sunday 30th September 2012 and
# ends on Sunday 7th of April 2013.
#
# Please find link below for more information.
# http://www.mcil.gov.ws/mcil_publications.html
#
# That publication also includes dates for Summer of 2013/4 as well
# which give the impression of a pattern in selecting dates for the
# future, so for now, we will guess this will continue.

# Western Samoa
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	WS	2012	max	-	Sep	lastSun	3:00	1	D
Rule	WS	2012	max	-	Apr	Sun>=1	4:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Apia	 12:33:04 -	LMT	1879 Jul  5
			-11:26:56 -	LMT	1911
			-11:30	-	SAMT	1950		# Samoa Time
			-11:00	-	WST	2010 Sep 26
			-11:00	1:00	WSDT	2011 Apr 2 4:00
			-11:00	-	WST	2011 Sep 24 3:00
			-11:00	1:00	WSDT	2011 Dec 30
			 13:00	1:00	WSDT	2012 Apr Sun>=1 4:00
			 13:00	WS	WS%sT

# Solomon Is
# excludes Bougainville, for which see Papua New Guinea
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Guadalcanal 10:39:48 -	LMT	1912 Oct	# Honiara
			11:00	-	SBT	# Solomon Is Time

# Tokelau Is
#
# From Gwillim Law (2011-12-29)
# A correspondent informed me that Tokelau, like Samoa, will be skipping
# December 31 this year ...
#
# From Steffen Thorsen (2012-07-25)
# ... we double checked by calling hotels and offices based in Tokelau asking
# about the time there, and they all told a time that agrees with UTC+13....
# Shanks says UTC-10 from 1901 [but] ... there is a good chance the change
# actually was to UTC-11 back then.
#
# From Paul Eggert (2012-07-25)
# A Google Books snippet of Appendix to the Journals of the House of
# Representatives of New Zealand, Session 1948,
# , page 65, says Tokelau
# was "11 hours slow on G.M.T."  Go with Thorsen and assume Shanks & Pottenger
# are off by an hour starting in 1901.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Fakaofo	-11:24:56 -	LMT	1901
			-11:00	-	TKT 2011 Dec 30	# Tokelau Time
			13:00	-	TKT

# Tonga
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Tonga	1999	only	-	Oct	 7	2:00s	1:00	S
Rule	Tonga	2000	only	-	Mar	19	2:00s	0	-
Rule	Tonga	2000	2001	-	Nov	Sun>=1	2:00	1:00	S
Rule	Tonga	2001	2002	-	Jan	lastSun	2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Tongatapu	12:19:20 -	LMT	1901
			12:20	-	TOT	1941 # Tonga Time
			13:00	-	TOT	1999
			13:00	Tonga	TO%sT

# Tuvalu
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Funafuti	11:56:52 -	LMT	1901
			12:00	-	TVT	# Tuvalu Time


# US minor outlying islands

# Howland, Baker
# Howland was mined for guano by American companies 1857-1878 and British
# 1886-1891; Baker was similar but exact dates are not known.
# Inhabited by civilians 1935-1942; U.S. military bases 1943-1944;
# uninhabited thereafter.
# Howland observed Hawaii Standard Time (UTC-10:30) in 1937;
# see page 206 of Elgen M. Long and Marie K. Long,
# Amelia Earhart: the Mystery Solved, Simon & Schuster (2000).
# So most likely Howland and Baker observed Hawaii Time from 1935
# until they were abandoned after the war.

# Jarvis
# Mined for guano by American companies 1857-1879 and British 1883?-1891?.
# Inhabited by civilians 1935-1942; IGY scientific base 1957-1958;
# uninhabited thereafter.
# no information; was probably like Pacific/Kiritimati

# Johnston
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Pacific/Johnston	-10:00	-	HST

# Kingman
# uninhabited

# Midway
#
# From Mark Brader (2005-01-23):
# [Fallacies and Fantasies of Air Transport History, by R.E.G. Davies,
# published 1994 by Paladwr Press, McLean, VA, USA; ISBN 0-9626483-5-3]
# reproduced a Pan American Airways timeables from 1936, for their weekly
# "Orient Express" flights between San Francisco and Manila, and connecting
# flights to Chicago and the US East Coast.  As it uses some time zone
# designations that I've never seen before:....
# Fri. 6:30A Lv. HONOLOLU (Pearl Harbor), H.I.   H.L.T. Ar. 5:30P Sun.
#  "   3:00P Ar. MIDWAY ISLAND . . . . . . . . . M.L.T. Lv. 6:00A  "
#
Zone Pacific/Midway	-11:49:28 -	LMT	1901
			-11:00	-	NST	1956 Jun  3
			-11:00	1:00	NDT	1956 Sep  2
			-11:00	-	NST	1967 Apr	# N=Nome
			-11:00	-	BST	1983 Nov 30	# B=Bering
			-11:00	-	SST			# S=Samoa

# Palmyra
# uninhabited since World War II; was probably like Pacific/Kiritimati

# Wake
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Wake	11:06:28 -	LMT	1901
			12:00	-	WAKT	# Wake Time


# Vanuatu
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Vanuatu	1983	only	-	Sep	25	0:00	1:00	S
Rule	Vanuatu	1984	1991	-	Mar	Sun>=23	0:00	0	-
Rule	Vanuatu	1984	only	-	Oct	23	0:00	1:00	S
Rule	Vanuatu	1985	1991	-	Sep	Sun>=23	0:00	1:00	S
Rule	Vanuatu	1992	1993	-	Jan	Sun>=23	0:00	0	-
Rule	Vanuatu	1992	only	-	Oct	Sun>=23	0:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Efate	11:13:16 -	LMT	1912 Jan 13		# Vila
			11:00	Vanuatu	VU%sT	# Vanuatu Time

# Wallis and Futuna
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Pacific/Wallis	12:15:20 -	LMT	1901
			12:00	-	WFT	# Wallis & Futuna Time

###############################################################################

# NOTES

# This data is by no means authoritative; if you think you know better,
# go ahead and edit the file (and please send any changes to
# tz@iana.org for general use in the future).

# From Paul Eggert (2013-02-21):
# A good source for time zone historical data outside the U.S. is
# Thomas G. Shanks and Rique Pottenger, The International Atlas (6th edition),
# San Diego: ACS Publications, Inc. (2003).
#
# Gwillim Law writes that a good source
# for recent time zone data is the International Air Transport
# Association's Standard Schedules Information Manual (IATA SSIM),
# published semiannually.  Law sent in several helpful summaries
# of the IATA's data after 1990.
#
# Except where otherwise noted, Shanks & Pottenger is the source for
# entries through 1990, and IATA SSIM is the source for entries afterwards.
#
# Another source occasionally used is Edward W. Whitman, World Time Differences,
# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), which
# I found in the UCLA library.
#
# For data circa 1899, a common source is:
# Milne J. Civil time. Geogr J. 1899 Feb;13(2):173-94
# .
#
# A reliable and entertaining source about time zones is
# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997).
#
# I invented the abbreviations marked `*' in the following table;
# the rest are from earlier versions of this file, or from other sources.
# Corrections are welcome!
#		std dst
#		LMT	Local Mean Time
#	  8:00	WST WST	Western Australia
#	  8:45	CWST CWST Central Western Australia*
#	  9:00	JST	Japan
#	  9:30	CST CST	Central Australia
#	 10:00	EST EST	Eastern Australia
#	 10:00	ChST	Chamorro
#	 10:30	LHST LHST Lord Howe*
#	 11:30	NZMT NZST New Zealand through 1945
#	 12:00	NZST NZDT New Zealand 1946-present
#	 12:45	CHAST CHADT Chatham*
#	-11:00	SST	Samoa
#	-10:00	HST	Hawaii
#	- 8:00	PST	Pitcairn*
#
# See the `northamerica' file for Hawaii.
# See the `southamerica' file for Easter I and the Galapagos Is.

###############################################################################

# Australia

# From Paul Eggert (2005-12-08):
# 
# Implementation Dates of Daylight Saving Time within Australia
#  summarizes daylight saving issues in Australia.

# From Arthur David Olson (2005-12-12):
# 
# Lawlink NSW:Daylight Saving in New South Wales
#  covers New South Wales in particular.

# From John Mackin (1991-03-06):
# We in Australia have _never_ referred to DST as `daylight' time.
# It is called `summer' time.  Now by a happy coincidence, `summer'
# and `standard' happen to start with the same letter; hence, the
# abbreviation does _not_ change...
# The legislation does not actually define abbreviations, at least
# in this State, but the abbreviation is just commonly taken to be the
# initials of the phrase, and the legislation here uniformly uses
# the phrase `summer time' and does not use the phrase `daylight
# time'.
# Announcers on the Commonwealth radio network, the ABC (for Australian
# Broadcasting Commission), use the phrases `Eastern Standard Time'
# or `Eastern Summer Time'.  (Note, though, that as I say in the
# current australasia file, there is really no such thing.)  Announcers
# on its overseas service, Radio Australia, use the same phrases
# prefixed by the word `Australian' when referring to local times;
# time announcements on that service, naturally enough, are made in UTC.

# From Arthur David Olson (1992-03-08):
# Given the above, what's chosen for year-round use is:
#	CST	for any place operating at a GMTOFF of 9:30
#	WST	for any place operating at a GMTOFF of 8:00
#	EST	for any place operating at a GMTOFF of 10:00

# From Chuck Soper (2006-06-01):
# I recently found this Australian government web page on time zones:
# 
# And this government web page lists time zone names and abbreviations:
# 

# From Paul Eggert (2001-04-05), summarizing a long discussion about "EST"
# versus "AEST" etc.:
#
# I see the following points of dispute:
#
# * How important are unique time zone abbreviations?
#
#   Here I tend to agree with the point (most recently made by Chris
#   Newman) that unique abbreviations should not be essential for proper
#   operation of software.  We have other instances of ambiguity
#   (e.g. "IST" denoting both "Israel Standard Time" and "Indian
#   Standard Time"), and they are not likely to go away any time soon.
#   In the old days, some software mistakenly relied on unique
#   abbreviations, but this is becoming less true with time, and I don't
#   think it's that important to cater to such software these days.
#
#   On the other hand, there is another motivation for unambiguous
#   abbreviations: it cuts down on human confusion.  This is
#   particularly true for Australia, where "EST" can mean one thing for
#   time T and a different thing for time T plus 1 second.
#
# * Does the relevant legislation indicate which abbreviations should be used?
#
#   Here I tend to think that things are a mess, just as they are in
#   many other countries.  We Americans are currently disagreeing about
#   which abbreviation to use for the newly legislated Chamorro Standard
#   Time, for example.
#
#   Personally, I would prefer to use common practice; I would like to
#   refer to legislation only for examples of common practice, or as a
#   tiebreaker.
#
# * Do Australians more often use "Eastern Daylight Time" or "Eastern
#   Summer Time"?  Do they typically prefix the time zone names with
#   the word "Australian"?
#
#   My own impression is that both "Daylight Time" and "Summer Time" are
#   common and are widely understood, but that "Summer Time" is more
#   popular; and that the leading "A" is also common but is omitted more
#   often than not.  I just used AltaVista advanced search and got the
#   following count of page hits:
#
#     1,103 "Eastern Summer Time" AND domain:au
#       971 "Australian Eastern Summer Time" AND domain:au
#       613 "Eastern Daylight Time" AND domain:au
#       127 "Australian Eastern Daylight Time" AND domain:au
#
#   Here "Summer" seems quite a bit more popular than "Daylight",
#   particularly when we know the time zone is Australian and not US,
#   say.  The "Australian" prefix seems to be popular for Eastern Summer
#   Time, but unpopular for Eastern Daylight Time.
#
#   For abbreviations, tools like AltaVista are less useful because of
#   ambiguity.  Many hits are not really time zones, unfortunately, and
#   many hits denote US time zones and not Australian ones.  But here
#   are the hit counts anyway:
#
#     161,304 "EST" and domain:au
#      25,156 "EDT" and domain:au
#      18,263 "AEST" and domain:au
#      10,416 "AEDT" and domain:au
#
#      14,538 "CST" and domain:au
#       5,728 "CDT" and domain:au
#         176 "ACST" and domain:au
#          29 "ACDT" and domain:au
#
#       7,539 "WST" and domain:au
#          68 "AWST" and domain:au
#
#   This data suggest that Australians tend to omit the "A" prefix in
#   practice.  The situation for "ST" versus "DT" is less clear, given
#   the ambiguities involved.
#
# * How do Australians feel about the abbreviations in the tz database?
#
#   If you just count Australians on this list, I count 2 in favor and 3
#   against.  One of the "against" votes (David Keegel) counseled delay,
#   saying that both AEST/AEDT and EST/EST are widely used and
#   understood in Australia.

# From Paul Eggert (1995-12-19):
# Shanks & Pottenger report 2:00 for all autumn changes in Australia and NZ.
# Mark Prior writes that his newspaper
# reports that NSW's fall 1995 change will occur at 2:00,
# but Robert Elz says it's been 3:00 in Victoria since 1970
# and perhaps the newspaper's `2:00' is referring to standard time.
# For now we'll continue to assume 2:00s for changes since 1960.

# From Eric Ulevik (1998-01-05):
#
# Here are some URLs to Australian time legislation. These URLs are stable,
# and should probably be included in the data file. There are probably more
# relevant entries in this database.
#
# NSW (including LHI and Broken Hill):
# 
# Standard Time Act 1987 (updated 1995-04-04)
# 
# ACT
# 
# Standard Time and Summer Time Act 1972
# 
# SA
# 
# Standard Time Act, 1898
# 

# From David Grosz (2005-06-13):
# It was announced last week that Daylight Saving would be extended by
# one week next year to allow for the 2006 Commonwealth Games.
# Daylight Saving is now to end for next year only on the first Sunday
# in April instead of the last Sunday in March.
#
# From Gwillim Law (2005-06-14):
# I did some Googling and found that all of those states (and territory) plan
# to extend DST together in 2006.
# ACT: http://www.cmd.act.gov.au/mediareleases/fileread.cfm?file=86.txt
# New South Wales: http://www.thecouriermail.news.com.au/common/story_page/0,5936,15538869%255E1702,00.html
# South Australia: http://www.news.com.au/story/0,10117,15555031-1246,00.html
# Tasmania: http://www.media.tas.gov.au/release.php?id=14772
# Victoria: I wasn't able to find anything separate, but the other articles
# allude to it.
# But not Queensland
# http://www.news.com.au/story/0,10117,15564030-1248,00.html.

# Northern Territory

# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06):
# # The NORTHERN TERRITORY..  [ Courtesy N.T. Dept of the Chief Minister ]
# #					[ Nov 1990 ]
# #	N.T. have never utilised any DST due to sub-tropical/tropical location.
# ...
# Zone        Australia/North         9:30    -       CST

# From Bradley White (1991-03-04):
# A recent excerpt from an Australian newspaper...
# the Northern Territory do[es] not have daylight saving.

# Western Australia

# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06):
# #  The state of WESTERN AUSTRALIA..  [ Courtesy W.A. dept Premier+Cabinet ]
# #						[ Nov 1990 ]
# #	W.A. suffers from a great deal of public and political opposition to
# #	DST in principle. A bill is brought before parliament in most years, but
# #	usually defeated either in the upper house, or in party caucus
# #	before reaching parliament.
# ...
# Zone	Australia/West		8:00	AW	%sST
# ...
# Rule	AW	1974	only	-	Oct	lastSun	2:00	1:00	D
# Rule	AW	1975	only	-	Mar	Sun>=1	3:00	0	W
# Rule	AW	1983	only	-	Oct	lastSun	2:00	1:00	D
# Rule	AW	1984	only	-	Mar	Sun>=1	3:00	0	W

# From Bradley White (1991-03-04):
# A recent excerpt from an Australian newspaper...
# Western Australia...do[es] not have daylight saving.

# From John D. Newman via Bradley White (1991-11-02):
# Western Australia is still on "winter time". Some DH in Sydney
# rang me at home a few days ago at 6.00am. (He had just arrived at
# work at 9.00am.)
# W.A. is switching to Summer Time on Nov 17th just to confuse
# everybody again.

# From Arthur David Olson (1992-03-08):
# The 1992 ending date used in the rules is a best guess;
# it matches what was used in the past.

# 
# The Australian Bureau of Meteorology FAQ
#  (1999-09-27) writes that Giles Meteorological Station uses
# South Australian time even though it's located in Western Australia.

# Queensland
# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06):
# #   The state of QUEENSLAND.. [ Courtesy Qld. Dept Premier Econ&Trade Devel ]
# #						[ Dec 1990 ]
# ...
# Zone	Australia/Queensland	10:00	AQ	%sST
# ...
# Rule	AQ	1971	only	-	Oct	lastSun	2:00	1:00	D
# Rule	AQ	1972	only	-	Feb	lastSun	3:00	0	E
# Rule	AQ	1989	max	-	Oct	lastSun	2:00	1:00	D
# Rule	AQ	1990	max	-	Mar	Sun>=1	3:00	0	E

# From Bradley White (1989-12-24):
# "Australia/Queensland" now observes daylight time (i.e. from
# October 1989).

# From Bradley White (1991-03-04):
# A recent excerpt from an Australian newspaper...
# ...Queensland...[has] agreed to end daylight saving
# at 3am tomorrow (March 3)...

# From John Mackin (1991-03-06):
# I can certainly confirm for my part that Daylight Saving in NSW did in fact
# end on Sunday, 3 March.  I don't know at what hour, though.  (It surprised
# me.)

# From Bradley White (1992-03-08):
# ...there was recently a referendum in Queensland which resulted
# in the experimental daylight saving system being abandoned. So, ...
# ...
# Rule	QLD	1989	1991	-	Oct	lastSun	2:00	1:00	D
# Rule	QLD	1990	1992	-	Mar	Sun>=1	3:00	0	S
# ...

# From Arthur David Olson (1992-03-08):
# The chosen rules the union of the 1971/1972 change and the 1989-1992 changes.

# From Christopher Hunt (2006-11-21), after an advance warning
# from Jesper Norgaard Welen (2006-11-01):
# WA are trialing DST for three years.
# 

# From Rives McDow (2002-04-09):
# The most interesting region I have found consists of three towns on the
# southern coast....  South Australia observes daylight saving time; Western
# Australia does not.  The two states are one and a half hours apart.  The
# residents decided to forget about this nonsense of changing the clock so
# much and set the local time 20 hours and 45 minutes from the
# international date line, or right in the middle of the time of South
# Australia and Western Australia....
#
# From Paul Eggert (2002-04-09):
# This is confirmed by the section entitled
# "What's the deal with time zones???" in
# .
#
# From Alex Livingston (2006-12-07):
# ... it was just on four years ago that I drove along the Eyre Highway,
# which passes through eastern Western Australia close to the southern
# coast of the continent.
#
# I paid particular attention to the time kept there. There can be no
# dispute that UTC+08:45 was considered "the time" from the border
# village just inside the border with South Australia to as far west
# as just east of Caiguna. There can also be no dispute that Eucla is
# the largest population centre in this zone....
#
# Now that Western Australia is observing daylight saving, the
# question arose whether this part of the state would follow suit. I
# just called the border village and confirmed that indeed they have,
# meaning that they are now observing UTC+09:45.
#
# (2006-12-09):
# I personally doubt that either experimentation with daylight saving
# in WA or its introduction in SA had anything to do with the genesis
# of this time zone.  My hunch is that it's been around since well
# before 1975.  I remember seeing it noted on road maps decades ago.

# From Paul Eggert (2006-12-15):
# For lack of better info, assume the tradition dates back to the
# introduction of standard time in 1895.


# southeast Australia
#
# From Paul Eggert (2007-07-23):
# Starting autumn 2008 Victoria, NSW, South Australia, Tasmania and the ACT
# end DST the first Sunday in April and start DST the first Sunday in October.
# http://www.theage.com.au/news/national/daylight-savings-to-span-six-months/2007/06/27/1182623966703.html


# South Australia

# From Bradley White (1991-03-04):
# A recent excerpt from an Australian newspaper...
# ...South Australia...[has] agreed to end daylight saving
# at 3am tomorrow (March 3)...

# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06):
# #   The state of SOUTH AUSTRALIA....[ Courtesy of S.A. Dept of Labour ]
# #						[ Nov 1990 ]
# ...
# Zone	Australia/South		9:30	AS	%sST
# ...
# Rule	 AS	1971	max	-	Oct	lastSun	2:00	1:00	D
# Rule	 AS	1972	1985	-	Mar	Sun>=1	3:00	0	C
# Rule	 AS	1986	1990	-	Mar	Sun>=15	3:00	0	C
# Rule	 AS	1991	max	-	Mar	Sun>=1	3:00	0	C

# From Bradley White (1992-03-11):
# Recent correspondence with a friend in Adelaide
# contained the following exchange:  "Due to the Adelaide Festival,
# South Australia delays setting back our clocks for a few weeks."

# From Robert Elz (1992-03-13):
# I heard that apparently (or at least, it appears that)
# South Aus will have an extra 3 weeks daylight saving every even
# numbered year (from 1990).  That's when the Adelaide Festival
# is on...

# From Robert Elz (1992-03-16, 00:57:07 +1000):
# DST didn't end in Adelaide today (yesterday)....
# But whether it's "4th Sunday" or "2nd last Sunday" I have no idea whatever...
# (it's just as likely to be "the Sunday we pick for this year"...).

# From Bradley White (1994-04-11):
# If Sun, 15 March, 1992 was at +1030 as kre asserts, but yet Sun, 20 March,
# 1994 was at +0930 as John Connolly's customer seems to assert, then I can
# only conclude that the actual rule is more complicated....

# From John Warburton (1994-10-07):
# The new Daylight Savings dates for South Australia ...
# was gazetted in the Government Hansard on Sep 26 1994....
# start on last Sunday in October and end in last sunday in March.

# From Paul Eggert (2007-07-23):
# See "southeast Australia" above for 2008 and later.

# Tasmania

# The rules for 1967 through 1991 were reported by George Shepherd
# via Simon Woodhead via Robert Elz (1991-03-06):
# #  The state of TASMANIA.. [Courtesy Tasmanian Dept of Premier + Cabinet ]
# #					[ Nov 1990 ]

# From Bill Hart via Guy Harris (1991-10-10):
# Oh yes, the new daylight savings rules are uniquely tasmanian, we have
# 6 weeks a year now when we are out of sync with the rest of Australia
# (but nothing new about that).

# From Alex Livingston (1999-10-04):
# I heard on the ABC (Australian Broadcasting Corporation) radio news on the
# (long) weekend that Tasmania, which usually goes its own way in this regard,
# has decided to join with most of NSW, the ACT, and most of Victoria
# (Australia) and start daylight saving on the last Sunday in August in 2000
# instead of the first Sunday in October.

# Sim Alam (2000-07-03) reported a legal citation for the 2000/2001 rules:
# http://www.thelaw.tas.gov.au/fragview/42++1968+GS3A@EN+2000070300

# From Paul Eggert (2007-07-23):
# See "southeast Australia" above for 2008 and later.

# Victoria

# The rules for 1971 through 1991 were reported by George Shepherd
# via Simon Woodhead via Robert Elz (1991-03-06):
# #   The state of VICTORIA.. [ Courtesy of Vic. Dept of Premier + Cabinet ]
# #						[ Nov 1990 ]

# From Scott Harrington (2001-08-29):
# On KQED's "City Arts and Lectures" program last night I heard an
# interesting story about daylight savings time.  Dr. John Heilbron was
# discussing his book "The Sun in the Church: Cathedrals as Solar
# Observatories"[1], and in particular the Shrine of Remembrance[2] located
# in Melbourne, Australia.
#
# Apparently the shrine's main purpose is a beam of sunlight which
# illuminates a special spot on the floor at the 11th hour of the 11th day
# of the 11th month (Remembrance Day) every year in memory of Australia's
# fallen WWI soldiers.  And if you go there on Nov. 11, at 11am local time,
# you will indeed see the sunbeam illuminate the special spot at the
# expected time.
#
# However, that is only because of some special mirror contraption that had
# to be employed, since due to daylight savings time, the true solar time of
# the remembrance moment occurs one hour later (or earlier?).  Perhaps
# someone with more information on this jury-rig can tell us more.
#
# [1] http://www.hup.harvard.edu/catalog/HEISUN.html
# [2] http://www.shrine.org.au

# From Paul Eggert (2007-07-23):
# See "southeast Australia" above for 2008 and later.

# New South Wales

# From Arthur David Olson:
# New South Wales and subjurisdictions have their own ideas of a fun time.
# Based on law library research by John Mackin,
# who notes:
#	In Australia, time is not legislated federally, but rather by the
#	individual states.  Thus, while such terms as ``Eastern Standard Time''
#	[I mean, of course, Australian EST, not any other kind] are in common
#	use, _they have NO REAL MEANING_, as they are not defined in the
#	legislation.  This is very important to understand.
#	I have researched New South Wales time only...

# From Eric Ulevik (1999-05-26):
# DST will start in NSW on the last Sunday of August, rather than the usual
# October in 2000.  [See: Matthew Moore,
# 
# Two months more daylight saving
# 
# Sydney Morning Herald (1999-05-26).]

# From Paul Eggert (1999-09-27):
# See the following official NSW source:
# 
# Daylight Saving in New South Wales.
# 
#
# Narrabri Shire (NSW) council has announced it will ignore the extension of
# daylight saving next year.  See:
# 
# Narrabri Council to ignore daylight saving
#  (1999-07-22).  For now, we'll wait to see if this really happens.
#
# Victoria will following NSW.  See:
# 
# Vic to extend daylight saving
#  (1999-07-28).
#
# However, South Australia rejected the DST request.  See:
# 
# South Australia rejects Olympics daylight savings request
#  (1999-07-19).
#
# Queensland also will not observe DST for the Olympics.  See:
# 
# Qld says no to daylight savings for Olympics
#  (1999-06-01), which quotes Queensland Premier Peter Beattie as saying
# ``Look you've got to remember in my family when this came up last time
# I voted for it, my wife voted against it and she said to me it's all very
# well for you, you don't have to worry about getting the children out of
# bed, getting them to school, getting them to sleep at night.
# I've been through all this argument domestically...my wife rules.''
#
# Broken Hill will stick with South Australian time in 2000.  See:
# 
# Broken Hill to be behind the times
#  (1999-07-21).

# IATA SSIM (1998-09) says that the spring 2000 change for Australian
# Capital Territory, New South Wales except Lord Howe Island and Broken
# Hill, and Victoria will be August 27, presumably due to the Sydney Olympics.

# From Eric Ulevik, referring to Sydney's Sun Herald (2000-08-13), page 29:
# The Queensland Premier Peter Beattie is encouraging northern NSW
# towns to use Queensland time.

# From Paul Eggert (2007-07-23):
# See "southeast Australia" above for 2008 and later.

# Yancowinna

# From John Mackin (1989-01-04):
# `Broken Hill' means the County of Yancowinna.

# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06):
# # YANCOWINNA..  [ Confirmation courtesy of Broken Hill Postmaster ]
# #					[ Dec 1990 ]
# ...
# # Yancowinna uses Central Standard Time, despite [its] location on the
# # New South Wales side of the S.A. border. Most business and social dealings
# # are with CST zones, therefore CST is legislated by local government
# # although the switch to Summer Time occurs in line with N.S.W. There have
# # been years when this did not apply, but the historical data is not
# # presently available.
# Zone	Australia/Yancowinna	9:30	 AY	%sST
# ...
# Rule	 AY	1971	1985	-	Oct	lastSun	2:00	1:00	D
# Rule	 AY	1972	only	-	Feb	lastSun	3:00	0	C
# [followed by other Rules]

# Lord Howe Island

# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06):
# LHI...		[ Courtesy of Pauline Van Winsen ]
#					[ Dec 1990 ]
# Lord Howe Island is located off the New South Wales coast, and is half an
# hour ahead of NSW time.

# From James Lonergan, Secretary, Lord Howe Island Board (2000-01-27):
# Lord Howe Island summer time in 2000/2001 will commence on the same
# date as the rest of NSW (i.e. 2000-08-27).  For your information the
# Lord Howe Island Board (controlling authority for the Island) is
# seeking the community's views on various options for summer time
# arrangements on the Island, e.g. advance clocks by 1 full hour
# instead of only 30 minutes.  [Dependent] on the wishes of residents
# the Board may approach the NSW government to change the existing
# arrangements.  The starting date for summer time on the Island will
# however always coincide with the rest of NSW.

# From James Lonergan, Secretary, Lord Howe Island Board (2000-10-25):
# Lord Howe Island advances clocks by 30 minutes during DST in NSW and retards
# clocks by 30 minutes when DST finishes. Since DST was most recently
# introduced in NSW, the "changeover" time on the Island has been 02:00 as
# shown on clocks on LHI. I guess this means that for 30 minutes at the start
# of DST, LHI is actually 1 hour ahead of the rest of NSW.

# From Paul Eggert (2006-03-22):
# For Lord Howe dates we use Shanks & Pottenger through 1989, and
# Lonergan thereafter.  For times we use Lonergan.

# From Paul Eggert (2007-07-23):
# See "southeast Australia" above for 2008 and later.

# From Steffen Thorsen (2009-04-28):
# According to the official press release, South Australia's extended daylight
# saving period will continue with the same rules as used during the 2008-2009
# summer (southern hemisphere).
#
# From
# 
# http://www.safework.sa.gov.au/uploaded_files/DaylightDatesSet.pdf
# 
# The extended daylight saving period that South Australia has been trialling
# for over the last year is now set to be ongoing.
# Daylight saving will continue to start on the first Sunday in October each
# year and finish on the first Sunday in April the following year.
# Industrial Relations Minister, Paul Caica, says this provides South Australia
# with a consistent half hour time difference with NSW, Victoria, Tasmania and
# the ACT for all 52 weeks of the year...
#
# We have a wrap-up here:
# 
# http://www.timeanddate.com/news/time/south-australia-extends-dst.html
# 
###############################################################################

# New Zealand

# From Mark Davies (1990-10-03):
# the 1989/90 year was a trial of an extended "daylight saving" period.
# This trial was deemed successful and the extended period adopted for
# subsequent years (with the addition of a further week at the start).
# source -- phone call to Ministry of Internal Affairs Head Office.

# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06):
# # The Country of New Zealand   (Australia's east island -) Gee they hate that!
# #				   or is Australia the west island of N.Z.
# #	[ courtesy of Geoff Tribble.. Auckland N.Z. ]
# #				[ Nov 1990 ]
# ...
# Rule	NZ      1974    1988	-	Oct	lastSun	2:00	1:00	D
# Rule	NZ	1989	max	-	Oct	Sun>=1	2:00	1:00	D
# Rule	NZ      1975    1989	-	Mar	Sun>=1	3:00	0	S
# Rule	NZ	1990	max	-	Mar	lastSun	3:00	0	S
# ...
# Zone	NZ			12:00	NZ		NZ%sT	# New Zealand
# Zone	NZ-CHAT			12:45	-		NZ-CHAT # Chatham Island

# From Arthur David Olson (1992-03-08):
# The chosen rules use the Davies October 8 values for the start of DST in 1989
# rather than the October 1 value.

# From Paul Eggert (1995-12-19);
# Shank & Pottenger report 2:00 for all autumn changes in Australia and NZ.
# Robert Uzgalis writes that the New Zealand Daylight
# Savings Time Order in Council dated 1990-06-18 specifies 2:00 standard
# time on both the first Sunday in October and the third Sunday in March.
# As with Australia, we'll assume the tradition is 2:00s, not 2:00.
#
# From Paul Eggert (2006-03-22):
# The Department of Internal Affairs (DIA) maintains a brief history,
# as does Carol Squires; see tz-link.htm for the full references.
# Use these sources in preference to Shanks & Pottenger.
#
# For Chatham, IATA SSIM (1991/1999) gives the NZ rules but with
# transitions at 2:45 local standard time; this confirms that Chatham
# is always exactly 45 minutes ahead of Auckland.

# From Colin Sharples (2007-04-30):
# DST will now start on the last Sunday in September, and end on the
# first Sunday in April.  The changes take effect this year, meaning
# that DST will begin on 2007-09-30 2008-04-06.
# http://www.dia.govt.nz/diawebsite.nsf/wpg_URL/Services-Daylight-Saving-Daylight-saving-to-be-extended

###############################################################################


# Fiji

# Howse writes (p 153) that in 1879 the British governor of Fiji
# enacted an ordinance standardizing the islands on Antipodean Time
# instead of the American system (which was one day behind).

# From Rives McDow (1998-10-08):
# Fiji will introduce DST effective 0200 local time, 1998-11-01
# until 0300 local time 1999-02-28.  Each year the DST period will
# be from the first Sunday in November until the last Sunday in February.

# From Paul Eggert (2000-01-08):
# IATA SSIM (1999-09) says DST ends 0100 local time.  Go with McDow.

# From the BBC World Service in
# http://news.bbc.co.uk/2/hi/asia-pacific/205226.stm (1998-10-31 16:03 UTC):
# The Fijiian government says the main reasons for the time change is to
# improve productivity and reduce road accidents.... [T]he move is also
# intended to boost Fiji's ability to attract tourists to witness the dawning
# of the new millennium.

# http://www.fiji.gov.fj/press/2000_09/2000_09_13-05.shtml (2000-09-13)
# reports that Fiji has discontinued DST.

# Johnston

# Johnston data is from usno1995.


# Kiribati

# From Paul Eggert (1996-01-22):
# Today's _Wall Street Journal_ (page 1) reports that Kiribati
# ``declared it the same day [throughout] the country as of Jan. 1, 1995''
# as part of the competition to be first into the 21st century.


# Kwajalein

# In comp.risks 14.87 (26 August 1993), Peter Neumann writes:
# I wonder what happened in Kwajalein, where there was NO Friday,
# 1993-08-20.  Thursday night at midnight Kwajalein switched sides with
# respect to the International Date Line, to rejoin its fellow islands,
# going from 11:59 p.m. Thursday to 12:00 m. Saturday in a blink.


# N Mariana Is, Guam

# Howse writes (p 153) ``The Spaniards, on the other hand, reached the
# Philippines and the Ladrones from America,'' and implies that the Ladrones
# (now called the Marianas) kept American date for quite some time.
# For now, we assume the Ladrones switched at the same time as the Philippines;
# see Asia/Manila.

# US Public Law 106-564 (2000-12-23) made UTC+10 the official standard time,
# under the name "Chamorro Standard Time".  There is no official abbreviation,
# but Congressman Robert A. Underwood, author of the bill that became law,
# wrote in a press release (2000-12-27) that he will seek the use of "ChST".


# Micronesia

# Alan Eugene Davis writes (1996-03-16),
# ``I am certain, having lived there for the past decade, that "Truk"
# (now properly known as Chuuk) ... is in the time zone GMT+10.''
#
# Shanks & Pottenger write that Truk switched from UTC+10 to UTC+11
# on 1978-10-01; ignore this for now.

# From Paul Eggert (1999-10-29):
# The Federated States of Micronesia Visitors Board writes in
# 
# The Federated States of Micronesia - Visitor Information
#  (1999-01-26)
# that Truk and Yap are UTC+10, and Ponape and Kosrae are UTC+11.
# We don't know when Kosrae switched from UTC+12; assume January 1 for now.


# Midway

# From Charles T O'Connor, KMTH DJ (1956),
# quoted in the KTMH section of the Radio Heritage Collection
#  (2002-12-31):
# For the past two months we've been on what is known as Daylight
# Saving Time.  This time has put us on air at 5am in the morning,
# your time down there in New Zealand.  Starting September 2, 1956
# we'll again go back to Standard Time.  This'll mean that we'll go to
# air at 6am your time.
#
# From Paul Eggert (2003-03-23):
# We don't know the date of that quote, but we'll guess they
# started DST on June 3.  Possibly DST was observed other years
# in Midway, but we have no record of it.


# Pitcairn

# From Rives McDow (1999-11-08):
# A Proclamation was signed by the Governor of Pitcairn on the 27th March 1998
# with regard to Pitcairn Standard Time.  The Proclamation is as follows.
#
#	The local time for general purposes in the Islands shall be
#	Co-ordinated Universal time minus 8 hours and shall be known
#	as Pitcairn Standard Time.
#
# ... I have also seen Pitcairn listed as UTC minus 9 hours in several
# references, and can only assume that this was an error in interpretation
# somehow in light of this proclamation.

# From Rives McDow (1999-11-09):
# The Proclamation regarding Pitcairn time came into effect on 27 April 1998
# ... at midnight.

# From Howie Phelps (1999-11-10), who talked to a Pitcairner via shortwave:
# Betty Christian told me yesterday that their local time is the same as
# Pacific Standard Time. They used to be 1/2 hour different from us here in
# Sacramento but it was changed a couple of years ago.


# Samoa

# Howse writes (p 153, citing p 10 of the 1883-11-18 New York Herald)
# that in 1879 the King of Samoa decided to change
# ``the date in his kingdom from the Antipodean to the American system,
# ordaining -- by a masterpiece of diplomatic flattery -- that
# the Fourth of July should be celebrated twice in that year.''


# Tonga

# From Paul Eggert (1996-01-22):
# Today's _Wall Street Journal_ (p 1) reports that ``Tonga has been plotting
# to sneak ahead of [New Zealanders] by introducing daylight-saving time.''
# Since Kiribati has moved the Date Line it's not clear what Tonga will do.

# Don Mundell writes in the 1997-02-20 Tonga Chronicle
# 
# How Tonga became `The Land where Time Begins'
# :

# Until 1941 Tonga maintained a standard time 50 minutes ahead of NZST
# 12 hours and 20 minutes ahead of GMT.  When New Zealand adjusted its
# standard time in 1940s, Tonga had the choice of subtracting from its
# local time to come on the same standard time as New Zealand or of
# advancing its time to maintain the differential of 13 degrees
# (approximately 50 minutes ahead of New Zealand time).
#
# Because His Majesty King Taufa'ahau Tupou IV, then Crown Prince
# Tungi, preferred to ensure Tonga's title as the land where time
# begins, the Legislative Assembly approved the latter change.
#
# But some of the older, more conservative members from the outer
# islands objected. "If at midnight on Dec. 31, we move ahead 40
# minutes, as your Royal Highness wishes, what becomes of the 40
# minutes we have lost?"
#
# The Crown Prince, presented an unanswerable argument: "Remember that
# on the World Day of Prayer, you would be the first people on Earth
# to say your prayers in the morning."

# From Paul Eggert (2006-03-22):
# Shanks & Pottenger say the transition was on 1968-10-01; go with Mundell.

# From Eric Ulevik (1999-05-03):
# Tonga's director of tourism, who is also secretary of the National Millennium
# Committee, has a plan to get Tonga back in front.
# He has proposed a one-off move to tropical daylight saving for Tonga from
# October to March, which has won approval in principle from the Tongan
# Government.

# From Steffen Thorsen (1999-09-09):
# * Tonga will introduce DST in November
#
# I was given this link by John Letts:
# 
# http://news.bbc.co.uk/hi/english/world/asia-pacific/newsid_424000/424764.stm
# 
#
# I have not been able to find exact dates for the transition in November
# yet. By reading this article it seems like Fiji will be 14 hours ahead
# of UTC as well, but as far as I know Fiji will only be 13 hours ahead
# (12 + 1 hour DST).

# From Arthur David Olson (1999-09-20):
# According to 
# http://www.tongaonline.com/news/sept1799.html
# :
# "Daylight Savings Time will take effect on Oct. 2 through April 15, 2000
# and annually thereafter from the first Saturday in October through the
# third Saturday of April.  Under the system approved by Privy Council on
# Sept. 10, clocks must be turned ahead one hour on the opening day and
# set back an hour on the closing date."
# Alas, no indication of the time of day.

# From Rives McDow (1999-10-06):
# Tonga started its Daylight Saving on Saturday morning October 2nd at 0200am.
# Daylight Saving ends on April 16 at 0300am which is Sunday morning.

# From Steffen Thorsen (2000-10-31):
# Back in March I found a notice on the website http://www.tongaonline.com
# that Tonga changed back to standard time one month early, on March 19
# instead of the original reported date April 16. Unfortunately, the article
# is no longer available on the site, and I did not make a copy of the
# text, and I have forgotten to report it here.
# (Original URL was: http://www.tongaonline.com/news/march162000.htm )

# From Rives McDow (2000-12-01):
# Tonga is observing DST as of 2000-11-04 and will stop on 2001-01-27.

# From Sione Moala-Mafi (2001-09-20) via Rives McDow:
# At 2:00am on the first Sunday of November, the standard time in the Kingdom
# shall be moved forward by one hour to 3:00am.  At 2:00am on the last Sunday
# of January the standard time in the Kingdom shall be moved backward by one
# hour to 1:00am.

# From Pulu 'Anau (2002-11-05):
# The law was for 3 years, supposedly to get renewed.  It wasn't.


# Wake

# From Vernice Anderson, Personal Secretary to Philip Jessup,
# US Ambassador At Large (oral history interview, 1971-02-02):
#
# Saturday, the 14th [of October, 1950] -- ...  The time was all the
# more confusing at that point, because we had crossed the
# International Date Line, thus getting two Sundays.  Furthermore, we
# discovered that Wake Island had two hours of daylight saving time
# making calculation of time in Washington difficult if not almost
# impossible.
#
# http://www.trumanlibrary.org/wake/meeting.htm

# From Paul Eggert (2003-03-23):
# We have no other report of DST in Wake Island, so omit this info for now.

###############################################################################

# The International Date Line

# From Gwillim Law (2000-01-03):
#
# The International Date Line is not defined by any international standard,
# convention, or treaty.  Mapmakers are free to draw it as they please.
# Reputable mapmakers will simply ensure that every point of land appears on
# the correct side of the IDL, according to the date legally observed there.
#
# When Kiribati adopted a uniform date in 1995, thereby moving the Phoenix and
# Line Islands to the west side of the IDL (or, if you prefer, moving the IDL
# to the east side of the Phoenix and Line Islands), I suppose that most
# mapmakers redrew the IDL following the boundary of Kiribati.  Even that line
# has a rather arbitrary nature.  The straight-line boundaries between Pacific
# island nations that are shown on many maps are based on an international
# convention, but are not legally binding national borders.... The date is
# governed by the IDL; therefore, even on the high seas, there may be some
# places as late as fourteen hours later than UTC.  And, since the IDL is not
# an international standard, there are some places on the high seas where the
# correct date is ambiguous.

# From Wikipedia  (2005-08-31):
# Before 1920, all ships kept local apparent time on the high seas by setting
# their clocks at night or at the morning sight so that, given the ship's
# speed and direction, it would be 12 o'clock when the Sun crossed the ship's
# meridian (12 o'clock = local apparent noon).  During 1917, at the
# Anglo-French Conference on Time-keeping at Sea, it was recommended that all
# ships, both military and civilian, should adopt hourly standard time zones
# on the high seas.  Whenever a ship was within the territorial waters of any
# nation it would use that nation's standard time.  The captain was permitted
# to change his ship's clocks at a time of his choice following his ship's
# entry into another zone time--he often chose midnight.  These zones were
# adopted by all major fleets between 1920 and 1925 but not by many
# independent merchant ships until World War II.

# From Paul Eggert, using references suggested by Oscar van Vlijmen
# (2005-03-20):
#
# The American Practical Navigator (2002)
# 
# talks only about the 180-degree meridian with respect to ships in
# international waters; it ignores the international date line.
joda-time-2.3/src/main/java/org/joda/time/tz/src/systemv0000644000175000017500000000301212137470245022537 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# Old rules, should the need arise.
# No attempt is made to handle Newfoundland, since it cannot be expressed
# using the System V "TZ" scheme (half-hour offset), or anything outside
# North America (no support for non-standard DST start/end dates), nor
# the changes in the DST rules in the US after 1976 (which occurred after
# the old rules were written).
#
# If you need the old rules, uncomment ## lines.
# Compile this *without* leap second correction for true conformance.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	SystemV	min	1973	-	Apr	lastSun	2:00	1:00	D
Rule	SystemV	min	1973	-	Oct	lastSun	2:00	0	S
Rule	SystemV	1974	only	-	Jan	6	2:00	1:00	D
Rule	SystemV	1974	only	-	Nov	lastSun	2:00	0	S
Rule	SystemV	1975	only	-	Feb	23	2:00	1:00	D
Rule	SystemV	1975	only	-	Oct	lastSun	2:00	0	S
Rule	SystemV	1976	max	-	Apr	lastSun	2:00	1:00	D
Rule	SystemV	1976	max	-	Oct	lastSun	2:00	0	S

# Zone	NAME		GMTOFF	RULES/SAVE	FORMAT	[UNTIL]
## Zone	SystemV/AST4ADT	-4:00	SystemV		A%sT
## Zone	SystemV/EST5EDT	-5:00	SystemV		E%sT
## Zone	SystemV/CST6CDT	-6:00	SystemV		C%sT
## Zone	SystemV/MST7MDT	-7:00	SystemV		M%sT
## Zone	SystemV/PST8PDT	-8:00	SystemV		P%sT
## Zone	SystemV/YST9YDT	-9:00	SystemV		Y%sT
## Zone	SystemV/AST4	-4:00	-		AST
## Zone	SystemV/EST5	-5:00	-		EST
## Zone	SystemV/CST6	-6:00	-		CST
## Zone	SystemV/MST7	-7:00	-		MST
## Zone	SystemV/PST8	-8:00	-		PST
## Zone	SystemV/YST9	-9:00	-		YST
## Zone	SystemV/HST10	-10:00	-		HST
joda-time-2.3/src/main/java/org/joda/time/tz/src/backward0000644000175000017500000000776312137470245022624 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# This file provides links between current names for time zones
# and their old names.  Many names changed in late 1993.

Link	Africa/Asmara		Africa/Asmera
Link	Africa/Bamako		Africa/Timbuktu
Link	America/Argentina/Catamarca	America/Argentina/ComodRivadavia
Link	America/Adak		America/Atka
Link	America/Argentina/Buenos_Aires	America/Buenos_Aires
Link	America/Argentina/Catamarca	America/Catamarca
Link	America/Atikokan	America/Coral_Harbour
Link	America/Argentina/Cordoba	America/Cordoba
Link	America/Tijuana		America/Ensenada
Link	America/Indiana/Indianapolis	America/Fort_Wayne
Link	America/Indiana/Indianapolis	America/Indianapolis
Link	America/Argentina/Jujuy	America/Jujuy
Link	America/Indiana/Knox	America/Knox_IN
Link	America/Kentucky/Louisville	America/Louisville
Link	America/Argentina/Mendoza	America/Mendoza
Link	America/Rio_Branco	America/Porto_Acre
Link	America/Argentina/Cordoba	America/Rosario
Link	America/St_Thomas	America/Virgin
Link	Asia/Ashgabat		Asia/Ashkhabad
Link	Asia/Chongqing		Asia/Chungking
Link	Asia/Dhaka		Asia/Dacca
Link	Asia/Kathmandu		Asia/Katmandu
Link	Asia/Kolkata		Asia/Calcutta
Link	Asia/Macau		Asia/Macao
Link	Asia/Jerusalem		Asia/Tel_Aviv
Link	Asia/Ho_Chi_Minh	Asia/Saigon
Link	Asia/Thimphu		Asia/Thimbu
Link	Asia/Makassar		Asia/Ujung_Pandang
Link	Asia/Ulaanbaatar	Asia/Ulan_Bator
Link	Atlantic/Faroe		Atlantic/Faeroe
Link	Europe/Oslo		Atlantic/Jan_Mayen
Link	Australia/Sydney	Australia/ACT
Link	Australia/Sydney	Australia/Canberra
Link	Australia/Lord_Howe	Australia/LHI
Link	Australia/Sydney	Australia/NSW
Link	Australia/Darwin	Australia/North
Link	Australia/Brisbane	Australia/Queensland
Link	Australia/Adelaide	Australia/South
Link	Australia/Hobart	Australia/Tasmania
Link	Australia/Melbourne	Australia/Victoria
Link	Australia/Perth		Australia/West
Link	Australia/Broken_Hill	Australia/Yancowinna
Link	America/Rio_Branco	Brazil/Acre
Link	America/Noronha		Brazil/DeNoronha
Link	America/Sao_Paulo	Brazil/East
Link	America/Manaus		Brazil/West
Link	America/Halifax		Canada/Atlantic
Link	America/Winnipeg	Canada/Central
Link	America/Regina		Canada/East-Saskatchewan
Link	America/Toronto		Canada/Eastern
Link	America/Edmonton	Canada/Mountain
Link	America/St_Johns	Canada/Newfoundland
Link	America/Vancouver	Canada/Pacific
Link	America/Regina		Canada/Saskatchewan
Link	America/Whitehorse	Canada/Yukon
Link	America/Santiago	Chile/Continental
Link	Pacific/Easter		Chile/EasterIsland
Link	America/Havana		Cuba
Link	Africa/Cairo		Egypt
Link	Europe/Dublin		Eire
Link	Europe/London		Europe/Belfast
Link	Europe/Chisinau		Europe/Tiraspol
Link	Europe/London		GB
Link	Europe/London		GB-Eire
Link	Etc/GMT			GMT+0
Link	Etc/GMT			GMT-0
Link	Etc/GMT			GMT0
Link	Etc/GMT			Greenwich
Link	Asia/Hong_Kong		Hongkong
Link	Atlantic/Reykjavik	Iceland
Link	Asia/Tehran		Iran
Link	Asia/Jerusalem		Israel
Link	America/Jamaica		Jamaica
Link	Asia/Tokyo		Japan
Link	Pacific/Kwajalein	Kwajalein
Link	Africa/Tripoli		Libya
Link	America/Tijuana		Mexico/BajaNorte
Link	America/Mazatlan	Mexico/BajaSur
Link	America/Mexico_City	Mexico/General
Link	Pacific/Auckland	NZ
Link	Pacific/Chatham		NZ-CHAT
Link	America/Denver		Navajo
Link	Asia/Shanghai		PRC
Link	Pacific/Pago_Pago	Pacific/Samoa
Link	Pacific/Chuuk		Pacific/Yap
Link	Pacific/Chuuk		Pacific/Truk
Link	Pacific/Pohnpei		Pacific/Ponape
Link	Europe/Warsaw		Poland
Link	Europe/Lisbon		Portugal
Link	Asia/Taipei		ROC
Link	Asia/Seoul		ROK
Link	Asia/Singapore		Singapore
Link	Europe/Istanbul		Turkey
Link	Etc/UCT			UCT
Link	America/Anchorage	US/Alaska
Link	America/Adak		US/Aleutian
Link	America/Phoenix		US/Arizona
Link	America/Chicago		US/Central
Link	America/Indiana/Indianapolis	US/East-Indiana
Link	America/New_York	US/Eastern
Link	Pacific/Honolulu	US/Hawaii
Link	America/Indiana/Knox	US/Indiana-Starke
Link	America/Detroit		US/Michigan
Link	America/Denver		US/Mountain
Link	America/Los_Angeles	US/Pacific
Link	Pacific/Pago_Pago	US/Samoa
Link	Etc/UTC			UTC
Link	Etc/UTC			Universal
Link	Europe/Moscow		W-SU
Link	Etc/UTC			Zulu
joda-time-2.3/src/main/java/org/joda/time/tz/src/northamerica0000644000175000017500000041274112137470246023517 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# also includes Central America and the Caribbean

# This data is by no means authoritative; if you think you know better,
# go ahead and edit the file (and please send any changes to
# tz@iana.org for general use in the future).

# From Paul Eggert (1999-03-22):
# A reliable and entertaining source about time zones is
# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997).

###############################################################################

# United States

# From Paul Eggert (1999-03-31):
# Howse writes (pp 121-125) that time zones were invented by
# Professor Charles Ferdinand Dowd (1825-1904),
# Principal of Temple Grove Ladies' Seminary (Saratoga Springs, NY).
# His pamphlet ``A System of National Time for Railroads'' (1870)
# was the result of his proposals at the Convention of Railroad Trunk Lines
# in New York City (1869-10).  His 1870 proposal was based on Washington, DC,
# but in 1872-05 he moved the proposed origin to Greenwich.
# His proposal was adopted by the railroads on 1883-11-18 at 12:00,
# and the most of the country soon followed suit.

# From Paul Eggert (2005-04-16):
# That 1883 transition occurred at 12:00 new time, not at 12:00 old time.
# See p 46 of David Prerau, Seize the daylight, Thunder's Mouth Press (2005).

# From Paul Eggert (2006-03-22):
# A good source for time zone historical data in the US is
# Thomas G. Shanks, The American Atlas (5th edition),
# San Diego: ACS Publications, Inc. (1991).
# Make sure you have the errata sheet; the book is somewhat useless without it.
# It is the source for most of the pre-1991 US entries below.

# From Paul Eggert (2001-03-06):
# Daylight Saving Time was first suggested as a joke by Benjamin Franklin
# in his whimsical essay ``An Economical Project for Diminishing the Cost
# of Light'' published in the Journal de Paris (1784-04-26).
# Not everyone is happy with the results:
#
#	I don't really care how time is reckoned so long as there is some
#	agreement about it, but I object to being told that I am saving
#	daylight when my reason tells me that I am doing nothing of the kind.
#	I even object to the implication that I am wasting something
#	valuable if I stay in bed after the sun has risen.  As an admirer
#	of moonlight I resent the bossy insistence of those who want to
#	reduce my time for enjoying it.  At the back of the Daylight Saving
#	scheme I detect the bony, blue-fingered hand of Puritanism, eager
#	to push people into bed earlier, and get them up earlier, to make
#	them healthy, wealthy and wise in spite of themselves.
#
#	-- Robertson Davies, The diary of Samuel Marchbanks,
#	   Clarke, Irwin (1947), XIX, Sunday
#
# For more about the first ten years of DST in the United States, see
# Robert Garland's 
# Ten years of daylight saving from the Pittsburgh standpoint
# (Carnegie Library of Pittsburgh, 1927).
#
# Shanks says that DST was called "War Time" in the US in 1918 and 1919.
# However, DST was imposed by the Standard Time Act of 1918, which
# was the first nationwide legal time standard, and apparently
# time was just called "Standard Time" or "Daylight Saving Time".

# From Arthur David Olson:
# US Daylight Saving Time ended on the last Sunday of *October* in 1974.
# See, for example, the front page of the Saturday, 1974-10-26
# and Sunday, 1974-10-27 editions of the Washington Post.

# From Arthur David Olson:
# Before the Uniform Time Act of 1966 took effect in 1967, observance of
# Daylight Saving Time in the US was by local option, except during wartime.

# From Arthur David Olson (2000-09-25):
# Last night I heard part of a rebroadcast of a 1945 Arch Oboler radio drama.
# In the introduction, Oboler spoke of "Eastern Peace Time."
# An AltaVista search turned up
# :
# "When the time is announced over the radio now, it is 'Eastern Peace
# Time' instead of the old familiar 'Eastern War Time.'  Peace is wonderful."
#  (August 1945) by way of confirmation.

# From Joseph Gallant citing
# George H. Douglas, _The Early Days of Radio Broadcasting_ (1987):
# At 7 P.M. (Eastern War Time) [on 1945-08-14], the networks were set
# to switch to London for Attlee's address, but the American people
# never got to hear his speech live. According to one press account,
# CBS' Bob Trout was first to announce the word of Japan's surrender,
# but a few seconds later, NBC, ABC and Mutual also flashed the word
# of surrender, all of whom interrupting the bells of Big Ben in
# London which were to precede Mr. Attlee's speech.

# From Paul Eggert (2003-02-09): It was Robert St John, not Bob Trout.  From
# Myrna Oliver's obituary of St John on page B16 of today's Los Angeles Times:
#
# ... a war-weary U.S. clung to radios, awaiting word of Japan's surrender.
# Any announcement from Asia would reach St. John's New York newsroom on a
# wire service teletype machine, which had prescribed signals for major news.
# Associated Press, for example, would ring five bells before spewing out
# typed copy of an important story, and 10 bells for news "of transcendental
# importance."
#
# On Aug. 14, stalling while talking steadily into the NBC networks' open
# microphone, St. John heard five bells and waited only to hear a sixth bell,
# before announcing confidently: "Ladies and gentlemen, World War II is over.
# The Japanese have agreed to our surrender terms."
#
# He had scored a 20-second scoop on other broadcasters.

# From Arthur David Olson (2005-08-22):
# Paul has been careful to use the "US" rules only in those locations
# that are part of the United States; this reflects the real scope of
# U.S. government action.  So even though the "US" rules have changed
# in the latest release, other countries won't be affected.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	US	1918	1919	-	Mar	lastSun	2:00	1:00	D
Rule	US	1918	1919	-	Oct	lastSun	2:00	0	S
Rule	US	1942	only	-	Feb	9	2:00	1:00	W # War
Rule	US	1945	only	-	Aug	14	23:00u	1:00	P # Peace
Rule	US	1945	only	-	Sep	30	2:00	0	S
Rule	US	1967	2006	-	Oct	lastSun	2:00	0	S
Rule	US	1967	1973	-	Apr	lastSun	2:00	1:00	D
Rule	US	1974	only	-	Jan	6	2:00	1:00	D
Rule	US	1975	only	-	Feb	23	2:00	1:00	D
Rule	US	1976	1986	-	Apr	lastSun	2:00	1:00	D
Rule	US	1987	2006	-	Apr	Sun>=1	2:00	1:00	D
Rule	US	2007	max	-	Mar	Sun>=8	2:00	1:00	D
Rule	US	2007	max	-	Nov	Sun>=1	2:00	0	S

# From Arthur David Olson, 2005-12-19
# We generate the files specified below to guard against old files with
# obsolete information being left in the time zone binary directory.
# We limit the list to names that have appeared in previous versions of
# this time zone package.
# We do these as separate Zones rather than as Links to avoid problems if
# a particular place changes whether it observes DST.
# We put these specifications here in the northamerica file both to
# increase the chances that they'll actually get compiled and to
# avoid the need to duplicate the US rules in another file.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	EST		 -5:00	-	EST
Zone	MST		 -7:00	-	MST
Zone	HST		-10:00	-	HST
Zone	EST5EDT		 -5:00	US	E%sT
Zone	CST6CDT		 -6:00	US	C%sT
Zone	MST7MDT		 -7:00	US	M%sT
Zone	PST8PDT		 -8:00	US	P%sT

# From Bob Devine (1988-01-28):
# ...Alaska (and Hawaii) had the timezone names changed in 1967.
#    old			 new
#    Pacific Standard Time(PST)  -same-
#    Yukon Standard Time(YST)    -same-
#    Central Alaska S.T. (CAT)   Alaska-Hawaii St[an]dard Time (AHST)
#    Nome Standard Time (NT)     Bering Standard Time (BST)
#
# ...Alaska's timezone lines were redrawn in 1983 to give only 2 tz.
#    The YST zone now covers nearly all of the state, AHST just part
#    of the Aleutian islands.   No DST.

# From Paul Eggert (1995-12-19):
# The tables below use `NST', not `NT', for Nome Standard Time.
# I invented `CAWT' for Central Alaska War Time.

# From U. S. Naval Observatory (1989-01-19):
# USA  EASTERN       5 H  BEHIND UTC    NEW YORK, WASHINGTON
# USA  EASTERN       4 H  BEHIND UTC    APR 3 - OCT 30
# USA  CENTRAL       6 H  BEHIND UTC    CHICAGO, HOUSTON
# USA  CENTRAL       5 H  BEHIND UTC    APR 3 - OCT 30
# USA  MOUNTAIN      7 H  BEHIND UTC    DENVER
# USA  MOUNTAIN      6 H  BEHIND UTC    APR 3 - OCT 30
# USA  PACIFIC       8 H  BEHIND UTC    L.A., SAN FRANCISCO
# USA  PACIFIC       7 H  BEHIND UTC    APR 3 - OCT 30
# USA  ALASKA STD    9 H  BEHIND UTC    MOST OF ALASKA     (AKST)
# USA  ALASKA STD    8 H  BEHIND UTC    APR 3 - OCT 30 (AKDT)
# USA  ALEUTIAN     10 H  BEHIND UTC    ISLANDS WEST OF 170W
# USA  - " -         9 H  BEHIND UTC    APR 3 - OCT 30
# USA  HAWAII       10 H  BEHIND UTC
# USA  BERING       11 H  BEHIND UTC    SAMOA, MIDWAY

# From Arthur David Olson (1989-01-21):
# The above dates are for 1988.
# Note the "AKST" and "AKDT" abbreviations, the claim that there's
# no DST in Samoa, and the claim that there is DST in Alaska and the
# Aleutians.

# From Arthur David Olson (1988-02-13):
# Legal standard time zone names, from United States Code (1982 Edition and
# Supplement III), Title 15, Chapter 6, Section 260 and forward.  First, names
# up to 1967-04-01 (when most provisions of the Uniform Time Act of 1966
# took effect), as explained in sections 263 and 261:
#	(none)
#	United States standard eastern time
#	United States standard mountain time
#	United States standard central time
#	United States standard Pacific time
#	(none)
#	United States standard Alaska time
#	(none)
# Next, names from 1967-04-01 until 1983-11-30 (the date for
# public law 98-181):
#	Atlantic standard time
#	eastern standard time
#	central standard time
#	mountain standard time
#	Pacific standard time
#	Yukon standard time
#	Alaska-Hawaii standard time
#	Bering standard time
# And after 1983-11-30:
#	Atlantic standard time
#	eastern standard time
#	central standard time
#	mountain standard time
#	Pacific standard time
#	Alaska standard time
#	Hawaii-Aleutian standard time
#	Samoa standard time
# The law doesn't give abbreviations.
#
# From Paul Eggert (2000-01-08), following a heads-up from Rives McDow:
# Public law 106-564 (2000-12-23) introduced the abbreviation
# "Chamorro Standard Time" for time in Guam and the Northern Marianas.
# See the file "australasia".

# From Arthur David Olson, 2005-08-09
# The following was signed into law on 2005-08-08.
#
# H.R. 6, Energy Policy Act of 2005, SEC. 110. DAYLIGHT SAVINGS.
#   (a) Amendment- Section 3(a) of the Uniform Time Act of 1966 (15
#   U.S.C. 260a(a)) is amended--
#     (1) by striking `first Sunday of April' and inserting `second
#     Sunday of March'; and
#     (2) by striking `last Sunday of October' and inserting `first
#     Sunday of November'.
#   (b) Effective Date- Subsection (a) shall take effect 1 year after the
#   date of enactment of this Act or March 1, 2007, whichever is later.
#   (c) Report to Congress- Not later than 9 months after the effective
#   date stated in subsection (b), the Secretary shall report to Congress
#   on the impact of this section on energy consumption in the United
#   States.
#   (d) Right to Revert- Congress retains the right to revert the
#   Daylight Saving Time back to the 2005 time schedules once the
#   Department study is complete.

# US eastern time, represented by New York

# Connecticut, Delaware, District of Columbia, most of Florida,
# Georgia, southeast Indiana (Dearborn and Ohio counties), eastern Kentucky
# (except America/Kentucky/Louisville below), Maine, Maryland, Massachusetts,
# New Hampshire, New Jersey, New York, North Carolina, Ohio,
# Pennsylvania, Rhode Island, South Carolina, eastern Tennessee,
# Vermont, Virginia, West Virginia

# From Dave Cantor (2004-11-02):
# Early this summer I had the occasion to visit the Mount Washington
# Observatory weather station atop (of course!) Mount Washington [, NH]....
# One of the staff members said that the station was on Eastern Standard Time
# and didn't change their clocks for Daylight Saving ... so that their
# reports will always have times which are 5 hours behind UTC.

# From Paul Eggert (2005-08-26):
# According to today's Huntsville Times
# 
# a few towns on Alabama's "eastern border with Georgia, such as Phenix City
# in Russell County, Lanett in Chambers County and some towns in Lee County,
# set their watches and clocks on Eastern time."  It quotes H.H. "Bubba"
# Roberts, city administrator in Phenix City. as saying "We are in the Central
# time zone, but we do go by the Eastern time zone because so many people work
# in Columbus."

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	NYC	1920	only	-	Mar	lastSun	2:00	1:00	D
Rule	NYC	1920	only	-	Oct	lastSun	2:00	0	S
Rule	NYC	1921	1966	-	Apr	lastSun	2:00	1:00	D
Rule	NYC	1921	1954	-	Sep	lastSun	2:00	0	S
Rule	NYC	1955	1966	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/New_York	-4:56:02 -	LMT	1883 Nov 18 12:03:58
			-5:00	US	E%sT	1920
			-5:00	NYC	E%sT	1942
			-5:00	US	E%sT	1946
			-5:00	NYC	E%sT	1967
			-5:00	US	E%sT

# US central time, represented by Chicago

# Alabama, Arkansas, Florida panhandle (Bay, Calhoun, Escambia,
# Gulf, Holmes, Jackson, Okaloosa, Santa Rosa, Walton, and
# Washington counties), Illinois, western Indiana
# (Gibson, Jasper, Lake, LaPorte, Newton, Porter, Posey, Spencer,
# Vanderburgh, and Warrick counties), Iowa, most of Kansas, western
# Kentucky, Louisiana, Minnesota, Mississippi, Missouri, eastern
# Nebraska, eastern North Dakota, Oklahoma, eastern South Dakota,
# western Tennessee, most of Texas, Wisconsin

# From Larry M. Smith (2006-04-26) re Wisconsin:
# http://www.legis.state.wi.us/statutes/Stat0175.pdf ...
# is currently enforced at the 01:00 time of change.  Because the local
# "bar time" in the state corresponds to 02:00, a number of citations
# are issued for the "sale of class 'B' alcohol after prohibited
# hours" within the deviated hour of this change every year....
#
# From Douglas R. Bomberg (2007-03-12):
# Wisconsin has enacted (nearly eleventh-hour) legislation to get WI
# Statue 175 closer in synch with the US Congress' intent....
# http://www.legis.state.wi.us/2007/data/acts/07Act3.pdf

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	Chicago	1920	only	-	Jun	13	2:00	1:00	D
Rule	Chicago	1920	1921	-	Oct	lastSun	2:00	0	S
Rule	Chicago	1921	only	-	Mar	lastSun	2:00	1:00	D
Rule	Chicago	1922	1966	-	Apr	lastSun	2:00	1:00	D
Rule	Chicago	1922	1954	-	Sep	lastSun	2:00	0	S
Rule	Chicago	1955	1966	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Chicago	-5:50:36 -	LMT	1883 Nov 18 12:09:24
			-6:00	US	C%sT	1920
			-6:00	Chicago	C%sT	1936 Mar  1 2:00
			-5:00	-	EST	1936 Nov 15 2:00
			-6:00	Chicago	C%sT	1942
			-6:00	US	C%sT	1946
			-6:00	Chicago	C%sT	1967
			-6:00	US	C%sT
# Oliver County, ND switched from mountain to central time on 1992-10-25.
Zone America/North_Dakota/Center -6:45:12 - LMT	1883 Nov 18 12:14:48
			-7:00	US	M%sT	1992 Oct 25 02:00
			-6:00	US	C%sT
# Morton County, ND, switched from mountain to central time on
# 2003-10-26, except for the area around Mandan which was already central time.
# See .
# Officially this switch also included part of Sioux County, and
# Jones, Mellette, and Todd Counties in South Dakota;
# but in practice these other counties were already observing central time.
# See .
Zone America/North_Dakota/New_Salem -6:45:39 - LMT 1883 Nov 18 12:14:21
			-7:00	US	M%sT	2003 Oct 26 02:00
			-6:00	US	C%sT

# From Josh Findley (2011-01-21):
# ...it appears that Mercer County, North Dakota, changed from the
# mountain time zone to the central time zone at the last transition from
# daylight-saving to standard time (on Nov. 7, 2010):
# 
# http://www.gpo.gov/fdsys/pkg/FR-2010-09-29/html/2010-24376.htm
# 
# 
# http://www.bismarcktribune.com/news/local/article_1eb1b588-c758-11df-b472-001cc4c03286.html
# 

# From Andy Lipscomb (2011-01-24):
# ...according to the Census Bureau, the largest city is Beulah (although
# it's commonly referred to as Beulah-Hazen, with Hazen being the next
# largest city in Mercer County).  Google Maps places Beulah's city hall
# at 4715'51" north, 10146'40" west, which yields an offset of 6h47'07".

Zone America/North_Dakota/Beulah -6:47:07 - LMT 1883 Nov 18 12:12:53
			-7:00	US	M%sT	2010 Nov  7 2:00
			-6:00	US	C%sT

# US mountain time, represented by Denver
#
# Colorado, far western Kansas, Montana, western
# Nebraska, Nevada border (Jackpot, Owyhee, and Mountain City),
# New Mexico, southwestern North Dakota,
# western South Dakota, far western Texas (El Paso County, Hudspeth County,
# and Pine Springs and Nickel Creek in Culberson County), Utah, Wyoming
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	Denver	1920	1921	-	Mar	lastSun	2:00	1:00	D
Rule	Denver	1920	only	-	Oct	lastSun	2:00	0	S
Rule	Denver	1921	only	-	May	22	2:00	0	S
Rule	Denver	1965	1966	-	Apr	lastSun	2:00	1:00	D
Rule	Denver	1965	1966	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Denver	-6:59:56 -	LMT	1883 Nov 18 12:00:04
			-7:00	US	M%sT	1920
			-7:00	Denver	M%sT	1942
			-7:00	US	M%sT	1946
			-7:00	Denver	M%sT	1967
			-7:00	US	M%sT

# US Pacific time, represented by Los Angeles
#
# California, northern Idaho (Benewah, Bonner, Boundary, Clearwater,
# Idaho, Kootenai, Latah, Lewis, Nez Perce, and Shoshone counties,
# and the northern three-quarters of Idaho county),
# most of Nevada, most of Oregon, and Washington
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	CA	1948	only	-	Mar	14	2:00	1:00	D
Rule	CA	1949	only	-	Jan	 1	2:00	0	S
Rule	CA	1950	1966	-	Apr	lastSun	2:00	1:00	D
Rule	CA	1950	1961	-	Sep	lastSun	2:00	0	S
Rule	CA	1962	1966	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Los_Angeles -7:52:58 -	LMT	1883 Nov 18 12:07:02
			-8:00	US	P%sT	1946
			-8:00	CA	P%sT	1967
			-8:00	US	P%sT

# Alaska
# AK%sT is the modern abbreviation for -9:00 per USNO.
#
# From Paul Eggert (2001-05-30):
# Howse writes that Alaska switched from the Julian to the Gregorian calendar,
# and from east-of-GMT to west-of-GMT days, when the US bought it from Russia.
# This was on 1867-10-18, a Friday; the previous day was 1867-10-06 Julian,
# also a Friday.  Include only the time zone part of this transition,
# ignoring the switch from Julian to Gregorian, since we can't represent
# the Julian calendar.
#
# As far as we know, none of the exact locations mentioned below were
# permanently inhabited in 1867 by anyone using either calendar.
# (Yakutat was colonized by the Russians in 1799, but the settlement
# was destroyed in 1805 by a Yakutat-kon war party.)  However, there
# were nearby inhabitants in some cases and for our purposes perhaps
# it's best to simply use the official transition.
#

# From Steve Ferguson (2011-01-31):
# The author lives in Alaska and many of the references listed are only
# available to Alaskan residents.
#
# 
# http://www.alaskahistoricalsociety.org/index.cfm?section=discover%20alaska&page=Glimpses%20of%20the%20Past&viewpost=2&ContentId=98
# 

# From Arthur David Olson (2011-02-01):
# Here's database-relevant material from the 2001 "Alaska History" article:
#
# On September 20 [1979]...DOT...officials decreed that on April 27,
# 1980, Juneau and other nearby communities would move to Yukon Time.
# Sitka, Petersburg, Wrangell, and Ketchikan, however, would remain on
# Pacific Time.
#
# ...on September 22, 1980, DOT Secretary Neil E. Goldschmidt rescinded the
# Department's September 1979 decision. Juneau and other communities in
# northern Southeast reverted to Pacific Time on October 26.
#
# On October 28 [1983]...the Metlakatla Indian Community Council voted
# unanimously to keep the reservation on Pacific Time.
#
# According to DOT official Joanne Petrie, Indian reservations are not
# bound to follow time zones imposed by neighboring jurisdictions.
#
# (The last is consistent with how the database now handles the Navajo
# Nation.)

# From Arthur David Olson (2011-02-09):
# I just spoke by phone with a staff member at the Metlakatla Indian
# Community office (using contact information available at
# 
# http://www.commerce.state.ak.us/dca/commdb/CIS.cfm?Comm_Boro_name=Metlakatla
# ).
# It's shortly after 1:00 here on the east coast of the United States;
# the staffer said it was shortly after 10:00 there. When I asked whether
# that meant they were on Pacific time, they said no--they were on their
# own time. I asked about daylight saving; they said it wasn't used. I
# did not inquire about practices in the past.

# From Arthur David Olson (2011-08-17):
# For lack of better information, assume that Metlakatla's
# abandonment of use of daylight saving resulted from the 1983 vote.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Juneau	 15:02:19 -	LMT	1867 Oct 18
			 -8:57:41 -	LMT	1900 Aug 20 12:00
			 -8:00	-	PST	1942
			 -8:00	US	P%sT	1946
			 -8:00	-	PST	1969
			 -8:00	US	P%sT	1980 Apr 27 2:00
			 -9:00	US	Y%sT	1980 Oct 26 2:00
			 -8:00	US	P%sT	1983 Oct 30 2:00
			 -9:00	US	Y%sT	1983 Nov 30
			 -9:00	US	AK%sT
Zone America/Sitka	 14:58:47 -	LMT	1867 Oct 18
			 -9:01:13 -	LMT	1900 Aug 20 12:00
			 -8:00	-	PST	1942
			 -8:00	US	P%sT	1946
			 -8:00	-	PST	1969
			 -8:00	US	P%sT	1983 Oct 30 2:00
			 -9:00	US	Y%sT	1983 Nov 30
			 -9:00	US	AK%sT
Zone America/Metlakatla	 15:13:42 -	LMT	1867 Oct 18
			 -8:46:18 -	LMT	1900 Aug 20 12:00
			 -8:00	-	PST	1942
			 -8:00	US	P%sT	1946
			 -8:00	-	PST	1969
			 -8:00	US	P%sT	1983 Oct 30 2:00
			 -8:00	-	MeST
Zone America/Yakutat	 14:41:05 -	LMT	1867 Oct 18
			 -9:18:55 -	LMT	1900 Aug 20 12:00
			 -9:00	-	YST	1942
			 -9:00	US	Y%sT	1946
			 -9:00	-	YST	1969
			 -9:00	US	Y%sT	1983 Nov 30
			 -9:00	US	AK%sT
Zone America/Anchorage	 14:00:24 -	LMT	1867 Oct 18
			 -9:59:36 -	LMT	1900 Aug 20 12:00
			-10:00	-	CAT	1942
			-10:00	US	CAT/CAWT 1945 Aug 14 23:00u
			-10:00	US	CAT/CAPT 1946 # Peace
			-10:00	-	CAT	1967 Apr
			-10:00	-	AHST	1969
			-10:00	US	AH%sT	1983 Oct 30 2:00
			 -9:00	US	Y%sT	1983 Nov 30
			 -9:00	US	AK%sT
Zone America/Nome	 12:58:21 -	LMT	1867 Oct 18
			-11:01:38 -	LMT	1900 Aug 20 12:00
			-11:00	-	NST	1942
			-11:00	US	N%sT	1946
			-11:00	-	NST	1967 Apr
			-11:00	-	BST	1969
			-11:00	US	B%sT	1983 Oct 30 2:00
			 -9:00	US	Y%sT	1983 Nov 30
			 -9:00	US	AK%sT
Zone America/Adak	 12:13:21 -	LMT	1867 Oct 18
			-11:46:38 -	LMT	1900 Aug 20 12:00
			-11:00	-	NST	1942
			-11:00	US	N%sT	1946
			-11:00	-	NST	1967 Apr
			-11:00	-	BST	1969
			-11:00	US	B%sT	1983 Oct 30 2:00
			-10:00	US	AH%sT	1983 Nov 30
			-10:00	US	HA%sT
# The following switches don't quite make our 1970 cutoff.
#
# Shanks writes that part of southwest Alaska (e.g. Aniak)
# switched from -11:00 to -10:00 on 1968-09-22 at 02:00,
# and another part (e.g. Akiak) made the same switch five weeks later.
#
# From David Flater (2004-11-09):
# In e-mail, 2004-11-02, Ray Hudson, historian/liaison to the Unalaska
# Historic Preservation Commission, provided this information, which
# suggests that Unalaska deviated from statutory time from early 1967
# possibly until 1983:
#
#  Minutes of the Unalaska City Council Meeting, January 10, 1967:
#  "Except for St. Paul and Akutan, Unalaska is the only important
#  location not on Alaska Standard Time.  The following resolution was
#  made by William Robinson and seconded by Henry Swanson:  Be it
#  resolved that the City of Unalaska hereby goes to Alaska Standard
#  Time as of midnight Friday, January 13, 1967 (1 A.M. Saturday,
#  January 14, Alaska Standard Time.)  This resolution was passed with
#  three votes for and one against."

# Hawaii

# From Arthur David Olson (2010-12-09):
# "Hawaiian Time" by Robert C. Schmitt and Doak C. Cox appears on pages 207-225
# of volume 26 of The Hawaiian Journal of History (1992). As of 2010-12-09,
# the article is available at
# 
# http://evols.library.manoa.hawaii.edu/bitstream/10524/239/2/JL26215.pdf
# 
# and indicates that standard time was adopted effective noon, January
# 13, 1896 (page 218), that in "1933, the Legislature decreed daylight
# saving for the period between the last Sunday of each April and the
# last Sunday of each September, but less than a month later repealed the
# act," (page 220), that year-round daylight saving time was in effect
# from 1942-02-09 to 1945-09-30 (page 221, with no time of day given for
# when clocks changed) and that clocks were changed by 30 minutes
# effective the second Sunday of June, 1947 (page 219, with no time of
# day given for when clocks changed). A footnote for the 1933 changes
# cites Session Laws of Hawaii 1933, "Act. 90 (approved 26 Apr. 1933)
# and Act 163 (approved 21 May 1933)."

# From Arthur David Olson (2011-01-19):
# The following is from "Laws of the Territory of Hawaii Passed by the
# Seventeenth Legislature: Regular Session 1933," available (as of
# 2011-01-19) at American University's Pence Law Library. Page 85: "Act
# 90...At 2 o'clock ante meridian of the last Sunday in April of each
# year, the standard time of this Territory shall be advanced one
# hour...This Act shall take effect upon its approval. Approved this 26th
# day of April, A. D. 1933. LAWRENCE M JUDD, Governor of the Territory of
# Hawaii." Page 172:  "Act 163...Act 90 of the Session Laws of 1933 is
# hereby repealed...This Act shall take effect upon its approval, upon
# which date the standard time of this Territory shall be restored to
# that existing immediately prior to the taking effect of said Act 90.
# Approved this 21st day of May, A. D. 1933. LAWRENCE M. JUDD, Governor
# of the Territory of Hawaii."
#
# Note that 1933-05-21 was a Sunday.
# We're left to guess the time of day when Act 163 was approved; guess noon.

Zone Pacific/Honolulu	-10:31:26 -	LMT	1896 Jan 13 12:00 #Schmitt&Cox
			-10:30	-	HST	1933 Apr 30 2:00 #Laws 1933
			-10:30	1:00	HDT	1933 May 21 12:00 #Laws 1933+12
			-10:30	-	HST	1942 Feb 09 2:00 #Schmitt&Cox+2
			-10:30	1:00	HDT	1945 Sep 30 2:00 #Schmitt&Cox+2
			-10:30	-	HST	1947 Jun  8 2:00 #Schmitt&Cox+2
			-10:00	-	HST

# Now we turn to US areas that have diverged from the consensus since 1970.

# Arizona mostly uses MST.

# From Paul Eggert (2002-10-20):
#
# The information in the rest of this paragraph is derived from the
# 
# Daylight Saving Time web page (2002-01-23) maintained by the
# Arizona State Library, Archives and Public Records.
# Between 1944-01-01 and 1944-04-01 the State of Arizona used standard
# time, but by federal law railroads, airlines, bus lines, military
# personnel, and some engaged in interstate commerce continued to
# observe war (i.e., daylight saving) time.  The 1944-03-17 Phoenix
# Gazette says that was the date the law changed, and that 04-01 was
# the date the state's clocks would change.  In 1945 the State of
# Arizona used standard time all year, again with exceptions only as
# mandated by federal law.  Arizona observed DST in 1967, but Arizona
# Laws 1968, ch. 183 (effective 1968-03-21) repealed DST.
#
# Shanks says the 1944 experiment came to an end on 1944-03-17.
# Go with the Arizona State Library instead.

Zone America/Phoenix	-7:28:18 -	LMT	1883 Nov 18 11:31:42
			-7:00	US	M%sT	1944 Jan  1 00:01
			-7:00	-	MST	1944 Apr  1 00:01
			-7:00	US	M%sT	1944 Oct  1 00:01
			-7:00	-	MST	1967
			-7:00	US	M%sT	1968 Mar 21
			-7:00	-	MST
# From Arthur David Olson (1988-02-13):
# A writer from the Inter Tribal Council of Arizona, Inc.,
# notes in private correspondence dated 1987-12-28 that "Presently, only the
# Navajo Nation participates in the Daylight Saving Time policy, due to its
# large size and location in three states."  (The "only" means that other
# tribal nations don't use DST.)

Link America/Denver America/Shiprock

# Southern Idaho (Ada, Adams, Bannock, Bear Lake, Bingham, Blaine,
# Boise, Bonneville, Butte, Camas, Canyon, Caribou, Cassia, Clark,
# Custer, Elmore, Franklin, Fremont, Gem, Gooding, Jefferson, Jerome,
# Lemhi, Lincoln, Madison, Minidoka, Oneida, Owyhee, Payette, Power,
# Teton, Twin Falls, Valley, Washington counties, and the southern
# quarter of Idaho county) and eastern Oregon (most of Malheur County)
# switched four weeks late in 1974.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Boise	-7:44:49 -	LMT	1883 Nov 18 12:15:11
			-8:00	US	P%sT	1923 May 13 2:00
			-7:00	US	M%sT	1974
			-7:00	-	MST	1974 Feb  3 2:00
			-7:00	US	M%sT

# Indiana
#
# For a map of Indiana's time zone regions, see:
# 
# What time is it in Indiana?
#  (2006-03-01)
#
# From Paul Eggert (2007-08-17):
# Since 1970, most of Indiana has been like America/Indiana/Indianapolis,
# with the following exceptions:
#
# - Gibson, Jasper, Lake, LaPorte, Newton, Porter, Posey, Spencer,
#   Vandenburgh, and Warrick counties have been like America/Chicago.
#
# - Dearborn and Ohio counties have been like America/New_York.
#
# - Clark, Floyd, and Harrison counties have been like
#   America/Kentucky/Louisville.
#
# - Crawford, Daviess, Dubois, Knox, Martin, Perry, Pike, Pulaski, Starke,
#   and Switzerland counties have their own time zone histories as noted below.
#
# Shanks partitioned Indiana into 345 regions, each with its own time history,
# and wrote ``Even newspaper reports present contradictory information.''
# Those Hoosiers!  Such a flighty and changeable people!
# Fortunately, most of the complexity occurred before our cutoff date of 1970.
#
# Other than Indianapolis, the Indiana place names are so nondescript
# that they would be ambiguous if we left them at the `America' level.
# So we reluctantly put them all in a subdirectory `America/Indiana'.

# From Paul Eggert (2005-08-16):
# http://www.mccsc.edu/time.html says that Indiana will use DST starting 2006.

# From Nathan Stratton Treadway (2006-03-30):
# http://www.dot.gov/affairs/dot0406.htm [3705 B]
# From Deborah Goldsmith (2006-01-18):
# http://dmses.dot.gov/docimages/pdf95/382329_web.pdf [2.9 MB]
# From Paul Eggert (2006-01-20):
# It says "DOT is relocating the time zone boundary in Indiana to move Starke,
# Pulaski, Knox, Daviess, Martin, Pike, Dubois, and Perry Counties from the
# Eastern Time Zone to the Central Time Zone.... The effective date of
# this rule is 2:OO a.m. EST Sunday, April 2, 2006, which is the
# changeover date from standard time to Daylight Saving Time."
# Strictly speaking, this means the affected counties will change their
# clocks twice that night, but this obviously is in error.  The intent
# is that 01:59:59 EST be followed by 02:00:00 CDT.

# From Gwillim Law (2007-02-10):
# The Associated Press has been reporting that Pulaski County, Indiana is
# going to switch from Central to Eastern Time on March 11, 2007....
# http://www.indystar.com/apps/pbcs.dll/article?AID=/20070207/LOCAL190108/702070524/0/LOCAL

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule Indianapolis 1941	only	-	Jun	22	2:00	1:00	D
Rule Indianapolis 1941	1954	-	Sep	lastSun	2:00	0	S
Rule Indianapolis 1946	1954	-	Apr	lastSun	2:00	1:00	D
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Indianapolis -5:44:38 - LMT 1883 Nov 18 12:15:22
			-6:00	US	C%sT	1920
			-6:00 Indianapolis C%sT	1942
			-6:00	US	C%sT	1946
			-6:00 Indianapolis C%sT	1955 Apr 24 2:00
			-5:00	-	EST	1957 Sep 29 2:00
			-6:00	-	CST	1958 Apr 27 2:00
			-5:00	-	EST	1969
			-5:00	US	E%sT	1971
			-5:00	-	EST	2006
			-5:00	US	E%sT
#
# Eastern Crawford County, Indiana, left its clocks alone in 1974,
# as well as from 1976 through 2005.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	Marengo	1951	only	-	Apr	lastSun	2:00	1:00	D
Rule	Marengo	1951	only	-	Sep	lastSun	2:00	0	S
Rule	Marengo	1954	1960	-	Apr	lastSun	2:00	1:00	D
Rule	Marengo	1954	1960	-	Sep	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Marengo -5:45:23 -	LMT	1883 Nov 18 12:14:37
			-6:00	US	C%sT	1951
			-6:00	Marengo	C%sT	1961 Apr 30 2:00
			-5:00	-	EST	1969
			-5:00	US	E%sT	1974 Jan  6 2:00
			-6:00	1:00	CDT	1974 Oct 27 2:00
			-5:00	US	E%sT	1976
			-5:00	-	EST	2006
			-5:00	US	E%sT
#
# Daviess, Dubois, Knox, and Martin Counties, Indiana,
# switched from eastern to central time in April 2006, then switched back
# in November 2007.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule Vincennes	1946	only	-	Apr	lastSun	2:00	1:00	D
Rule Vincennes	1946	only	-	Sep	lastSun	2:00	0	S
Rule Vincennes	1953	1954	-	Apr	lastSun	2:00	1:00	D
Rule Vincennes	1953	1959	-	Sep	lastSun	2:00	0	S
Rule Vincennes	1955	only	-	May	 1	0:00	1:00	D
Rule Vincennes	1956	1963	-	Apr	lastSun	2:00	1:00	D
Rule Vincennes	1960	only	-	Oct	lastSun	2:00	0	S
Rule Vincennes	1961	only	-	Sep	lastSun	2:00	0	S
Rule Vincennes	1962	1963	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Vincennes -5:50:07 - LMT	1883 Nov 18 12:09:53
			-6:00	US	C%sT	1946
			-6:00 Vincennes	C%sT	1964 Apr 26 2:00
			-5:00	-	EST	1969
			-5:00	US	E%sT	1971
			-5:00	-	EST	2006 Apr  2 2:00
			-6:00	US	C%sT	2007 Nov  4 2:00
			-5:00	US	E%sT
#
# Perry County, Indiana, switched from eastern to central time in April 2006.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule Perry	1946	only	-	Apr	lastSun	2:00	1:00	D
Rule Perry	1946	only	-	Sep	lastSun	2:00	0	S
Rule Perry	1953	1954	-	Apr	lastSun	2:00	1:00	D
Rule Perry	1953	1959	-	Sep	lastSun	2:00	0	S
Rule Perry	1955	only	-	May	 1	0:00	1:00	D
Rule Perry	1956	1963	-	Apr	lastSun	2:00	1:00	D
Rule Perry	1960	only	-	Oct	lastSun	2:00	0	S
Rule Perry	1961	only	-	Sep	lastSun	2:00	0	S
Rule Perry	1962	1963	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Tell_City -5:47:03 - LMT	1883 Nov 18 12:12:57
			-6:00	US	C%sT	1946
			-6:00 Perry	C%sT	1964 Apr 26 2:00
			-5:00	-	EST	1969
			-5:00	US	E%sT	1971
			-5:00	-	EST	2006 Apr  2 2:00
			-6:00	US	C%sT
#
# Pike County, Indiana moved from central to eastern time in 1977,
# then switched back in 2006, then switched back again in 2007.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	Pike	1955	only	-	May	 1	0:00	1:00	D
Rule	Pike	1955	1960	-	Sep	lastSun	2:00	0	S
Rule	Pike	1956	1964	-	Apr	lastSun	2:00	1:00	D
Rule	Pike	1961	1964	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Petersburg -5:49:07 - LMT	1883 Nov 18 12:10:53
			-6:00	US	C%sT	1955
			-6:00	Pike	C%sT	1965 Apr 25 2:00
			-5:00	-	EST	1966 Oct 30 2:00
			-6:00	US	C%sT	1977 Oct 30 2:00
			-5:00	-	EST	2006 Apr  2 2:00
			-6:00	US	C%sT	2007 Nov  4 2:00
			-5:00	US	E%sT
#
# Starke County, Indiana moved from central to eastern time in 1991,
# then switched back in 2006.
# From Arthur David Olson (1991-10-28):
# An article on page A3 of the Sunday, 1991-10-27 Washington Post
# notes that Starke County switched from Central time to Eastern time as of
# 1991-10-27.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	Starke	1947	1961	-	Apr	lastSun	2:00	1:00	D
Rule	Starke	1947	1954	-	Sep	lastSun	2:00	0	S
Rule	Starke	1955	1956	-	Oct	lastSun	2:00	0	S
Rule	Starke	1957	1958	-	Sep	lastSun	2:00	0	S
Rule	Starke	1959	1961	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Knox -5:46:30 -	LMT	1883 Nov 18 12:13:30
			-6:00	US	C%sT	1947
			-6:00	Starke	C%sT	1962 Apr 29 2:00
			-5:00	-	EST	1963 Oct 27 2:00
			-6:00	US	C%sT	1991 Oct 27 2:00
			-5:00	-	EST	2006 Apr  2 2:00
			-6:00	US	C%sT
#
# Pulaski County, Indiana, switched from eastern to central time in
# April 2006 and then switched back in March 2007.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	Pulaski	1946	1960	-	Apr	lastSun	2:00	1:00	D
Rule	Pulaski	1946	1954	-	Sep	lastSun	2:00	0	S
Rule	Pulaski	1955	1956	-	Oct	lastSun	2:00	0	S
Rule	Pulaski	1957	1960	-	Sep	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Winamac -5:46:25 - LMT	1883 Nov 18 12:13:35
			-6:00	US	C%sT	1946
			-6:00	Pulaski	C%sT	1961 Apr 30 2:00
			-5:00	-	EST	1969
			-5:00	US	E%sT	1971
			-5:00	-	EST	2006 Apr  2 2:00
			-6:00	US	C%sT	2007 Mar 11 2:00
			-5:00	US	E%sT
#
# Switzerland County, Indiana, did not observe DST from 1973 through 2005.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Indiana/Vevay -5:40:16 -	LMT	1883 Nov 18 12:19:44
			-6:00	US	C%sT	1954 Apr 25 2:00
			-5:00	-	EST	1969
			-5:00	US	E%sT	1973
			-5:00	-	EST	2006
			-5:00	US	E%sT

# Part of Kentucky left its clocks alone in 1974.
# This also includes Clark, Floyd, and Harrison counties in Indiana.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule Louisville	1921	only	-	May	1	2:00	1:00	D
Rule Louisville	1921	only	-	Sep	1	2:00	0	S
Rule Louisville	1941	1961	-	Apr	lastSun	2:00	1:00	D
Rule Louisville	1941	only	-	Sep	lastSun	2:00	0	S
Rule Louisville	1946	only	-	Jun	2	2:00	0	S
Rule Louisville	1950	1955	-	Sep	lastSun	2:00	0	S
Rule Louisville	1956	1960	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Kentucky/Louisville -5:43:02 -	LMT	1883 Nov 18 12:16:58
			-6:00	US	C%sT	1921
			-6:00 Louisville C%sT	1942
			-6:00	US	C%sT	1946
			-6:00 Louisville C%sT	1961 Jul 23 2:00
			-5:00	-	EST	1968
			-5:00	US	E%sT	1974 Jan  6 2:00
			-6:00	1:00	CDT	1974 Oct 27 2:00
			-5:00	US	E%sT
#
# Wayne County, Kentucky
#
# From
# 
# Lake Cumberland LIFE
#  (1999-01-29) via WKYM-101.7:
# Clinton County has joined Wayne County in asking the DoT to change from
# the Central to the Eastern time zone....  The Wayne County government made
# the same request in December.  And while Russell County officials have not
# taken action, the majority of respondents to a poll conducted there in
# August indicated they would like to change to "fast time" also.
# The three Lake Cumberland counties are the farthest east of any U.S.
# location in the Central time zone.
#
# From Rich Wales (2000-08-29):
# After prolonged debate, and despite continuing deep differences of opinion,
# Wayne County (central Kentucky) is switching from Central (-0600) to Eastern
# (-0500) time.  They won't "fall back" this year.  See Sara Shipley,
# The difference an hour makes, Nando Times (2000-08-29 15:33 -0400).
#
# From Paul Eggert (2001-07-16):
# The final rule was published in the
# 
# Federal Register 65, 160 (2000-08-17), page 50154-50158.
# 
#
Zone America/Kentucky/Monticello -5:39:24 - LMT	1883 Nov 18 12:20:36
			-6:00	US	C%sT	1946
			-6:00	-	CST	1968
			-6:00	US	C%sT	2000 Oct 29  2:00
			-5:00	US	E%sT


# From Rives McDow (2000-08-30):
# Here ... are all the changes in the US since 1985.
# Kearny County, KS (put all of county on central;
#	previously split between MST and CST) ... 1990-10
# Starke County, IN (from CST to EST) ... 1991-10
# Oliver County, ND (from MST to CST) ... 1992-10
# West Wendover, NV (from PST TO MST) ... 1999-10
# Wayne County, KY (from CST to EST) ... 2000-10
#
# From Paul Eggert (2001-07-17):
# We don't know where the line used to be within Kearny County, KS,
# so omit that change for now.
# See America/Indiana/Knox for the Starke County, IN change.
# See America/North_Dakota/Center for the Oliver County, ND change.
# West Wendover, NV officially switched from Pacific to mountain time on
# 1999-10-31.  See the
# 
# Federal Register 64, 203 (1999-10-21), page 56705-56707.
# 
# However, the Federal Register says that West Wendover already operated
# on mountain time, and the rule merely made this official;
# hence a separate tz entry is not needed.

# Michigan
#
# From Bob Devine (1988-01-28):
# Michigan didn't observe DST from 1968 to 1973.
#
# From Paul Eggert (1999-03-31):
# Shanks writes that Michigan started using standard time on 1885-09-18,
# but Howse writes (pp 124-125, referring to Popular Astronomy, 1901-01)
# that Detroit kept
#
#	local time until 1900 when the City Council decreed that clocks should
#	be put back twenty-eight minutes to Central Standard Time.  Half the
#	city obeyed, half refused.  After considerable debate, the decision
#	was rescinded and the city reverted to Sun time.  A derisive offer to
#	erect a sundial in front of the city hall was referred to the
#	Committee on Sewers.  Then, in 1905, Central time was adopted
#	by city vote.
#
# This story is too entertaining to be false, so go with Howse over Shanks.
#
# From Paul Eggert (2001-03-06):
# Garland (1927) writes ``Cleveland and Detroit advanced their clocks
# one hour in 1914.''  This change is not in Shanks.  We have no more
# info, so omit this for now.
#
# Most of Michigan observed DST from 1973 on, but was a bit late in 1975.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule	Detroit	1948	only	-	Apr	lastSun	2:00	1:00	D
Rule	Detroit	1948	only	-	Sep	lastSun	2:00	0	S
Rule	Detroit	1967	only	-	Jun	14	2:00	1:00	D
Rule	Detroit	1967	only	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Detroit	-5:32:11 -	LMT	1905
			-6:00	-	CST	1915 May 15 2:00
			-5:00	-	EST	1942
			-5:00	US	E%sT	1946
			-5:00	Detroit	E%sT	1973
			-5:00	US	E%sT	1975
			-5:00	-	EST	1975 Apr 27 2:00
			-5:00	US	E%sT
#
# Dickinson, Gogebic, Iron, and Menominee Counties, Michigan,
# switched from EST to CST/CDT in 1973.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
Rule Menominee	1946	only	-	Apr	lastSun	2:00	1:00	D
Rule Menominee	1946	only	-	Sep	lastSun	2:00	0	S
Rule Menominee	1966	only	-	Apr	lastSun	2:00	1:00	D
Rule Menominee	1966	only	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Menominee	-5:50:27 -	LMT	1885 Sep 18 12:00
			-6:00	US	C%sT	1946
			-6:00 Menominee	C%sT	1969 Apr 27 2:00
			-5:00	-	EST	1973 Apr 29 2:00
			-6:00	US	C%sT

# Navassa
# administered by the US Fish and Wildlife Service
# claimed by US under the provisions of the 1856 Guano Islands Act
# also claimed by Haiti
# occupied 1857/1900 by the Navassa Phosphate Co
# US lighthouse 1917/1996-09
# currently uninhabited
# see Mark Fineman, ``An Isle Rich in Guano and Discord'',
# _Los Angeles Times_ (1998-11-10), A1, A10; it cites
# Jimmy Skaggs, _The Great Guano Rush_ (1994).

################################################################################


# From Paul Eggert (2006-03-22):
# A good source for time zone historical data outside the U.S. is
# Thomas G. Shanks and Rique Pottenger, The International Atlas (6th edition),
# San Diego: ACS Publications, Inc. (2003).
#
# Gwillim Law writes that a good source
# for recent time zone data is the International Air Transport
# Association's Standard Schedules Information Manual (IATA SSIM),
# published semiannually.  Law sent in several helpful summaries
# of the IATA's data after 1990.
#
# Except where otherwise noted, Shanks & Pottenger is the source for
# entries through 1990, and IATA SSIM is the source for entries afterwards.
#
# Other sources occasionally used include:
#
#	Edward W. Whitman, World Time Differences,
#	Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated),
#	which I found in the UCLA library.
#
#	
#	William Willett, The Waste of Daylight, 19th edition
#	 (1914-03)
#
#	Milne J. Civil time. Geogr J. 1899 Feb;13(2):173-94
#	.
#
# See the `europe' file for Greenland.

# Canada

# From Alain LaBont (1994-11-14):
# I post here the time zone abbreviations standardized in Canada
# for both English and French in the CAN/CSA-Z234.4-89 standard....
#
#	UTC	Standard time	Daylight savings time
#	offset	French	English	French	English
#	-2:30	-	-	HAT	NDT
#	-3	-	-	HAA	ADT
#	-3:30	HNT	NST	-	-
#	-4	HNA	AST	HAE	EDT
#	-5	HNE	EST	HAC	CDT
#	-6	HNC	CST	HAR	MDT
#	-7	HNR	MST	HAP	PDT
#	-8	HNP	PST	HAY	YDT
#	-9	HNY	YST	-	-
#
#	HN: Heure Normale	ST: Standard Time
#	HA: Heure Avance	DT: Daylight saving Time
#
#	A: de l'Atlantique	Atlantic
#	C: du Centre		Central
#	E: de l'Est		Eastern
#	M:			Mountain
#	N:			Newfoundland
#	P: du Pacifique		Pacific
#	R: des Rocheuses
#	T: de Terre-Neuve
#	Y: du Yukon		Yukon
#
# From Paul Eggert (1994-11-22):
# Alas, this sort of thing must be handled by localization software.

# Unless otherwise specified, the data for Canada are all from Shanks
# & Pottenger.

# From Chris Walton (2006-04-01, 2006-04-25, 2006-06-26, 2007-01-31,
# 2007-03-01):
# The British Columbia government announced yesterday that it will
# adjust daylight savings next year to align with changes in the
# U.S. and the rest of Canada....
# http://www2.news.gov.bc.ca/news_releases_2005-2009/2006AG0014-000330.htm
# ...
# Nova Scotia
# Daylight saving time will be extended by four weeks starting in 2007....
# http://www.gov.ns.ca/just/regulations/rg2/2006/ma1206.pdf
#
# [For New Brunswick] the new legislation dictates that the time change is to
# be done at 02:00 instead of 00:01.
# http://www.gnb.ca/0062/acts/BBA-2006/Chap-19.pdf
# ...
# Manitoba has traditionally changed the clock every fall at 03:00.
# As of 2006, the transition is to take place one hour earlier at 02:00.
# http://web2.gov.mb.ca/laws/statutes/ccsm/o030e.php
# ...
# [Alberta, Ontario, Quebec] will follow US rules.
# http://www.qp.gov.ab.ca/documents/spring/CH03_06.CFM
# http://www.e-laws.gov.on.ca/DBLaws/Source/Regs/English/2006/R06111_e.htm
# http://www2.publicationsduquebec.gouv.qc.ca/dynamicSearch/telecharge.php?type=5&file=2006C39A.PDF
# ...
# P.E.I. will follow US rules....
# http://www.assembly.pe.ca/bills/pdf_chapter/62/3/chapter-41.pdf
# ...
# Province of Newfoundland and Labrador....
# http://www.hoa.gov.nl.ca/hoa/bills/Bill0634.htm
# ...
# Yukon
# http://www.gov.yk.ca/legislation/regs/oic2006_127.pdf
# ...
# N.W.T. will follow US rules.  Whoever maintains the government web site
# does not seem to believe in bookmarks.  To see the news release, click the
# following link and search for "Daylight Savings Time Change".  Press the
# "Daylight Savings Time Change" link; it will fire off a popup using
# JavaScript.
# http://www.exec.gov.nt.ca/currentnews/currentPR.asp?mode=archive
# ...
# Nunavut
# An amendment to the Interpretation Act was registered on February 19/2007....
# http://action.attavik.ca/home/justice-gn/attach/2007/gaz02part2.pdf

# From Paul Eggert (2006-04-25):
# H. David Matthews and Mary Vincent's map
# 
# "It's about TIME", _Canadian Geographic_ (September-October 1998)
#  contains detailed boundaries for regions observing nonstandard
# time and daylight saving time arrangements in Canada circa 1998.
#
# INMS, the Institute for National Measurement Standards in Ottawa, has 
# information about standard and daylight saving time zones in Canada.
#  (updated periodically).
# Its unofficial information is often taken from Matthews and Vincent.

# From Paul Eggert (2006-06-27):
# For now, assume all of DST-observing Canada will fall into line with the
# new US DST rules,

# From Chris Walton (2011-12-01)
# In the first of Tammy Hardwick's articles
# 
# http://www.ilovecreston.com/?p=articles&t=spec&ar=260
# 
# she quotes the Friday November 1/1918 edition of the Creston Review.
# The quote includes these two statements:
# 'Sunday the CPR went back to the old system of time...'
# '... The daylight saving scheme was dropped all over Canada at the same time,'
# These statements refer to a transition from daylight time to standard time
# that occurred nationally on Sunday October 27/1918.  This transition was
# also documented in the Saturday October 26/1918 edition of the Toronto Star.

# In light of that evidence, we alter the date from the earlier believed
# Oct 31, to Oct 27, 1918 (and Sunday is a more likely transition day
# than Thursday) in all Canadian rulesets.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Canada	1918	only	-	Apr	14	2:00	1:00	D
Rule	Canada	1918	only	-	Oct	27	2:00	0	S
Rule	Canada	1942	only	-	Feb	 9	2:00	1:00	W # War
Rule	Canada	1945	only	-	Aug	14	23:00u	1:00	P # Peace
Rule	Canada	1945	only	-	Sep	30	2:00	0	S
Rule	Canada	1974	1986	-	Apr	lastSun	2:00	1:00	D
Rule	Canada	1974	2006	-	Oct	lastSun	2:00	0	S
Rule	Canada	1987	2006	-	Apr	Sun>=1	2:00	1:00	D
Rule	Canada	2007	max	-	Mar	Sun>=8	2:00	1:00	D
Rule	Canada	2007	max	-	Nov	Sun>=1	2:00	0	S


# Newfoundland and Labrador

# From Paul Eggert (2000-10-02):
# Matthews and Vincent (1998) write that Labrador should use NST/NDT,
# but the only part of Labrador that follows the rules is the
# southeast corner, including Port Hope Simpson and Mary's Harbour,
# but excluding, say, Black Tickle.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	StJohns	1917	only	-	Apr	 8	2:00	1:00	D
Rule	StJohns	1917	only	-	Sep	17	2:00	0	S
# Whitman gives 1919 Apr 5 and 1920 Apr 5; go with Shanks & Pottenger.
Rule	StJohns	1919	only	-	May	 5	23:00	1:00	D
Rule	StJohns	1919	only	-	Aug	12	23:00	0	S
# For 1931-1935 Whitman gives Apr same date; go with Shanks & Pottenger.
Rule	StJohns	1920	1935	-	May	Sun>=1	23:00	1:00	D
Rule	StJohns	1920	1935	-	Oct	lastSun	23:00	0	S
# For 1936-1941 Whitman gives May Sun>=8 and Oct Sun>=1; go with Shanks &
# Pottenger.
Rule	StJohns	1936	1941	-	May	Mon>=9	0:00	1:00	D
Rule	StJohns	1936	1941	-	Oct	Mon>=2	0:00	0	S
# Whitman gives the following transitions:
# 1942 03-01/12-31, 1943 05-30/09-05, 1944 07-10/09-02, 1945 01-01/10-07
# but go with Shanks & Pottenger and assume they used Canadian rules.
# For 1946-9 Whitman gives May 5,4,9,1 - Oct 1,5,3,2, and for 1950 he gives
# Apr 30 - Sep 24; go with Shanks & Pottenger.
Rule	StJohns	1946	1950	-	May	Sun>=8	2:00	1:00	D
Rule	StJohns	1946	1950	-	Oct	Sun>=2	2:00	0	S
Rule	StJohns	1951	1986	-	Apr	lastSun	2:00	1:00	D
Rule	StJohns	1951	1959	-	Sep	lastSun	2:00	0	S
Rule	StJohns	1960	1986	-	Oct	lastSun	2:00	0	S
# From Paul Eggert (2000-10-02):
# INMS (2000-09-12) says that, since 1988 at least, Newfoundland switches
# at 00:01 local time.  For now, assume it started in 1987.

# From Michael Pelley (2011-09-12):
# We received today, Monday, September 12, 2011, notification that the
# changes to the Newfoundland Standard Time Act have been proclaimed.
# The change in the Act stipulates that the change from Daylight Savings
# Time to Standard Time and from Standard Time to Daylight Savings Time
# now occurs at 2:00AM.
# ...
# 
# http://www.assembly.nl.ca/legislation/sr/annualstatutes/2011/1106.chp.htm
# 
# ...
# MICHAEL PELLEY  |  Manager of Enterprise Architecture - Solution Delivery
# Office of the Chief Information Officer
# Executive Council
# Government of Newfoundland & Labrador

Rule	StJohns	1987	only	-	Apr	Sun>=1	0:01	1:00	D
Rule	StJohns	1987	2006	-	Oct	lastSun	0:01	0	S
Rule	StJohns	1988	only	-	Apr	Sun>=1	0:01	2:00	DD
Rule	StJohns	1989	2006	-	Apr	Sun>=1	0:01	1:00	D
Rule	StJohns	2007	2011	-	Mar	Sun>=8	0:01	1:00	D
Rule	StJohns	2007	2010	-	Nov	Sun>=1	0:01	0	S
#
# St John's has an apostrophe, but Posix file names can't have apostrophes.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/St_Johns	-3:30:52 -	LMT	1884
			-3:30:52 StJohns N%sT	1918
			-3:30:52 Canada	N%sT	1919
			-3:30:52 StJohns N%sT	1935 Mar 30
			-3:30	StJohns	N%sT	1942 May 11
			-3:30	Canada	N%sT	1946
			-3:30	StJohns	N%sT	2011 Nov
			-3:30	Canada	N%sT

# most of east Labrador

# The name `Happy Valley-Goose Bay' is too long; use `Goose Bay'.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Goose_Bay	-4:01:40 -	LMT	1884 # Happy Valley-Goose Bay
			-3:30:52 -	NST	1918
			-3:30:52 Canada N%sT	1919
			-3:30:52 -	NST	1935 Mar 30
			-3:30	-	NST	1936
			-3:30	StJohns	N%sT	1942 May 11
			-3:30	Canada	N%sT	1946
			-3:30	StJohns	N%sT	1966 Mar 15 2:00
			-4:00	StJohns	A%sT	2011 Nov
			-4:00	Canada	A%sT


# west Labrador, Nova Scotia, Prince Edward I

# From Paul Eggert (2006-03-22):
# Shanks & Pottenger write that since 1970 most of this region has been like
# Halifax.  Many locales did not observe peacetime DST until 1972;
# Glace Bay, NS is the largest that we know of.
# Shanks & Pottenger also write that Liverpool, NS was the only town
# in Canada to observe DST in 1971 but not 1970; for now we'll assume
# this is a typo.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Halifax	1916	only	-	Apr	 1	0:00	1:00	D
Rule	Halifax	1916	only	-	Oct	 1	0:00	0	S
Rule	Halifax	1920	only	-	May	 9	0:00	1:00	D
Rule	Halifax	1920	only	-	Aug	29	0:00	0	S
Rule	Halifax	1921	only	-	May	 6	0:00	1:00	D
Rule	Halifax	1921	1922	-	Sep	 5	0:00	0	S
Rule	Halifax	1922	only	-	Apr	30	0:00	1:00	D
Rule	Halifax	1923	1925	-	May	Sun>=1	0:00	1:00	D
Rule	Halifax	1923	only	-	Sep	 4	0:00	0	S
Rule	Halifax	1924	only	-	Sep	15	0:00	0	S
Rule	Halifax	1925	only	-	Sep	28	0:00	0	S
Rule	Halifax	1926	only	-	May	16	0:00	1:00	D
Rule	Halifax	1926	only	-	Sep	13	0:00	0	S
Rule	Halifax	1927	only	-	May	 1	0:00	1:00	D
Rule	Halifax	1927	only	-	Sep	26	0:00	0	S
Rule	Halifax	1928	1931	-	May	Sun>=8	0:00	1:00	D
Rule	Halifax	1928	only	-	Sep	 9	0:00	0	S
Rule	Halifax	1929	only	-	Sep	 3	0:00	0	S
Rule	Halifax	1930	only	-	Sep	15	0:00	0	S
Rule	Halifax	1931	1932	-	Sep	Mon>=24	0:00	0	S
Rule	Halifax	1932	only	-	May	 1	0:00	1:00	D
Rule	Halifax	1933	only	-	Apr	30	0:00	1:00	D
Rule	Halifax	1933	only	-	Oct	 2	0:00	0	S
Rule	Halifax	1934	only	-	May	20	0:00	1:00	D
Rule	Halifax	1934	only	-	Sep	16	0:00	0	S
Rule	Halifax	1935	only	-	Jun	 2	0:00	1:00	D
Rule	Halifax	1935	only	-	Sep	30	0:00	0	S
Rule	Halifax	1936	only	-	Jun	 1	0:00	1:00	D
Rule	Halifax	1936	only	-	Sep	14	0:00	0	S
Rule	Halifax	1937	1938	-	May	Sun>=1	0:00	1:00	D
Rule	Halifax	1937	1941	-	Sep	Mon>=24	0:00	0	S
Rule	Halifax	1939	only	-	May	28	0:00	1:00	D
Rule	Halifax	1940	1941	-	May	Sun>=1	0:00	1:00	D
Rule	Halifax	1946	1949	-	Apr	lastSun	2:00	1:00	D
Rule	Halifax	1946	1949	-	Sep	lastSun	2:00	0	S
Rule	Halifax	1951	1954	-	Apr	lastSun	2:00	1:00	D
Rule	Halifax	1951	1954	-	Sep	lastSun	2:00	0	S
Rule	Halifax	1956	1959	-	Apr	lastSun	2:00	1:00	D
Rule	Halifax	1956	1959	-	Sep	lastSun	2:00	0	S
Rule	Halifax	1962	1973	-	Apr	lastSun	2:00	1:00	D
Rule	Halifax	1962	1973	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Halifax	-4:14:24 -	LMT	1902 Jun 15
			-4:00	Halifax	A%sT	1918
			-4:00	Canada	A%sT	1919
			-4:00	Halifax	A%sT	1942 Feb  9 2:00s
			-4:00	Canada	A%sT	1946
			-4:00	Halifax	A%sT	1974
			-4:00	Canada	A%sT
Zone America/Glace_Bay	-3:59:48 -	LMT	1902 Jun 15
			-4:00	Canada	A%sT	1953
			-4:00	Halifax	A%sT	1954
			-4:00	-	AST	1972
			-4:00	Halifax	A%sT	1974
			-4:00	Canada	A%sT

# New Brunswick

# From Paul Eggert (2007-01-31):
# The Time Definition Act 
# says they changed at 00:01 through 2006, and
#  makes it
# clear that this was the case since at least 1993.
# For now, assume it started in 1993.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Moncton	1933	1935	-	Jun	Sun>=8	1:00	1:00	D
Rule	Moncton	1933	1935	-	Sep	Sun>=8	1:00	0	S
Rule	Moncton	1936	1938	-	Jun	Sun>=1	1:00	1:00	D
Rule	Moncton	1936	1938	-	Sep	Sun>=1	1:00	0	S
Rule	Moncton	1939	only	-	May	27	1:00	1:00	D
Rule	Moncton	1939	1941	-	Sep	Sat>=21	1:00	0	S
Rule	Moncton	1940	only	-	May	19	1:00	1:00	D
Rule	Moncton	1941	only	-	May	 4	1:00	1:00	D
Rule	Moncton	1946	1972	-	Apr	lastSun	2:00	1:00	D
Rule	Moncton	1946	1956	-	Sep	lastSun	2:00	0	S
Rule	Moncton	1957	1972	-	Oct	lastSun	2:00	0	S
Rule	Moncton	1993	2006	-	Apr	Sun>=1	0:01	1:00	D
Rule	Moncton	1993	2006	-	Oct	lastSun	0:01	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Moncton	-4:19:08 -	LMT	1883 Dec  9
			-5:00	-	EST	1902 Jun 15
			-4:00	Canada	A%sT	1933
			-4:00	Moncton	A%sT	1942
			-4:00	Canada	A%sT	1946
			-4:00	Moncton	A%sT	1973
			-4:00	Canada	A%sT	1993
			-4:00	Moncton	A%sT	2007
			-4:00	Canada	A%sT

# Quebec

# From Paul Eggert (2006-07-09):
# Shanks & Pottenger write that since 1970 most of Quebec has been
# like Montreal.

# From Paul Eggert (2006-06-27):
# Matthews and Vincent (1998) also write that Quebec east of the -63
# meridian is supposed to observe AST, but residents as far east as
# Natashquan use EST/EDT, and residents east of Natashquan use AST.
# In "Official time in Quebec" the Quebec department of justice writes in
# http://www.justice.gouv.qc.ca/english/publications/generale/temps-regl-1-a.htm
# that "The residents of the Municipality of the
# Cote-Nord-du-Golfe-Saint-Laurent and the municipalities of Saint-Augustin,
# Bonne-Esperance and Blanc-Sablon apply the Official Time Act as it is
# written and use Atlantic standard time all year round. The same applies to
# the residents of the Native facilities along the lower North Shore."
# 
# says this common practice was codified into law as of 2007.
# For lack of better info, guess this practice began around 1970, contra to
# Shanks & Pottenger who have this region observing AST/ADT.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Mont	1917	only	-	Mar	25	2:00	1:00	D
Rule	Mont	1917	only	-	Apr	24	0:00	0	S
Rule	Mont	1919	only	-	Mar	31	2:30	1:00	D
Rule	Mont	1919	only	-	Oct	25	2:30	0	S
Rule	Mont	1920	only	-	May	 2	2:30	1:00	D
Rule	Mont	1920	1922	-	Oct	Sun>=1	2:30	0	S
Rule	Mont	1921	only	-	May	 1	2:00	1:00	D
Rule	Mont	1922	only	-	Apr	30	2:00	1:00	D
Rule	Mont	1924	only	-	May	17	2:00	1:00	D
Rule	Mont	1924	1926	-	Sep	lastSun	2:30	0	S
Rule	Mont	1925	1926	-	May	Sun>=1	2:00	1:00	D
# The 1927-to-1937 rules can be expressed more simply as
# Rule	Mont	1927	1937	-	Apr	lastSat	24:00	1:00	D
# Rule	Mont	1927	1937	-	Sep	lastSat	24:00	0	S
# The rules below avoid use of 24:00
# (which pre-1998 versions of zic cannot handle).
Rule	Mont	1927	only	-	May	1	0:00	1:00	D
Rule	Mont	1927	1932	-	Sep	lastSun	0:00	0	S
Rule	Mont	1928	1931	-	Apr	lastSun	0:00	1:00	D
Rule	Mont	1932	only	-	May	1	0:00	1:00	D
Rule	Mont	1933	1940	-	Apr	lastSun	0:00	1:00	D
Rule	Mont	1933	only	-	Oct	1	0:00	0	S
Rule	Mont	1934	1939	-	Sep	lastSun	0:00	0	S
Rule	Mont	1946	1973	-	Apr	lastSun	2:00	1:00	D
Rule	Mont	1945	1948	-	Sep	lastSun	2:00	0	S
Rule	Mont	1949	1950	-	Oct	lastSun	2:00	0	S
Rule	Mont	1951	1956	-	Sep	lastSun	2:00	0	S
Rule	Mont	1957	1973	-	Oct	lastSun	2:00	0	S

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Blanc-Sablon -3:48:28 -	LMT	1884
			-4:00	Canada	A%sT	1970
			-4:00	-	AST
Zone America/Montreal	-4:54:16 -	LMT	1884
			-5:00	Mont	E%sT	1918
			-5:00	Canada	E%sT	1919
			-5:00	Mont	E%sT	1942 Feb  9 2:00s
			-5:00	Canada	E%sT	1946
			-5:00	Mont	E%sT	1974
			-5:00	Canada	E%sT


# Ontario

# From Paul Eggert (2006-07-09):
# Shanks & Pottenger write that since 1970 most of Ontario has been like
# Toronto.
# Thunder Bay skipped DST in 1973.
# Many smaller locales did not observe peacetime DST until 1974;
# Nipigon (EST) and Rainy River (CST) are the largest that we know of.
# Far west Ontario is like Winnipeg; far east Quebec is like Halifax.

# From Mark Brader (2003-07-26):
# [According to the Toronto Star] Orillia, Ontario, adopted DST
# effective Saturday, 1912-06-22, 22:00; the article mentions that
# Port Arthur (now part of Thunder Bay, Ontario) as well as Moose Jaw
# have already done so.  In Orillia DST was to run until Saturday,
# 1912-08-31 (no time mentioned), but it was met with considerable
# hostility from certain segments of the public, and was revoked after
# only two weeks -- I copied it as Saturday, 1912-07-07, 22:00, but
# presumably that should be -07-06.  (1912-06-19, -07-12; also letters
# earlier in June).
#
# Kenora, Ontario, was to abandon DST on 1914-06-01 (-05-21).

# From Paul Eggert (1997-10-17):
# Mark Brader writes that an article in the 1997-10-14 Toronto Star
# says that Atikokan, Ontario currently does not observe DST,
# but will vote on 11-10 whether to use EST/EDT.
# He also writes that the
# 
# Ontario Time Act (1990, Chapter T.9)
# 
# says that Ontario east of 90W uses EST/EDT, and west of 90W uses CST/CDT.
# Officially Atikokan is therefore on CST/CDT, and most likely this report
# concerns a non-official time observed as a matter of local practice.
#
# From Paul Eggert (2000-10-02):
# Matthews and Vincent (1998) write that Atikokan, Pickle Lake, and
# New Osnaburgh observe CST all year, that Big Trout Lake observes
# CST/CDT, and that Upsala and Shebandowan observe EST/EDT, all in
# violation of the official Ontario rules.
#
# From Paul Eggert (2006-07-09):
# Chris Walton (2006-07-06) mentioned an article by Stephanie MacLellan in the
# 2005-07-21 Chronicle-Journal, which said:
#
#	The clocks in Atikokan stay set on standard time year-round.
#	This means they spend about half the time on central time and
#	the other half on eastern time.
#
#	For the most part, the system works, Mayor Dennis Brown said.
#
#	"The majority of businesses in Atikokan deal more with Eastern
#	Canada, but there are some that deal with Western Canada," he
#	said.  "I don't see any changes happening here."
#
# Walton also writes "Supposedly Pickle Lake and Mishkeegogamang
# [New Osnaburgh] follow the same practice."

# From Garry McKinnon (2006-07-14) via Chris Walton:
# I chatted with a member of my board who has an outstanding memory
# and a long history in Atikokan (and in the telecom industry) and he
# can say for certain that Atikokan has been practicing the current
# time keeping since 1952, at least.

# From Paul Eggert (2006-07-17):
# Shanks & Pottenger say that Atikokan has agreed with Rainy River
# ever since standard time was introduced, but the information from
# McKinnon sounds more authoritative.  For now, assume that Atikokan
# switched to EST immediately after WWII era daylight saving time
# ended.  This matches the old (less-populous) America/Coral_Harbour
# entry since our cutoff date of 1970, so we can move
# America/Coral_Harbour to the 'backward' file.

# From Mark Brader (2010-03-06):
#
# Currently the database has:
#
# # Ontario
#
# # From Paul Eggert (2006-07-09):
# # Shanks & Pottenger write that since 1970 most of Ontario has been like
# # Toronto.
# # Thunder Bay skipped DST in 1973.
# # Many smaller locales did not observe peacetime DST until 1974;
# # Nipigon (EST) and Rainy River (CST) are the largest that we know of.
#
# In the (Toronto) Globe and Mail for Saturday, 1955-09-24, in the bottom
# right corner of page 1, it says that Toronto will return to standard
# time at 2 am Sunday morning (which agrees with the database), and that:
#
#     The one-hour setback will go into effect throughout most of Ontario,
#     except in areas like Windsor which remains on standard time all year.
#
# Windsor is, of course, a lot larger than Nipigon.
#
# I only came across this incidentally.  I don't know if Windsor began
# observing DST when Detroit did, or in 1974, or on some other date.
#
# By the way, the article continues by noting that:
#
#     Some cities in the United States have pushed the deadline back
#     three weeks and will change over from daylight saving in October.

# From Arthur David Olson (2010-07-17):
#
# "Standard Time and Time Zones in Canada" appeared in
# The Journal of The Royal Astronomical Society of Canada,
# volume 26, number 2 (February 1932) and, as of 2010-07-17,
# was available at
# 
# http://adsabs.harvard.edu/full/1932JRASC..26...49S
# 
#
# It includes the text below (starting on page 57):
#
#   A list of the places in Canada using daylight saving time would
# require yearly revision. From information kindly furnished by
# the provincial governments and by the postmasters in many cities
# and towns, it is found that the following places used daylight sav-
# ing in 1930. The information for the province of Quebec is definite,
# for the other provinces only approximate:
#
# 	Province	Daylight saving time used
# Prince Edward Island	Not used.
# Nova Scotia		In Halifax only.
# New Brunswick		In St. John only.
# Quebec		In the following places:
# 			Montreal	Lachine
# 			Quebec		Mont-Royal
# 			Levis		Iberville
# 			St. Lambert	Cap de la Madeleine
# 			Verdun		Loretteville
# 			Westmount	Richmond
# 			Outremont	St. Jerome
# 			Longueuil	Greenfield Park
# 			Arvida		Waterloo
# 			Chambly-Canton	Beaulieu
# 			Melbourne	La Tuque
# 			St. Theophile	Buckingham
# Ontario		Used generally in the cities and towns along
# 			the southerly part of the province. Not
# 			used in the northwesterlhy part.
# Manitoba		Not used.
# Saskatchewan		In Regina only.
# Alberta		Not used.
# British Columbia	Not used.
#
#   With some exceptions, the use of daylight saving may be said to be limited
# to those cities and towns lying between Quebec city and Windsor, Ont.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Toronto	1919	only	-	Mar	30	23:30	1:00	D
Rule	Toronto	1919	only	-	Oct	26	0:00	0	S
Rule	Toronto	1920	only	-	May	 2	2:00	1:00	D
Rule	Toronto	1920	only	-	Sep	26	0:00	0	S
Rule	Toronto	1921	only	-	May	15	2:00	1:00	D
Rule	Toronto	1921	only	-	Sep	15	2:00	0	S
Rule	Toronto	1922	1923	-	May	Sun>=8	2:00	1:00	D
# Shanks & Pottenger say 1923-09-19; assume it's a typo and that "-16"
# was meant.
Rule	Toronto	1922	1926	-	Sep	Sun>=15	2:00	0	S
Rule	Toronto	1924	1927	-	May	Sun>=1	2:00	1:00	D
# The 1927-to-1939 rules can be expressed more simply as
# Rule	Toronto	1927	1937	-	Sep	Sun>=25	2:00	0	S
# Rule	Toronto	1928	1937	-	Apr	Sun>=25	2:00	1:00	D
# Rule	Toronto	1938	1940	-	Apr	lastSun	2:00	1:00	D
# Rule	Toronto	1938	1939	-	Sep	lastSun	2:00	0	S
# The rules below avoid use of Sun>=25
# (which pre-2004 versions of zic cannot handle).
Rule	Toronto	1927	1932	-	Sep	lastSun	2:00	0	S
Rule	Toronto	1928	1931	-	Apr	lastSun	2:00	1:00	D
Rule	Toronto	1932	only	-	May	1	2:00	1:00	D
Rule	Toronto	1933	1940	-	Apr	lastSun	2:00	1:00	D
Rule	Toronto	1933	only	-	Oct	1	2:00	0	S
Rule	Toronto	1934	1939	-	Sep	lastSun	2:00	0	S
Rule	Toronto	1945	1946	-	Sep	lastSun	2:00	0	S
Rule	Toronto	1946	only	-	Apr	lastSun	2:00	1:00	D
Rule	Toronto	1947	1949	-	Apr	lastSun	0:00	1:00	D
Rule	Toronto	1947	1948	-	Sep	lastSun	0:00	0	S
Rule	Toronto	1949	only	-	Nov	lastSun	0:00	0	S
Rule	Toronto	1950	1973	-	Apr	lastSun	2:00	1:00	D
Rule	Toronto	1950	only	-	Nov	lastSun	2:00	0	S
Rule	Toronto	1951	1956	-	Sep	lastSun	2:00	0	S
# Shanks & Pottenger say Toronto ended DST a week early in 1971,
# namely on 1971-10-24, but Mark Brader wrote (2003-05-31) that this
# is wrong, and that he had confirmed it by checking the 1971-10-30
# Toronto Star, which said that DST was ending 1971-10-31 as usual.
Rule	Toronto	1957	1973	-	Oct	lastSun	2:00	0	S

# From Paul Eggert (2003-07-27):
# Willett (1914-03) writes (p. 17) "In the Cities of Fort William, and
# Port Arthur, Ontario, the principle of the Bill has been in
# operation for the past three years, and in the City of Moose Jaw,
# Saskatchewan, for one year."

# From David Bryan via Tory Tronrud, Director/Curator,
# Thunder Bay Museum (2003-11-12):
# There is some suggestion, however, that, by-law or not, daylight
# savings time was being practiced in Fort William and Port Arthur
# before 1909.... [I]n 1910, the line between the Eastern and Central
# Time Zones was permanently moved about two hundred miles west to
# include the Thunder Bay area....  When Canada adopted daylight
# savings time in 1916, Fort William and Port Arthur, having done so
# already, did not change their clocks....  During the Second World
# War,... [t]he cities agreed to implement DST during the summer
# months for the remainder of the war years.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Toronto	-5:17:32 -	LMT	1895
			-5:00	Canada	E%sT	1919
			-5:00	Toronto	E%sT	1942 Feb  9 2:00s
			-5:00	Canada	E%sT	1946
			-5:00	Toronto	E%sT	1974
			-5:00	Canada	E%sT
Zone America/Thunder_Bay -5:57:00 -	LMT	1895
			-6:00	-	CST	1910
			-5:00	-	EST	1942
			-5:00	Canada	E%sT	1970
			-5:00	Mont	E%sT	1973
			-5:00	-	EST	1974
			-5:00	Canada	E%sT
Zone America/Nipigon	-5:53:04 -	LMT	1895
			-5:00	Canada	E%sT	1940 Sep 29
			-5:00	1:00	EDT	1942 Feb  9 2:00s
			-5:00	Canada	E%sT
Zone America/Rainy_River -6:18:16 -	LMT	1895
			-6:00	Canada	C%sT	1940 Sep 29
			-6:00	1:00	CDT	1942 Feb  9 2:00s
			-6:00	Canada	C%sT
Zone America/Atikokan	-6:06:28 -	LMT	1895
			-6:00	Canada	C%sT	1940 Sep 29
			-6:00	1:00	CDT	1942 Feb  9 2:00s
			-6:00	Canada	C%sT	1945 Sep 30 2:00
			-5:00	-	EST


# Manitoba

# From Rob Douglas (2006-04-06):
# the old Manitoba Time Act - as amended by Bill 2, assented to
# March 27, 1987 ... said ...
# "between two o'clock Central Standard Time in the morning of
# the first Sunday of April of each year and two o'clock Central
# Standard Time in the morning of the last Sunday of October next
# following, one hour in advance of Central Standard Time."...
# I believe that the English legislation [of the old time act] had =
# been assented to (March 22, 1967)....
# Also, as far as I can tell, there was no order-in-council varying
# the time of Daylight Saving Time for 2005 and so the provisions of
# the 1987 version would apply - the changeover was at 2:00 Central
# Standard Time (i.e. not until 3:00 Central Daylight Time).

# From Paul Eggert (2006-04-10):
# Shanks & Pottenger say Manitoba switched at 02:00 (not 02:00s)
# starting 1966.  Since 02:00s is clearly correct for 1967 on, assume
# it was also 02:00s in 1966.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Winn	1916	only	-	Apr	23	0:00	1:00	D
Rule	Winn	1916	only	-	Sep	17	0:00	0	S
Rule	Winn	1918	only	-	Apr	14	2:00	1:00	D
Rule	Winn	1918	only	-	Oct	27	2:00	0	S
Rule	Winn	1937	only	-	May	16	2:00	1:00	D
Rule	Winn	1937	only	-	Sep	26	2:00	0	S
Rule	Winn	1942	only	-	Feb	 9	2:00	1:00	W # War
Rule	Winn	1945	only	-	Aug	14	23:00u	1:00	P # Peace
Rule	Winn	1945	only	-	Sep	lastSun	2:00	0	S
Rule	Winn	1946	only	-	May	12	2:00	1:00	D
Rule	Winn	1946	only	-	Oct	13	2:00	0	S
Rule	Winn	1947	1949	-	Apr	lastSun	2:00	1:00	D
Rule	Winn	1947	1949	-	Sep	lastSun	2:00	0	S
Rule	Winn	1950	only	-	May	 1	2:00	1:00	D
Rule	Winn	1950	only	-	Sep	30	2:00	0	S
Rule	Winn	1951	1960	-	Apr	lastSun	2:00	1:00	D
Rule	Winn	1951	1958	-	Sep	lastSun	2:00	0	S
Rule	Winn	1959	only	-	Oct	lastSun	2:00	0	S
Rule	Winn	1960	only	-	Sep	lastSun	2:00	0	S
Rule	Winn	1963	only	-	Apr	lastSun	2:00	1:00	D
Rule	Winn	1963	only	-	Sep	22	2:00	0	S
Rule	Winn	1966	1986	-	Apr	lastSun	2:00s	1:00	D
Rule	Winn	1966	2005	-	Oct	lastSun	2:00s	0	S
Rule	Winn	1987	2005	-	Apr	Sun>=1	2:00s	1:00	D
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Winnipeg	-6:28:36 -	LMT	1887 Jul 16
			-6:00	Winn	C%sT	2006
			-6:00	Canada	C%sT


# Saskatchewan

# From Mark Brader (2003-07-26):
# The first actual adoption of DST in Canada was at the municipal
# level.  As the [Toronto] Star put it (1912-06-07), "While people
# elsewhere have long been talking of legislation to save daylight,
# the city of Moose Jaw [Saskatchewan] has acted on its own hook."
# DST in Moose Jaw began on Saturday, 1912-06-01 (no time mentioned:
# presumably late evening, as below), and would run until "the end of
# the summer".  The discrepancy between municipal time and railroad
# time was noted.

# From Paul Eggert (2003-07-27):
# Willett (1914-03) notes that DST "has been in operation ... in the
# City of Moose Jaw, Saskatchewan, for one year."

# From Paul Eggert (2006-03-22):
# Shanks & Pottenger say that since 1970 this region has mostly been as Regina.
# Some western towns (e.g. Swift Current) switched from MST/MDT to CST in 1972.
# Other western towns (e.g. Lloydminster) are like Edmonton.
# Matthews and Vincent (1998) write that Denare Beach and Creighton
# are like Winnipeg, in violation of Saskatchewan law.

# From W. Jones (1992-11-06):
# The. . .below is based on information I got from our law library, the
# provincial archives, and the provincial Community Services department.
# A precise history would require digging through newspaper archives, and
# since you didn't say what you wanted, I didn't bother.
#
# Saskatchewan is split by a time zone meridian (105W) and over the years
# the boundary became pretty ragged as communities near it reevaluated
# their affiliations in one direction or the other.  In 1965 a provincial
# referendum favoured legislating common time practices.
#
# On 15 April 1966 the Time Act (c. T-14, Revised Statutes of
# Saskatchewan 1978) was proclaimed, and established that the eastern
# part of Saskatchewan would use CST year round, that districts in
# northwest Saskatchewan would by default follow CST but could opt to
# follow Mountain Time rules (thus 1 hour difference in the winter and
# zero in the summer), and that districts in southwest Saskatchewan would
# by default follow MT but could opt to follow CST.
#
# It took a few years for the dust to settle (I know one story of a town
# on one time zone having its school in another, such that a mom had to
# serve her family lunch in two shifts), but presently it seems that only
# a few towns on the border with Alberta (e.g. Lloydminster) follow MT
# rules any more; all other districts appear to have used CST year round
# since sometime in the 1960s.

# From Chris Walton (2006-06-26):
# The Saskatchewan time act which was last updated in 1996 is about 30 pages
# long and rather painful to read.
# http://www.qp.gov.sk.ca/documents/English/Statutes/Statutes/T14.pdf

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Regina	1918	only	-	Apr	14	2:00	1:00	D
Rule	Regina	1918	only	-	Oct	27	2:00	0	S
Rule	Regina	1930	1934	-	May	Sun>=1	0:00	1:00	D
Rule	Regina	1930	1934	-	Oct	Sun>=1	0:00	0	S
Rule	Regina	1937	1941	-	Apr	Sun>=8	0:00	1:00	D
Rule	Regina	1937	only	-	Oct	Sun>=8	0:00	0	S
Rule	Regina	1938	only	-	Oct	Sun>=1	0:00	0	S
Rule	Regina	1939	1941	-	Oct	Sun>=8	0:00	0	S
Rule	Regina	1942	only	-	Feb	 9	2:00	1:00	W # War
Rule	Regina	1945	only	-	Aug	14	23:00u	1:00	P # Peace
Rule	Regina	1945	only	-	Sep	lastSun	2:00	0	S
Rule	Regina	1946	only	-	Apr	Sun>=8	2:00	1:00	D
Rule	Regina	1946	only	-	Oct	Sun>=8	2:00	0	S
Rule	Regina	1947	1957	-	Apr	lastSun	2:00	1:00	D
Rule	Regina	1947	1957	-	Sep	lastSun	2:00	0	S
Rule	Regina	1959	only	-	Apr	lastSun	2:00	1:00	D
Rule	Regina	1959	only	-	Oct	lastSun	2:00	0	S
#
Rule	Swift	1957	only	-	Apr	lastSun	2:00	1:00	D
Rule	Swift	1957	only	-	Oct	lastSun	2:00	0	S
Rule	Swift	1959	1961	-	Apr	lastSun	2:00	1:00	D
Rule	Swift	1959	only	-	Oct	lastSun	2:00	0	S
Rule	Swift	1960	1961	-	Sep	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Regina	-6:58:36 -	LMT	1905 Sep
			-7:00	Regina	M%sT	1960 Apr lastSun 2:00
			-6:00	-	CST
Zone America/Swift_Current -7:11:20 -	LMT	1905 Sep
			-7:00	Canada	M%sT	1946 Apr lastSun 2:00
			-7:00	Regina	M%sT	1950
			-7:00	Swift	M%sT	1972 Apr lastSun 2:00
			-6:00	-	CST


# Alberta

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Edm	1918	1919	-	Apr	Sun>=8	2:00	1:00	D
Rule	Edm	1918	only	-	Oct	27	2:00	0	S
Rule	Edm	1919	only	-	May	27	2:00	0	S
Rule	Edm	1920	1923	-	Apr	lastSun	2:00	1:00	D
Rule	Edm	1920	only	-	Oct	lastSun	2:00	0	S
Rule	Edm	1921	1923	-	Sep	lastSun	2:00	0	S
Rule	Edm	1942	only	-	Feb	 9	2:00	1:00	W # War
Rule	Edm	1945	only	-	Aug	14	23:00u	1:00	P # Peace
Rule	Edm	1945	only	-	Sep	lastSun	2:00	0	S
Rule	Edm	1947	only	-	Apr	lastSun	2:00	1:00	D
Rule	Edm	1947	only	-	Sep	lastSun	2:00	0	S
Rule	Edm	1967	only	-	Apr	lastSun	2:00	1:00	D
Rule	Edm	1967	only	-	Oct	lastSun	2:00	0	S
Rule	Edm	1969	only	-	Apr	lastSun	2:00	1:00	D
Rule	Edm	1969	only	-	Oct	lastSun	2:00	0	S
Rule	Edm	1972	1986	-	Apr	lastSun	2:00	1:00	D
Rule	Edm	1972	2006	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Edmonton	-7:33:52 -	LMT	1906 Sep
			-7:00	Edm	M%sT	1987
			-7:00	Canada	M%sT


# British Columbia

# From Paul Eggert (2006-03-22):
# Shanks & Pottenger write that since 1970 most of this region has
# been like Vancouver.
# Dawson Creek uses MST.  Much of east BC is like Edmonton.
# Matthews and Vincent (1998) write that Creston is like Dawson Creek.

# It seems though that (re: Creston) is not entirely correct:

# From Chris Walton (2011-12-01):
# There are two areas within the Canadian province of British Columbia
# that do not currently observe daylight saving:
# a) The Creston Valley (includes the town of Creston and surrounding area)
# b) The eastern half of the Peace River Regional District
# (includes the cities of Dawson Creek and Fort St. John)

# Earlier this year I stumbled across a detailed article about the time
# keeping history of Creston; it was written by Tammy Hardwick who is the
# manager of the Creston & District Museum. The article was written in May 2009.
# 
# http://www.ilovecreston.com/?p=articles&t=spec&ar=260
# 
# According to the article, Creston has not changed its clocks since June 1918.
# i.e. Creston has been stuck on UTC-7 for 93 years.
# Dawson Creek, on the other hand, changed its clocks as recently as April 1972.

# Unfortunately the exact date for the time change in June 1918 remains
# unknown and will be difficult to ascertain.  I e-mailed Tammy a few months
# ago to ask if Sunday June 2 was a reasonable guess.  She said it was just
# as plausible as any other date (in June).  She also said that after writing the
# article she had discovered another time change in 1916; this is the subject
# of another article which she wrote in October 2010.
# 
# http://www.creston.museum.bc.ca/index.php?module=comments&uop=view_comment&cm+id=56
# 

# Here is a summary of the three clock change events in Creston's history:
# 1. 1884 or 1885: adoption of Mountain Standard Time (GMT-7)
# Exact date unknown
# 2. Oct 1916: switch to Pacific Standard Time (GMT-8)
# Exact date in October unknown;  Sunday October 1 is a reasonable guess.
# 3. June 1918: switch to Pacific Daylight Time (GMT-7)
# Exact date in June unknown; Sunday June 2 is a reasonable guess.
# note#1:
# On Oct 27/1918 when daylight saving ended in the rest of Canada,
# Creston did not change its clocks.
# note#2:
# During WWII when the Federal Government legislated a mandatory clock change,
# Creston did not oblige.
# note#3:
# There is no guarantee that Creston will remain on Mountain Standard Time
# (UTC-7) forever.
# The subject was debated at least once this year by the town Council.
# 
# http://www.bclocalnews.com/kootenay_rockies/crestonvalleyadvance/news/116760809.html
# 

# During a period WWII, summer time (Daylight saying) was mandatory in Canada.
# In Creston, that was handled by shifting the area to PST (-8:00) then applying
# summer time to cause the offset to be -7:00, the same as it had been before
# the change.  It can be argued that the timezone abbreviation during this
# period should be PDT rather than MST, but that doesn't seem important enough
# (to anyone) to further complicate the rules.

# The transition dates (and times) are guesses.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Vanc	1918	only	-	Apr	14	2:00	1:00	D
Rule	Vanc	1918	only	-	Oct	27	2:00	0	S
Rule	Vanc	1942	only	-	Feb	 9	2:00	1:00	W # War
Rule	Vanc	1945	only	-	Aug	14	23:00u	1:00	P # Peace
Rule	Vanc	1945	only	-	Sep	30	2:00	0	S
Rule	Vanc	1946	1986	-	Apr	lastSun	2:00	1:00	D
Rule	Vanc	1946	only	-	Oct	13	2:00	0	S
Rule	Vanc	1947	1961	-	Sep	lastSun	2:00	0	S
Rule	Vanc	1962	2006	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Vancouver	-8:12:28 -	LMT	1884
			-8:00	Vanc	P%sT	1987
			-8:00	Canada	P%sT
Zone America/Dawson_Creek -8:00:56 -	LMT	1884
			-8:00	Canada	P%sT	1947
			-8:00	Vanc	P%sT	1972 Aug 30 2:00
			-7:00	-	MST
Zone America/Creston	-7:46:04 -	LMT	1884
			-7:00	-	MST	1916 Oct 1
			-8:00	-	PST	1918 Jun 2
			-7:00	-	MST

# Northwest Territories, Nunavut, Yukon

# From Paul Eggert (2006-03-22):
# Dawson switched to PST in 1973.  Inuvik switched to MST in 1979.
# Mathew Englander (1996-10-07) gives the following refs:
#	* 1967. Paragraph 28(34)(g) of the Interpretation Act, S.C. 1967-68,
#	c. 7 defines Yukon standard time as UTC-9.  This is still valid;
#	see Interpretation Act, R.S.C. 1985, c. I-21, s. 35(1).
#	* C.O. 1973/214 switched Yukon to PST on 1973-10-28 00:00.
#	* O.I.C. 1980/02 established DST.
#	* O.I.C. 1987/056 changed DST to Apr firstSun 2:00 to Oct lastSun 2:00.
# Shanks & Pottenger say Yukon's 1973-10-28 switch was at 2:00; go
# with Englander.
# From Chris Walton (2006-06-26):
# Here is a link to the old daylight saving portion of the interpretation
# act which was last updated in 1987:
# http://www.gov.yk.ca/legislation/regs/oic1987_056.pdf

# From Rives McDow (1999-09-04):
# Nunavut ... moved ... to incorporate the whole territory into one time zone.
# 
# Nunavut moves to single time zone Oct. 31
# 
#
# From Antoine Leca (1999-09-06):
# We then need to create a new timezone for the Kitikmeot region of Nunavut
# to differentiate it from the Yellowknife region.

# From Paul Eggert (1999-09-20):
# 
# Basic Facts: The New Territory
#  (1999) reports that Pangnirtung operates on eastern time,
# and that Coral Harbour does not observe DST.  We don't know when
# Pangnirtung switched to eastern time; we'll guess 1995.

# From Rives McDow (1999-11-08):
# On October 31, when the rest of Nunavut went to Central time,
# Pangnirtung wobbled.  Here is the result of their wobble:
#
# The following businesses and organizations in Pangnirtung use Central Time:
#
#	First Air, Power Corp, Nunavut Construction, Health Center, RCMP,
#	Eastern Arctic National Parks, A & D Specialist
#
# The following businesses and organizations in Pangnirtung use Eastern Time:
#
#	Hamlet office, All other businesses, Both schools, Airport operator
#
# This has made for an interesting situation there, which warranted the news.
# No one there that I spoke with seems concerned, or has plans to
# change the local methods of keeping time, as it evidently does not
# really interfere with any activities or make things difficult locally.
# They plan to celebrate New Year's turn-over twice, one hour apart,
# so it appears that the situation will last at least that long.
# The Nunavut Intergovernmental Affairs hopes that they will "come to
# their senses", but the locals evidently don't see any problem with
# the current state of affairs.

# From Michaela Rodrigue, writing in the
# 
# Nunatsiaq News (1999-11-19):
# Clyde River, Pangnirtung and Sanikiluaq now operate with two time zones,
# central - or Nunavut time - for government offices, and eastern time
# for municipal offices and schools....  Igloolik [was similar but then]
# made the switch to central time on Saturday, Nov. 6.

# From Paul Eggert (2000-10-02):
# Matthews and Vincent (1998) say the following, but we lack histories
# for these potential new Zones.
#
# The Canadian Forces station at Alert uses Eastern Time while the
# handful of residents at the Eureka weather station [in the Central
# zone] skip daylight savings.  Baffin Island, which is crossed by the
# Central, Eastern and Atlantic Time zones only uses Eastern Time.
# Gjoa Haven, Taloyoak and Pelly Bay all use Mountain instead of
# Central Time and Southampton Island [in the Central zone] is not
# required to use daylight savings.

# From
# 
# Nunavut now has two time zones
#  (2000-11-10):
# The Nunavut government would allow its employees in Kugluktuk and
# Cambridge Bay to operate on central time year-round, putting them
# one hour behind the rest of Nunavut for six months during the winter.
# At the end of October the two communities had rebelled against
# Nunavut's unified time zone, refusing to shift to eastern time with
# the rest of the territory for the winter.  Cambridge Bay remained on
# central time, while Kugluktuk, even farther west, reverted to
# mountain time, which they had used before the advent of Nunavut's
# unified time zone in 1999.
#
# From Rives McDow (2001-01-20), quoting the Nunavut government:
# The preceding decision came into effect at midnight, Saturday Nov 4, 2000.

# From Paul Eggert (2000-12-04):
# Let's just keep track of the official times for now.

# From Rives McDow (2001-03-07):
# The premier of Nunavut has issued a ministerial statement advising
# that effective 2001-04-01, the territory of Nunavut will revert
# back to three time zones (mountain, central, and eastern).  Of the
# cities in Nunavut, Coral Harbor is the only one that I know of that
# has said it will not observe dst, staying on EST year round.  I'm
# checking for more info, and will get back to you if I come up with
# more.
# [Also see  (2001-03-09).]

# From Gwillim Law (2005-05-21):
# According to maps at
# http://inms-ienm.nrc-cnrc.gc.ca/images/time_services/TZ01SWE.jpg
# http://inms-ienm.nrc-cnrc.gc.ca/images/time_services/TZ01SSE.jpg
# (both dated 2003), and
# http://www.canadiangeographic.ca/Magazine/SO98/geomap.asp
# (from a 1998 Canadian Geographic article), the de facto and de jure time
# for Southampton Island (at the north end of Hudson Bay) is UTC-5 all year
# round.  Using Google, it's easy to find other websites that confirm this.
# I wasn't able to find how far back this time regimen goes, but since it
# predates the creation of Nunavut, it probably goes back many years....
# The Inuktitut name of Coral Harbour is Sallit, but it's rarely used.
#
# From Paul Eggert (2005-07-26):
# For lack of better information, assume that Southampton Island observed
# daylight saving only during wartime.

# From Chris Walton (2007-03-01):
# ... the community of Resolute (located on Cornwallis Island in
# Nunavut) moved from Central Time to Eastern Time last November.
# Basically the community did not change its clocks at the end of
# daylight saving....
# http://www.nnsl.com/frames/newspapers/2006-11/nov13_06none.html

# From Chris Walton (2011-03-21):
# Back in 2007 I initiated the creation of a new "zone file" for Resolute
# Bay. Resolute Bay is a small community located about 900km north of
# the Arctic Circle. The zone file was required because Resolute Bay had
# decided to use UTC-5 instead of UTC-6 for the winter of 2006-2007.
#
# According to new information which I received last week, Resolute Bay
# went back to using UTC-6 in the winter of 2007-2008...
#
# On March 11/2007 most of Canada went onto daylight saving. On March
# 14/2007 I phoned the Resolute Bay hamlet office to do a "time check." I
# talked to somebody that was both knowledgeable and helpful. I was able
# to confirm that Resolute Bay was still operating on UTC-5. It was
# explained to me that Resolute Bay had been on the Eastern Time zone
# (EST) in the winter, and was now back on the Central Time zone (CDT).
# i.e. the time zone had changed twice in the last year but the clocks
# had not moved. The residents had to know which time zone they were in
# so they could follow the correct TV schedule...
#
# On Nov 02/2008 most of Canada went onto standard time. On Nov 03/2008 I
# phoned the Resolute Bay hamlet office...[D]ue to the challenging nature
# of the phone call, I decided to seek out an alternate source of
# information. I found an e-mail address for somebody by the name of
# Stephanie Adams whose job was listed as "Inns North Support Officer for
# Arctic Co-operatives." I was under the impression that Stephanie lived
# and worked in Resolute Bay...
#
# On March 14/2011 I phoned the hamlet office again. I was told that
# Resolute Bay had been using Central Standard Time over the winter of
# 2010-2011 and that the clocks had therefore been moved one hour ahead
# on March 13/2011. The person I talked to was aware that Resolute Bay
# had previously experimented with Eastern Standard Time but he could not
# tell me when the practice had stopped.
#
# On March 17/2011 I searched the Web to find an e-mail address of
# somebody that might be able to tell me exactly when Resolute Bay went
# off Eastern Standard Time. I stumbled on the name "Aziz Kheraj." Aziz
# used to be the mayor of Resolute Bay and he apparently owns half the
# businesses including "South Camp Inn." This website has some info on
# Aziz:
# 
# http://www.uphere.ca/node/493
# 
#
# I sent Aziz an e-mail asking when Resolute Bay had stopped using
# Eastern Standard Time.
#
# Aziz responded quickly with this: "hi, The time was not changed for the
# 1 year only, the following year, the community went back to the old way
# of "spring ahead-fall behind" currently we are zulu plus 5 hrs and in
# the winter Zulu plus 6 hrs"
#
# This of course conflicted with everything I had ascertained in November 2008.
#
# I sent Aziz a copy of my 2008 e-mail exchange with Stephanie. Aziz
# responded with this: "Hi, Stephanie lives in Winnipeg. I live here, You
# may want to check with the weather office in Resolute Bay or do a
# search on the weather through Env. Canada. web site"
#
# If I had realized the Stephanie did not live in Resolute Bay I would
# never have contacted her.  I now believe that all the information I
# obtained in November 2008 should be ignored...
# I apologize for reporting incorrect information in 2008.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	NT_YK	1918	only	-	Apr	14	2:00	1:00	D
Rule	NT_YK	1918	only	-	Oct	27	2:00	0	S
Rule	NT_YK	1919	only	-	May	25	2:00	1:00	D
Rule	NT_YK	1919	only	-	Nov	 1	0:00	0	S
Rule	NT_YK	1942	only	-	Feb	 9	2:00	1:00	W # War
Rule	NT_YK	1945	only	-	Aug	14	23:00u	1:00	P # Peace
Rule	NT_YK	1945	only	-	Sep	30	2:00	0	S
Rule	NT_YK	1965	only	-	Apr	lastSun	0:00	2:00	DD
Rule	NT_YK	1965	only	-	Oct	lastSun	2:00	0	S
Rule	NT_YK	1980	1986	-	Apr	lastSun	2:00	1:00	D
Rule	NT_YK	1980	2006	-	Oct	lastSun	2:00	0	S
Rule	NT_YK	1987	2006	-	Apr	Sun>=1	2:00	1:00	D
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# aka Panniqtuuq
Zone America/Pangnirtung 0	-	zzz	1921 # trading post est.
			-4:00	NT_YK	A%sT	1995 Apr Sun>=1 2:00
			-5:00	Canada	E%sT	1999 Oct 31 2:00
			-6:00	Canada	C%sT	2000 Oct 29 2:00
			-5:00	Canada	E%sT
# formerly Frobisher Bay
Zone America/Iqaluit	0	-	zzz	1942 Aug # Frobisher Bay est.
			-5:00	NT_YK	E%sT	1999 Oct 31 2:00
			-6:00	Canada	C%sT	2000 Oct 29 2:00
			-5:00	Canada	E%sT
# aka Qausuittuq
Zone America/Resolute	0	-	zzz	1947 Aug 31 # Resolute founded
			-6:00	NT_YK	C%sT	2000 Oct 29 2:00
			-5:00	-	EST	2001 Apr  1 3:00
			-6:00	Canada	C%sT	2006 Oct 29 2:00
			-5:00	-	EST	2007 Mar 11 3:00
			-6:00	Canada	C%sT
# aka Kangiqiniq
Zone America/Rankin_Inlet 0	-	zzz	1957 # Rankin Inlet founded
			-6:00	NT_YK	C%sT	2000 Oct 29 2:00
			-5:00	-	EST	2001 Apr  1 3:00
			-6:00	Canada	C%sT
# aka Iqaluktuuttiaq
Zone America/Cambridge_Bay 0	-	zzz	1920 # trading post est.?
			-7:00	NT_YK	M%sT	1999 Oct 31 2:00
			-6:00	Canada	C%sT	2000 Oct 29 2:00
			-5:00	-	EST	2000 Nov  5 0:00
			-6:00	-	CST	2001 Apr  1 3:00
			-7:00	Canada	M%sT
Zone America/Yellowknife 0	-	zzz	1935 # Yellowknife founded?
			-7:00	NT_YK	M%sT	1980
			-7:00	Canada	M%sT
Zone America/Inuvik	0	-	zzz	1953 # Inuvik founded
			-8:00	NT_YK	P%sT	1979 Apr lastSun 2:00
			-7:00	NT_YK	M%sT	1980
			-7:00	Canada	M%sT
Zone America/Whitehorse	-9:00:12 -	LMT	1900 Aug 20
			-9:00	NT_YK	Y%sT	1966 Jul 1 2:00
			-8:00	NT_YK	P%sT	1980
			-8:00	Canada	P%sT
Zone America/Dawson	-9:17:40 -	LMT	1900 Aug 20
			-9:00	NT_YK	Y%sT	1973 Oct 28 0:00
			-8:00	NT_YK	P%sT	1980
			-8:00	Canada	P%sT


###############################################################################

# Mexico

# From Paul Eggert (2001-03-05):
# The Investigation and Analysis Service of the
# Mexican Library of Congress (MLoC) has published a
# 
# history of Mexican local time (in Spanish)
# .
#
# Here are the discrepancies between Shanks & Pottenger (S&P) and the MLoC.
# (In all cases we go with the MLoC.)
# S&P report that Baja was at -8:00 in 1922/1923.
# S&P say the 1930 transition in Baja was 1930-11-16.
# S&P report no DST during summer 1931.
# S&P report a transition at 1932-03-30 23:00, not 1932-04-01.

# From Gwillim Law (2001-02-20):
# There are some other discrepancies between the Decrees page and the
# tz database.  I think they can best be explained by supposing that
# the researchers who prepared the Decrees page failed to find some of
# the relevant documents.

# From Alan Perry (1996-02-15):
# A guy from our Mexico subsidiary finally found the Presidential Decree
# outlining the timezone changes in Mexico.
#
# ------------- Begin Forwarded Message -------------
#
# I finally got my hands on the Official Presidential Decree that sets up the
# rules for the DST changes. The rules are:
#
# 1. The country is divided in 3 timezones:
#    - Baja California Norte (the Mexico/BajaNorte TZ)
#    - Baja California Sur, Nayarit, Sinaloa and Sonora (the Mexico/BajaSur TZ)
#    - The rest of the country (the Mexico/General TZ)
#
# 2. From the first Sunday in April at 2:00 AM to the last Sunday in October
#    at 2:00 AM, the times in each zone are as follows:
#    BajaNorte: GMT+7
#    BajaSur:   GMT+6
#    General:   GMT+5
#
# 3. The rest of the year, the times are as follows:
#    BajaNorte: GMT+8
#    BajaSur:   GMT+7
#    General:   GMT+6
#
# The Decree was published in Mexico's Official Newspaper on January 4th.
#
# -------------- End Forwarded Message --------------
# From Paul Eggert (1996-06-12):
# For an English translation of the decree, see
# 
# ``Diario Oficial: Time Zone Changeover'' (1996-01-04).
# 

# From Rives McDow (1998-10-08):
# The State of Quintana Roo has reverted back to central STD and DST times
# (i.e. UTC -0600 and -0500 as of 1998-08-02).

# From Rives McDow (2000-01-10):
# Effective April 4, 1999 at 2:00 AM local time, Sonora changed to the time
# zone 5 hours from the International Date Line, and will not observe daylight
# savings time so as to stay on the same time zone as the southern part of
# Arizona year round.

# From Jesper Norgaard, translating
#  (2001-01-17):
# In Oaxaca, the 55.000 teachers from the Section 22 of the National
# Syndicate of Education Workers, refuse to apply daylight saving each
# year, so that the more than 10,000 schools work at normal hour the
# whole year.

# From Gwillim Law (2001-01-19):
#  ... says
# (translated):...
# January 17, 2000 - The Energy Secretary, Ernesto Martens, announced
# that Summer Time will be reduced from seven to five months, starting
# this year....
# 
# [translated], says "summer time will ... take effect on the first Sunday
# in May, and end on the last Sunday of September.

# From Arthur David Olson (2001-01-25):
# The 2001-01-24 traditional Washington Post contained the page one
# story "Timely Issue Divides Mexicans."...
# http://www.washingtonpost.com/wp-dyn/articles/A37383-2001Jan23.html
# ... Mexico City Mayor Lopez Obrador "...is threatening to keep
# Mexico City and its 20 million residents on a different time than
# the rest of the country..." In particular, Lopez Obrador would abolish
# observation of Daylight Saving Time.

# 
# Official statute published by the Energy Department
#  (2001-02-01) shows Baja and Chihauhua as still using US DST rules,
# and Sonora with no DST.  This was reported by Jesper Norgaard (2001-02-03).

# From Paul Eggert (2001-03-03):
#
# 
# James F. Smith writes in today's LA Times
# 
# * Sonora will continue to observe standard time.
# * Last week Mexico City's mayor Andres Manuel Lopez Obrador decreed that
#   the Federal District will not adopt DST.
# * 4 of 16 district leaders announced they'll ignore the decree.
# * The decree does not affect federal-controlled facilities including
#   the airport, banks, hospitals, and schools.
#
# For now we'll assume that the Federal District will bow to federal rules.

# From Jesper Norgaard (2001-04-01):
# I found some references to the Mexican application of daylight
# saving, which modifies what I had already sent you, stating earlier
# that a number of northern Mexican states would go on daylight
# saving. The modification reverts this to only cover Baja California
# (Norte), while all other states (except Sonora, who has no daylight
# saving all year) will follow the original decree of president
# Vicente Fox, starting daylight saving May 6, 2001 and ending
# September 30, 2001.
# References: "Diario de Monterrey" 
# Palabra  (2001-03-31)

# From Reuters (2001-09-04):
# Mexico's Supreme Court on Tuesday declared that daylight savings was
# unconstitutional in Mexico City, creating the possibility the
# capital will be in a different time zone from the rest of the nation
# next year....  The Supreme Court's ruling takes effect at 2:00
# a.m. (0800 GMT) on Sept. 30, when Mexico is scheduled to revert to
# standard time. "This is so residents of the Federal District are not
# subject to unexpected time changes," a statement from the court said.

# From Jesper Norgaard Welen (2002-03-12):
# ... consulting my local grocery store(!) and my coworkers, they all insisted
# that a new decision had been made to reinstate US style DST in Mexico....
# http://www.conae.gob.mx/ahorro/horaver2001_m1_2002.html (2002-02-20)
# confirms this.  Sonora as usual is the only state where DST is not applied.

# From Steffen Thorsen (2009-12-28):
#
# Steffen Thorsen wrote:
# > Mexico's House of Representatives has approved a proposal for northern
# > Mexico's border cities to share the same daylight saving schedule as
# > the United States.
# Now this has passed both the Congress and the Senate, so starting from
# 2010, some border regions will be the same:
# 
# http://www.signonsandiego.com/news/2009/dec/28/clocks-will-match-both-sides-border/
# 
# 
# http://www.elmananarey.com/diario/noticia/nacional/noticias/empatan_horario_de_frontera_con_eu/621939
# 
# (Spanish)
#
# Could not find the new law text, but the proposed law text changes are here:
# 
# http://gaceta.diputados.gob.mx/Gaceta/61/2009/dic/20091210-V.pdf
# 
# (Gaceta Parlamentaria)
#
# There is also a list of the votes here:
# 
# http://gaceta.diputados.gob.mx/Gaceta/61/2009/dic/V2-101209.html
# 
#
# Our page:
# 
# http://www.timeanddate.com/news/time/north-mexico-dst-change.html
# 

# From Arthur David Olson (2010-01-20):
# The page
# 
# http://dof.gob.mx/nota_detalle.php?codigo=5127480&fecha=06/01/2010
# 
# includes this text:
# En los municipios fronterizos de Tijuana y Mexicali en Baja California;
# Juárez y Ojinaga en Chihuahua; Acuña y Piedras Negras en Coahuila;
# Anáhuac en Nuevo León; y Nuevo Laredo, Reynosa y Matamoros en
# Tamaulipas, la aplicación de este horario estacional surtirá efecto
# desde las dos horas del segundo domingo de marzo y concluirá a las dos
# horas del primer domingo de noviembre.
# En los municipios fronterizos que se encuentren ubicados en la franja
# fronteriza norte en el territorio comprendido entre la línea
# internacional y la línea paralela ubicada a una distancia de veinte
# kilómetros, así como la Ciudad de Ensenada, Baja California, hacia el
# interior del país, la aplicación de este horario estacional surtirá
# efecto desde las dos horas del segundo domingo de marzo y concluirá a
# las dos horas del primer domingo de noviembre.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Mexico	1939	only	-	Feb	5	0:00	1:00	D
Rule	Mexico	1939	only	-	Jun	25	0:00	0	S
Rule	Mexico	1940	only	-	Dec	9	0:00	1:00	D
Rule	Mexico	1941	only	-	Apr	1	0:00	0	S
Rule	Mexico	1943	only	-	Dec	16	0:00	1:00	W # War
Rule	Mexico	1944	only	-	May	1	0:00	0	S
Rule	Mexico	1950	only	-	Feb	12	0:00	1:00	D
Rule	Mexico	1950	only	-	Jul	30	0:00	0	S
Rule	Mexico	1996	2000	-	Apr	Sun>=1	2:00	1:00	D
Rule	Mexico	1996	2000	-	Oct	lastSun	2:00	0	S
Rule	Mexico	2001	only	-	May	Sun>=1	2:00	1:00	D
Rule	Mexico	2001	only	-	Sep	lastSun	2:00	0	S
Rule	Mexico	2002	max	-	Apr	Sun>=1	2:00	1:00	D
Rule	Mexico	2002	max	-	Oct	lastSun	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# Quintana Roo
Zone America/Cancun	-5:47:04 -	LMT	1922 Jan  1  0:12:56
			-6:00	-	CST	1981 Dec 23
			-5:00	Mexico	E%sT	1998 Aug  2  2:00
			-6:00	Mexico	C%sT
# Campeche, Yucatan
Zone America/Merida	-5:58:28 -	LMT	1922 Jan  1  0:01:32
			-6:00	-	CST	1981 Dec 23
			-5:00	-	EST	1982 Dec  2
			-6:00	Mexico	C%sT
# Coahuila, Durango, Nuevo Leon, Tamaulipas (near US border)
Zone America/Matamoros	-6:40:00 -	LMT	1921 Dec 31 23:20:00
			-6:00	-	CST	1988
			-6:00	US	C%sT	1989
			-6:00	Mexico	C%sT	2010
			-6:00	US	C%sT
# Coahuila, Durango, Nuevo Leon, Tamaulipas (away from US border)
Zone America/Monterrey	-6:41:16 -	LMT	1921 Dec 31 23:18:44
			-6:00	-	CST	1988
			-6:00	US	C%sT	1989
			-6:00	Mexico	C%sT
# Central Mexico
Zone America/Mexico_City -6:36:36 -	LMT	1922 Jan  1 0:23:24
			-7:00	-	MST	1927 Jun 10 23:00
			-6:00	-	CST	1930 Nov 15
			-7:00	-	MST	1931 May  1 23:00
			-6:00	-	CST	1931 Oct
			-7:00	-	MST	1932 Apr  1
			-6:00	Mexico	C%sT	2001 Sep 30 02:00
			-6:00	-	CST	2002 Feb 20
			-6:00	Mexico	C%sT
# Chihuahua (near US border)
Zone America/Ojinaga	-6:57:40 -	LMT	1922 Jan 1 0:02:20
			-7:00	-	MST	1927 Jun 10 23:00
			-6:00	-	CST	1930 Nov 15
			-7:00	-	MST	1931 May  1 23:00
			-6:00	-	CST	1931 Oct
			-7:00	-	MST	1932 Apr  1
			-6:00	-	CST	1996
			-6:00	Mexico	C%sT	1998
			-6:00	-	CST	1998 Apr Sun>=1 3:00
			-7:00	Mexico	M%sT	2010
			-7:00	US	M%sT
# Chihuahua (away from US border)
Zone America/Chihuahua	-7:04:20 -	LMT	1921 Dec 31 23:55:40
			-7:00	-	MST	1927 Jun 10 23:00
			-6:00	-	CST	1930 Nov 15
			-7:00	-	MST	1931 May  1 23:00
			-6:00	-	CST	1931 Oct
			-7:00	-	MST	1932 Apr  1
			-6:00	-	CST	1996
			-6:00	Mexico	C%sT	1998
			-6:00	-	CST	1998 Apr Sun>=1 3:00
			-7:00	Mexico	M%sT
# Sonora
Zone America/Hermosillo	-7:23:52 -	LMT	1921 Dec 31 23:36:08
			-7:00	-	MST	1927 Jun 10 23:00
			-6:00	-	CST	1930 Nov 15
			-7:00	-	MST	1931 May  1 23:00
			-6:00	-	CST	1931 Oct
			-7:00	-	MST	1932 Apr  1
			-6:00	-	CST	1942 Apr 24
			-7:00	-	MST	1949 Jan 14
			-8:00	-	PST	1970
			-7:00	Mexico	M%sT	1999
			-7:00	-	MST

# From Alexander Krivenyshev (2010-04-21):
# According to news, Bahía de Banderas (Mexican state of Nayarit)
# changed time zone UTC-7 to new time zone UTC-6 on April 4, 2010 (to
# share the same time zone as nearby city Puerto Vallarta, Jalisco).
#
# (Spanish)
# Bahía de Banderas homologa su horario al del centro del
# país, a partir de este domingo
# 
# http://www.nayarit.gob.mx/notes.asp?id=20748
# 
#
# Bahía de Banderas homologa su horario con el del Centro del
# País
# 
# http://www.bahiadebanderas.gob.mx/principal/index.php?option=com_content&view=article&id=261:bahia-de-banderas-homologa-su-horario-con-el-del-centro-del-pais&catid=42:comunicacion-social&Itemid=50"
# 
#
# (English)
# Puerto Vallarta and Bahía de Banderas: One Time Zone
# 
# http://virtualvallarta.com/puertovallarta/puertovallarta/localnews/2009-12-03-Puerto-Vallarta-and-Bahia-de-Banderas-One-Time-Zone.shtml
# 
#
# or
# 
# http://www.worldtimezone.com/dst_news/dst_news_mexico08.html
# 
#
# "Mexico's Senate approved the amendments to the Mexican Schedule System that
# will allow Bahía de Banderas and Puerto Vallarta to share the same time
# zone ..."
# Baja California Sur, Nayarit, Sinaloa

# From Arthur David Olson (2010-05-01):
# Use "Bahia_Banderas" to keep the name to fourteen characters.

Zone America/Mazatlan	-7:05:40 -	LMT	1921 Dec 31 23:54:20
			-7:00	-	MST	1927 Jun 10 23:00
			-6:00	-	CST	1930 Nov 15
			-7:00	-	MST	1931 May  1 23:00
			-6:00	-	CST	1931 Oct
			-7:00	-	MST	1932 Apr  1
			-6:00	-	CST	1942 Apr 24
			-7:00	-	MST	1949 Jan 14
			-8:00	-	PST	1970
			-7:00	Mexico	M%sT

Zone America/Bahia_Banderas	-7:01:00 -	LMT	1921 Dec 31 23:59:00
			-7:00	-	MST	1927 Jun 10 23:00
			-6:00	-	CST	1930 Nov 15
			-7:00	-	MST	1931 May  1 23:00
			-6:00	-	CST	1931 Oct
			-7:00	-	MST	1932 Apr  1
			-6:00	-	CST	1942 Apr 24
			-7:00	-	MST	1949 Jan 14
			-8:00	-	PST	1970
			-7:00	Mexico	M%sT	2010 Apr 4 2:00
			-6:00	Mexico	C%sT

# Baja California (near US border)
Zone America/Tijuana	-7:48:04 -	LMT	1922 Jan  1  0:11:56
			-7:00	-	MST	1924
			-8:00	-	PST	1927 Jun 10 23:00
			-7:00	-	MST	1930 Nov 15
			-8:00	-	PST	1931 Apr  1
			-8:00	1:00	PDT	1931 Sep 30
			-8:00	-	PST	1942 Apr 24
			-8:00	1:00	PWT	1945 Aug 14 23:00u
			-8:00	1:00	PPT	1945 Nov 12 # Peace
			-8:00	-	PST	1948 Apr  5
			-8:00	1:00	PDT	1949 Jan 14
			-8:00	-	PST	1954
			-8:00	CA	P%sT	1961
			-8:00	-	PST	1976
			-8:00	US	P%sT	1996
			-8:00	Mexico	P%sT	2001
			-8:00	US	P%sT	2002 Feb 20
			-8:00	Mexico	P%sT	2010
			-8:00	US	P%sT
# Baja California (away from US border)
Zone America/Santa_Isabel	-7:39:28 -	LMT	1922 Jan  1  0:20:32
			-7:00	-	MST	1924
			-8:00	-	PST	1927 Jun 10 23:00
			-7:00	-	MST	1930 Nov 15
			-8:00	-	PST	1931 Apr  1
			-8:00	1:00	PDT	1931 Sep 30
			-8:00	-	PST	1942 Apr 24
			-8:00	1:00	PWT	1945 Aug 14 23:00u
			-8:00	1:00	PPT	1945 Nov 12 # Peace
			-8:00	-	PST	1948 Apr  5
			-8:00	1:00	PDT	1949 Jan 14
			-8:00	-	PST	1954
			-8:00	CA	P%sT	1961
			-8:00	-	PST	1976
			-8:00	US	P%sT	1996
			-8:00	Mexico	P%sT	2001
			-8:00	US	P%sT	2002 Feb 20
			-8:00	Mexico	P%sT
# From Paul Eggert (2006-03-22):
# Formerly there was an America/Ensenada zone, which differed from
# America/Tijuana only in that it did not observe DST from 1976
# through 1995.  This was as per Shanks (1999).  But Shanks & Pottenger say
# Ensenada did not observe DST from 1948 through 1975.  Guy Harris reports
# that the 1987 OAG says "Only Ensenada, Mexicale, San Felipe and
# Tijuana observe DST," which agrees with Shanks & Pottenger but implies that
# DST-observance was a town-by-town matter back then.  This concerns
# data after 1970 so most likely there should be at least one Zone
# other than America/Tijuana for Baja, but it's not clear yet what its
# name or contents should be.
#
# Revillagigedo Is
# no information

###############################################################################

# Anguilla
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Anguilla	-4:12:16 -	LMT	1912 Mar 2
			-4:00	-	AST

# Antigua and Barbuda
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Antigua	-4:07:12 -	LMT	1912 Mar 2
			-5:00	-	EST	1951
			-4:00	-	AST

# Bahamas
#
# For 1899 Milne gives -5:09:29.5; round that.
#
# From Sue Williams (2006-12-07):
# The Bahamas announced about a month ago that they plan to change their DST
# rules to sync with the U.S. starting in 2007....
# http://www.jonesbahamas.com/?c=45&a=10412

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Bahamas	1964	1975	-	Oct	lastSun	2:00	0	S
Rule	Bahamas	1964	1975	-	Apr	lastSun	2:00	1:00	D
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Nassau	-5:09:30 -	LMT	1912 Mar 2
			-5:00	Bahamas	E%sT	1976
			-5:00	US	E%sT

# Barbados

# For 1899 Milne gives -3:58:29.2; round that.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Barb	1977	only	-	Jun	12	2:00	1:00	D
Rule	Barb	1977	1978	-	Oct	Sun>=1	2:00	0	S
Rule	Barb	1978	1980	-	Apr	Sun>=15	2:00	1:00	D
Rule	Barb	1979	only	-	Sep	30	2:00	0	S
Rule	Barb	1980	only	-	Sep	25	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Barbados	-3:58:29 -	LMT	1924		# Bridgetown
			-3:58:29 -	BMT	1932	  # Bridgetown Mean Time
			-4:00	Barb	A%sT

# Belize
# Whitman entirely disagrees with Shanks; go with Shanks & Pottenger.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Belize	1918	1942	-	Oct	Sun>=2	0:00	0:30	HD
Rule	Belize	1919	1943	-	Feb	Sun>=9	0:00	0	S
Rule	Belize	1973	only	-	Dec	 5	0:00	1:00	D
Rule	Belize	1974	only	-	Feb	 9	0:00	0	S
Rule	Belize	1982	only	-	Dec	18	0:00	1:00	D
Rule	Belize	1983	only	-	Feb	12	0:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Belize	-5:52:48 -	LMT	1912 Apr
			-6:00	Belize	C%sT

# Bermuda

# For 1899 Milne gives -4:19:18.3 as the meridian of the clock tower,
# Bermuda dockyard, Ireland I; round that.

# From Dan Jones, reporting in The Royal Gazette (2006-06-26):

# Next year, however, clocks in the US will go forward on the second Sunday
# in March, until the first Sunday in November.  And, after the Time Zone
# (Seasonal Variation) Bill 2006 was passed in the House of Assembly on
# Friday, the same thing will happen in Bermuda.
# http://www.theroyalgazette.com/apps/pbcs.dll/article?AID=/20060529/NEWS/105290135

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Atlantic/Bermuda	-4:19:18 -	LMT	1930 Jan  1 2:00    # Hamilton
			-4:00	-	AST	1974 Apr 28 2:00
			-4:00	Bahamas	A%sT	1976
			-4:00	US	A%sT

# Cayman Is
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Cayman	-5:25:32 -	LMT	1890		# Georgetown
			-5:07:12 -	KMT	1912 Feb    # Kingston Mean Time
			-5:00	-	EST

# Costa Rica

# Milne gives -5:36:13.3 as San Jose mean time; round to nearest.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	CR	1979	1980	-	Feb	lastSun	0:00	1:00	D
Rule	CR	1979	1980	-	Jun	Sun>=1	0:00	0	S
Rule	CR	1991	1992	-	Jan	Sat>=15	0:00	1:00	D
# IATA SSIM (1991-09) says the following was at 1:00;
# go with Shanks & Pottenger.
Rule	CR	1991	only	-	Jul	 1	0:00	0	S
Rule	CR	1992	only	-	Mar	15	0:00	0	S
# There are too many San Joses elsewhere, so we'll use `Costa Rica'.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Costa_Rica	-5:36:13 -	LMT	1890		# San Jose
			-5:36:13 -	SJMT	1921 Jan 15 # San Jose Mean Time
			-6:00	CR	C%sT
# Coco
# no information; probably like America/Costa_Rica

# Cuba

# From Paul Eggert (2013-02-21):
# Milne gives -5:28:50.45 for the observatory at Havana, -5:29:23.57
# for the port, and -5:30 for meteorological observations.
# For now, stick with Shanks & Pottenger.

# From Arthur David Olson (1999-03-29):
# The 1999-03-28 exhibition baseball game held in Havana, Cuba, between
# the Cuban National Team and the Baltimore Orioles was carried live on
# the Orioles Radio Network, including affiliate WTOP in Washington, DC.
# During the game, play-by-play announcer Jim Hunter noted that
# "We'll be losing two hours of sleep...Cuba switched to Daylight Saving
# Time today."  (The "two hour" remark referred to losing one hour of
# sleep on 1999-03-28--when the announcers were in Cuba as it switched
# to DST--and one more hour on 1999-04-04--when the announcers will have
# returned to Baltimore, which switches on that date.)

# From Evert van der Veer via Steffen Thorsen (2004-10-28):
# Cuba is not going back to standard time this year.
# From Paul Eggert (2006-03-22):
# http://www.granma.cu/ingles/2004/septiembre/juev30/41medid-i.html
# says that it's due to a problem at the Antonio Guiteras
# thermoelectric plant, and says "This October there will be no return
# to normal hours (after daylight saving time)".
# For now, let's assume that it's a temporary measure.

# From Carlos A. Carnero Delgado (2005-11-12):
# This year (just like in 2004-2005) there's no change in time zone
# adjustment in Cuba.  We will stay in daylight saving time:
# http://www.granma.cu/espanol/2005/noviembre/mier9/horario.html

# From Jesper Norgaard Welen (2006-10-21):
# An article in GRANMA INTERNACIONAL claims that Cuba will end
# the 3 years of permanent DST next weekend, see
# http://www.granma.cu/ingles/2006/octubre/lun16/43horario.html
# "On Saturday night, October 28 going into Sunday, October 29, at 01:00,
# watches should be set back one hour -- going back to 00:00 hours -- returning
# to the normal schedule....

# From Paul Eggert (2007-03-02):
# http://www.granma.cubaweb.cu/english/news/art89.html, dated yesterday,
# says Cuban clocks will advance at midnight on March 10.
# For lack of better information, assume Cuba will use US rules,
# except that it switches at midnight standard time as usual.
#
# From Steffen Thorsen (2007-10-25):
# Carlos Alberto Fonseca Arauz informed me that Cuba will end DST one week
# earlier - on the last Sunday of October, just like in 2006.
#
# He supplied these references:
#
# http://www.prensalatina.com.mx/article.asp?ID=%7B4CC32C1B-A9F7-42FB-8A07-8631AFC923AF%7D&language=ES
# http://actualidad.terra.es/sociedad/articulo/cuba_llama_ahorrar_energia_cambio_1957044.htm
#
# From Alex Kryvenishev (2007-10-25):
# Here is also article from Granma (Cuba):
#
# [Regira] el Horario Normal desde el [proximo] domingo 28 de octubre
# http://www.granma.cubaweb.cu/2007/10/24/nacional/artic07.html
#
# http://www.worldtimezone.com/dst_news/dst_news_cuba03.html

# From Arthur David Olson (2008-03-09):
# I'm in Maryland which is now observing United States Eastern Daylight
# Time. At 9:44 local time I used RealPlayer to listen to
# 
# http://media.enet.cu/radioreloj
# , a Cuban information station, and heard
# the time announced as "ocho cuarenta y cuatro" ("eight forty-four"),
# indicating that Cuba is still on standard time.

# From Steffen Thorsen (2008-03-12):
# It seems that Cuba will start DST on Sunday, 2007-03-16...
# It was announced yesterday, according to this source (in Spanish):
# 
# http://www.nnc.cubaweb.cu/marzo-2008/cien-1-11-3-08.htm
# 
#
# Some more background information is posted here:
# 
# http://www.timeanddate.com/news/time/cuba-starts-dst-march-16.html
# 
#
# The article also says that Cuba has been observing DST since 1963,
# while Shanks (and tzdata) has 1965 as the first date (except in the
# 1940's). Many other web pages in Cuba also claim that it has been
# observed since 1963, but with the exception of 1970 - an exception
# which is not present in tzdata/Shanks. So there is a chance we need to
# change some historic records as well.
#
# One example:
# 
# http://www.radiohc.cu/espanol/noticias/mar07/11mar/hor.htm
# 

# From Jesper Norgaard Welen (2008-03-13):
# The Cuban time change has just been confirmed on the most authoritative
# web site, the Granma.  Please check out
# 
# http://www.granma.cubaweb.cu/2008/03/13/nacional/artic10.html
# 
#
# Basically as expected after Steffen Thorsens information, the change
# will take place midnight between Saturday and Sunday.

# From Arthur David Olson (2008-03-12):
# Assume Sun>=15 (third Sunday) going forward.

# From Alexander Krivenyshev (2009-03-04)
# According to the Radio Reloj - Cuba will start Daylight Saving Time on
# midnight between Saturday, March 07, 2009 and Sunday, March 08, 2009-
# not on midnight March 14 / March 15 as previously thought.
#
# 
# http://www.worldtimezone.com/dst_news/dst_news_cuba05.html
# (in Spanish)
# 

# From Arthur David Olson (2009-03-09)
# I listened over the Internet to
# 
# http://media.enet.cu/readioreloj
# 
# this morning; when it was 10:05 a. m. here in Bethesda, Maryland the
# the time was announced as "diez cinco"--the same time as here, indicating
# that has indeed switched to DST. Assume second Sunday from 2009 forward.

# From Steffen Thorsen (2011-03-08):
# Granma announced that Cuba is going to start DST on 2011-03-20 00:00:00
# this year. Nothing about the end date known so far (if that has
# changed at all).
#
# Source:
# 
# http://granma.co.cu/2011/03/08/nacional/artic01.html
# 
#
# Our info:
# 
# http://www.timeanddate.com/news/time/cuba-starts-dst-2011.html
# 
#
# From Steffen Thorsen (2011-10-30)
# Cuba will end DST two weeks later this year. Instead of going back
# tonight, it has been delayed to 2011-11-13 at 01:00.
#
# One source (Spanish)
# 
# http://www.radioangulo.cu/noticias/cuba/17105-cuba-restablecera-el-horario-del-meridiano-de-greenwich.html
# 
#
# Our page:
# 
# http://www.timeanddate.com/news/time/cuba-time-changes-2011.html
# 
#
# From Steffen Thorsen (2012-03-01)
# According to Radio Reloj, Cuba will start DST on Midnight between March
# 31 and April 1.
#
# Radio Reloj has the following info (Spanish):
# 
# http://www.radioreloj.cu/index.php/noticias-radio-reloj/71-miscelaneas/7529-cuba-aplicara-el-horario-de-verano-desde-el-1-de-abril
# 
#
# Our info on it:
# 
# http://www.timeanddate.com/news/time/cuba-starts-dst-2012.html
# 

# From Steffen Thorsen (2012-11-03):
# Radio Reloj and many other sources report that Cuba is changing back
# to standard time on 2012-11-04:
# http://www.radioreloj.cu/index.php/noticias-radio-reloj/36-nacionales/9961-regira-horario-normal-en-cuba-desde-el-domingo-cuatro-de-noviembre
# From Paul Eggert (2012-11-03):
# For now, assume the future rule is first Sunday in November.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Cuba	1928	only	-	Jun	10	0:00	1:00	D
Rule	Cuba	1928	only	-	Oct	10	0:00	0	S
Rule	Cuba	1940	1942	-	Jun	Sun>=1	0:00	1:00	D
Rule	Cuba	1940	1942	-	Sep	Sun>=1	0:00	0	S
Rule	Cuba	1945	1946	-	Jun	Sun>=1	0:00	1:00	D
Rule	Cuba	1945	1946	-	Sep	Sun>=1	0:00	0	S
Rule	Cuba	1965	only	-	Jun	1	0:00	1:00	D
Rule	Cuba	1965	only	-	Sep	30	0:00	0	S
Rule	Cuba	1966	only	-	May	29	0:00	1:00	D
Rule	Cuba	1966	only	-	Oct	2	0:00	0	S
Rule	Cuba	1967	only	-	Apr	8	0:00	1:00	D
Rule	Cuba	1967	1968	-	Sep	Sun>=8	0:00	0	S
Rule	Cuba	1968	only	-	Apr	14	0:00	1:00	D
Rule	Cuba	1969	1977	-	Apr	lastSun	0:00	1:00	D
Rule	Cuba	1969	1971	-	Oct	lastSun	0:00	0	S
Rule	Cuba	1972	1974	-	Oct	8	0:00	0	S
Rule	Cuba	1975	1977	-	Oct	lastSun	0:00	0	S
Rule	Cuba	1978	only	-	May	7	0:00	1:00	D
Rule	Cuba	1978	1990	-	Oct	Sun>=8	0:00	0	S
Rule	Cuba	1979	1980	-	Mar	Sun>=15	0:00	1:00	D
Rule	Cuba	1981	1985	-	May	Sun>=5	0:00	1:00	D
Rule	Cuba	1986	1989	-	Mar	Sun>=14	0:00	1:00	D
Rule	Cuba	1990	1997	-	Apr	Sun>=1	0:00	1:00	D
Rule	Cuba	1991	1995	-	Oct	Sun>=8	0:00s	0	S
Rule	Cuba	1996	only	-	Oct	 6	0:00s	0	S
Rule	Cuba	1997	only	-	Oct	12	0:00s	0	S
Rule	Cuba	1998	1999	-	Mar	lastSun	0:00s	1:00	D
Rule	Cuba	1998	2003	-	Oct	lastSun	0:00s	0	S
Rule	Cuba	2000	2004	-	Apr	Sun>=1	0:00s	1:00	D
Rule	Cuba	2006	2010	-	Oct	lastSun	0:00s	0	S
Rule	Cuba	2007	only	-	Mar	Sun>=8	0:00s	1:00	D
Rule	Cuba	2008	only	-	Mar	Sun>=15	0:00s	1:00	D
Rule	Cuba	2009	2010	-	Mar	Sun>=8	0:00s	1:00	D
Rule	Cuba	2011	only	-	Mar	Sun>=15	0:00s	1:00	D
Rule	Cuba	2011	only	-	Nov	13	0:00s	0	S
Rule	Cuba	2012	only	-	Apr	1	0:00s	1:00	D
Rule	Cuba	2012	max	-	Nov	Sun>=1	0:00s	0	S
Rule	Cuba	2013	max	-	Mar	Sun>=8	0:00s	1:00	D

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Havana	-5:29:28 -	LMT	1890
			-5:29:36 -	HMT	1925 Jul 19 12:00 # Havana MT
			-5:00	Cuba	C%sT

# Dominica
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Dominica	-4:05:36 -	LMT	1911 Jul 1 0:01		# Roseau
			-4:00	-	AST

# Dominican Republic

# From Steffen Thorsen (2000-10-30):
# Enrique Morales reported to me that the Dominican Republic has changed the
# time zone to Eastern Standard Time as of Sunday 29 at 2 am....
# http://www.listin.com.do/antes/261000/republica/princi.html

# From Paul Eggert (2000-12-04):
# That URL (2000-10-26, in Spanish) says they planned to use US-style DST.

# From Rives McDow (2000-12-01):
# Dominican Republic changed its mind and presidential decree on Tuesday,
# November 28, 2000, with a new decree.  On Sunday, December 3 at 1:00 AM the
# Dominican Republic will be reverting to 8 hours from the International Date
# Line, and will not be using DST in the foreseeable future.  The reason they
# decided to use DST was to be in synch with Puerto Rico, who was also going
# to implement DST.  When Puerto Rico didn't implement DST, the president
# decided to revert.


# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	DR	1966	only	-	Oct	30	0:00	1:00	D
Rule	DR	1967	only	-	Feb	28	0:00	0	S
Rule	DR	1969	1973	-	Oct	lastSun	0:00	0:30	HD
Rule	DR	1970	only	-	Feb	21	0:00	0	S
Rule	DR	1971	only	-	Jan	20	0:00	0	S
Rule	DR	1972	1974	-	Jan	21	0:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Santo_Domingo -4:39:36 -	LMT	1890
			-4:40	-	SDMT	1933 Apr  1 12:00 # S. Dom. MT
			-5:00	DR	E%sT	1974 Oct 27
			-4:00	-	AST	2000 Oct 29 02:00
			-5:00	US	E%sT	2000 Dec  3 01:00
			-4:00	-	AST

# El Salvador

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Salv	1987	1988	-	May	Sun>=1	0:00	1:00	D
Rule	Salv	1987	1988	-	Sep	lastSun	0:00	0	S
# There are too many San Salvadors elsewhere, so use America/El_Salvador
# instead of America/San_Salvador.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/El_Salvador -5:56:48 -	LMT	1921		# San Salvador
			-6:00	Salv	C%sT

# Grenada
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Grenada	-4:07:00 -	LMT	1911 Jul	# St George's
			-4:00	-	AST

# Guadeloupe
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Guadeloupe	-4:06:08 -	LMT	1911 Jun 8	# Pointe a Pitre
			-4:00	-	AST
# St Barthelemy
Link America/Guadeloupe	America/St_Barthelemy
# St Martin (French part)
Link America/Guadeloupe	America/Marigot

# Guatemala
#
# From Gwillim Law (2006-04-22), after a heads-up from Oscar van Vlijmen:
# Diario Co Latino, at
# http://www.diariocolatino.com/internacionales/detalles.asp?NewsID=8079,
# says in an article dated 2006-04-19 that the Guatemalan government had
# decided on that date to advance official time by 60 minutes, to lessen the
# impact of the elevated cost of oil....  Daylight saving time will last from
# 2006-04-29 24:00 (Guatemalan standard time) to 2006-09-30 (time unspecified).
# From Paul Eggert (2006-06-22):
# The Ministry of Energy and Mines, press release CP-15/2006
# (2006-04-19), says DST ends at 24:00.  See
# .

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Guat	1973	only	-	Nov	25	0:00	1:00	D
Rule	Guat	1974	only	-	Feb	24	0:00	0	S
Rule	Guat	1983	only	-	May	21	0:00	1:00	D
Rule	Guat	1983	only	-	Sep	22	0:00	0	S
Rule	Guat	1991	only	-	Mar	23	0:00	1:00	D
Rule	Guat	1991	only	-	Sep	 7	0:00	0	S
Rule	Guat	2006	only	-	Apr	30	0:00	1:00	D
Rule	Guat	2006	only	-	Oct	 1	0:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Guatemala	-6:02:04 -	LMT	1918 Oct 5
			-6:00	Guat	C%sT

# Haiti
# From Gwillim Law (2005-04-15):
# Risto O. Nykanen wrote me that Haiti is now on DST.
# I searched for confirmation, and I found a
#  press release
# on the Web page of the Haitian Consulate in Chicago (2005-03-31),
# .  Translated from French, it says:
#
#  "The Prime Minister's Communication Office notifies the public in general
#   and the press in particular that, following a decision of the Interior
#   Ministry and the Territorial Collectivities [I suppose that means the
#   provinces], Haiti will move to Eastern Daylight Time in the night from next
#   Saturday the 2nd to Sunday the 3rd.
#
#  "Consequently, the Prime Minister's Communication Office wishes to inform
#   the population that the country's clocks will be set forward one hour
#   starting at midnight.  This provision will hold until the last Saturday in
#   October 2005.
#
#  "Port-au-Prince, March 31, 2005"
#
# From Steffen Thorsen (2006-04-04):
# I have been informed by users that Haiti observes DST this year like
# last year, so the current "only" rule for 2005 might be changed to a
# "max" rule or to last until 2006. (Who knows if they will observe DST
# next year or if they will extend their DST like US/Canada next year).
#
# I have found this article about it (in French):
# http://www.haitipressnetwork.com/news.cfm?articleID=7612
#
# The reason seems to be an energy crisis.

# From Stephen Colebourne (2007-02-22):
# Some IATA info: Haiti won't be having DST in 2007.

# From Steffen Thorsen (2012-03-11):
# According to several news sources, Haiti will observe DST this year,
# apparently using the same start and end date as USA/Canada.
# So this means they have already changed their time.
#
# http://www.alterpresse.org/spip.php?article12510
# http://radiovision2000haiti.net/home/?p=13253
#
# From Arthur David Olson (2012-03-11):
# The alterpresse.org source seems to show a US-style leap from 2:00 a.m. to
# 3:00 a.m. rather than the traditional Haitian jump at midnight.
# Assume a US-style fall back as well.

# From Steffen Thorsen (2013-03-10):
# It appears that Haiti is observing DST this year as well, same rules
# as US/Canada.  They did it last year as well, and it looks like they
# are going to observe DST every year now...
#
# http://radiovision2000haiti.net/public/haiti-avis-changement-dheure-dimanche/
# http://www.canalplushaiti.net/?p=6714

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Haiti	1983	only	-	May	8	0:00	1:00	D
Rule	Haiti	1984	1987	-	Apr	lastSun	0:00	1:00	D
Rule	Haiti	1983	1987	-	Oct	lastSun	0:00	0	S
# Shanks & Pottenger say AT is 2:00, but IATA SSIM (1991/1997) says 1:00s.
# Go with IATA.
Rule	Haiti	1988	1997	-	Apr	Sun>=1	1:00s	1:00	D
Rule	Haiti	1988	1997	-	Oct	lastSun	1:00s	0	S
Rule	Haiti	2005	2006	-	Apr	Sun>=1	0:00	1:00	D
Rule	Haiti	2005	2006	-	Oct	lastSun	0:00	0	S
Rule	Haiti	2012	max	-	Mar	Sun>=8	2:00	1:00	D
Rule	Haiti	2012	max	-	Nov	Sun>=1	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Port-au-Prince -4:49:20 -	LMT	1890
			-4:49	-	PPMT	1917 Jan 24 12:00 # P-a-P MT
			-5:00	Haiti	E%sT

# Honduras
# Shanks & Pottenger say 1921 Jan 1; go with Whitman's more precise Apr 1.

# From Paul Eggert (2006-05-05):
# worldtimezone.com reports a 2006-05-02 Spanish-language AP article
# saying Honduras will start using DST midnight Saturday, effective 4
# months until September.  La Tribuna reported today
#  that Manuel Zelaya, the president
# of Honduras, refused to back down on this.

# From Jesper Norgaard Welen (2006-08-08):
# It seems that Honduras has returned from DST to standard time this Monday at
# 00:00 hours (prolonging Sunday to 25 hours duration).
# http://www.worldtimezone.com/dst_news/dst_news_honduras04.html

# From Paul Eggert (2006-08-08):
# Also see Diario El Heraldo, The country returns to standard time (2006-08-08)
# .
# It mentions executive decree 18-2006.

# From Steffen Thorsen (2006-08-17):
# Honduras will observe DST from 2007 to 2009, exact dates are not
# published, I have located this authoritative source:
# http://www.presidencia.gob.hn/noticia.aspx?nId=47

# From Steffen Thorsen (2007-03-30):
# http://www.laprensahn.com/pais_nota.php?id04962=7386
# So it seems that Honduras will not enter DST this year....

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Hond	1987	1988	-	May	Sun>=1	0:00	1:00	D
Rule	Hond	1987	1988	-	Sep	lastSun	0:00	0	S
Rule	Hond	2006	only	-	May	Sun>=1	0:00	1:00	D
Rule	Hond	2006	only	-	Aug	Mon>=1	0:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Tegucigalpa -5:48:52 -	LMT	1921 Apr
			-6:00	Hond	C%sT
#
# Great Swan I ceded by US to Honduras in 1972

# Jamaica

# From Bob Devine (1988-01-28):
# Follows US rules.

# From U. S. Naval Observatory (1989-01-19):
# JAMAICA             5 H  BEHIND UTC

# From Shanks & Pottenger:
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Jamaica	-5:07:12 -	LMT	1890		# Kingston
			-5:07:12 -	KMT	1912 Feb    # Kingston Mean Time
			-5:00	-	EST	1974 Apr 28 2:00
			-5:00	US	E%sT	1984
			-5:00	-	EST

# Martinique
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Martinique	-4:04:20 -      LMT	1890		# Fort-de-France
			-4:04:20 -	FFMT	1911 May     # Fort-de-France MT
			-4:00	-	AST	1980 Apr  6
			-4:00	1:00	ADT	1980 Sep 28
			-4:00	-	AST

# Montserrat
# From Paul Eggert (2006-03-22):
# In 1995 volcanic eruptions forced evacuation of Plymouth, the capital.
# world.gazetteer.com says Cork Hill is the most populous location now.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Montserrat	-4:08:52 -	LMT	1911 Jul 1 0:01   # Cork Hill
			-4:00	-	AST

# Nicaragua
#
# This uses Shanks & Pottenger for times before 2005.
#
# From Steffen Thorsen (2005-04-12):
# I've got reports from 8 different people that Nicaragua just started
# DST on Sunday 2005-04-10, in order to save energy because of
# expensive petroleum.  The exact end date for DST is not yet
# announced, only "September" but some sites also say "mid-September".
# Some background information is available on the President's official site:
# http://www.presidencia.gob.ni/Presidencia/Files_index/Secretaria/Notas%20de%20Prensa/Presidente/2005/ABRIL/Gobierno-de-nicaragua-adelanta-hora-oficial-06abril.htm
# The Decree, no 23-2005 is available here:
# http://www.presidencia.gob.ni/buscador_gaceta/BD/DECRETOS/2005/Decreto%2023-2005%20Se%20adelanta%20en%20una%20hora%20en%20todo%20el%20territorio%20nacional%20apartir%20de%20las%2024horas%20del%2009%20de%20Abril.pdf
#
# From Paul Eggert (2005-05-01):
# The decree doesn't say anything about daylight saving, but for now let's
# assume that it is daylight saving....
#
# From Gwillim Law (2005-04-21):
# The Associated Press story on the time change, which can be found at
# http://www.lapalmainteractivo.com/guias/content/gen/ap/America_Latina/AMC_GEN_NICARAGUA_HORA.html
# and elsewhere, says (fifth paragraph, translated from Spanish):  "The last
# time that a change of clocks was applied to save energy was in the year 2000
# during the Arnoldo Aleman administration."...
# The northamerica file says that Nicaragua has been on UTC-6 continuously
# since December 1998.  I wasn't able to find any details of Nicaraguan time
# changes in 2000.  Perhaps a note could be added to the northamerica file, to
# the effect that we have indirect evidence that DST was observed in 2000.
#
# From Jesper Norgaard Welen (2005-11-02):
# Nicaragua left DST the 2005-10-02 at 00:00 (local time).
# http://www.presidencia.gob.ni/presidencia/files_index/secretaria/comunicados/2005/septiembre/26septiembre-cambio-hora.htm
# (2005-09-26)
#
# From Jesper Norgaard Welen (2006-05-05):
# http://www.elnuevodiario.com.ni/2006/05/01/nacionales/18410
# (my informal translation)
# By order of the president of the republic, Enrique Bolanos, Nicaragua
# advanced by sixty minutes their official time, yesterday at 2 in the
# morning, and will stay that way until 30.th. of september.
#
# From Jesper Norgaard Welen (2006-09-30):
# http://www.presidencia.gob.ni/buscador_gaceta/BD/DECRETOS/2006/D-063-2006P-PRN-Cambio-Hora.pdf
# My informal translation runs:
# The natural sun time is restored in all the national territory, in that the
# time is returned one hour at 01:00 am of October 1 of 2006.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Nic	1979	1980	-	Mar	Sun>=16	0:00	1:00	D
Rule	Nic	1979	1980	-	Jun	Mon>=23	0:00	0	S
Rule	Nic	2005	only	-	Apr	10	0:00	1:00	D
Rule	Nic	2005	only	-	Oct	Sun>=1	0:00	0	S
Rule	Nic	2006	only	-	Apr	30	2:00	1:00	D
Rule	Nic	2006	only	-	Oct	Sun>=1	1:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Managua	-5:45:08 -	LMT	1890
			-5:45:12 -	MMT	1934 Jun 23 # Managua Mean Time?
			-6:00	-	CST	1973 May
			-5:00	-	EST	1975 Feb 16
			-6:00	Nic	C%sT	1992 Jan  1 4:00
			-5:00	-	EST	1992 Sep 24
			-6:00	-	CST	1993
			-5:00	-	EST	1997
			-6:00	Nic	C%sT

# Panama
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Panama	-5:18:08 -	LMT	1890
			-5:19:36 -	CMT	1908 Apr 22   # Colon Mean Time
			-5:00	-	EST

# Puerto Rico
# There are too many San Juans elsewhere, so we'll use `Puerto_Rico'.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Puerto_Rico -4:24:25 -	LMT	1899 Mar 28 12:00    # San Juan
			-4:00	-	AST	1942 May  3
			-4:00	US	A%sT	1946
			-4:00	-	AST

# St Kitts-Nevis
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/St_Kitts	-4:10:52 -	LMT	1912 Mar 2	# Basseterre
			-4:00	-	AST

# St Lucia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/St_Lucia	-4:04:00 -	LMT	1890		# Castries
			-4:04:00 -	CMT	1912	    # Castries Mean Time
			-4:00	-	AST

# St Pierre and Miquelon
# There are too many St Pierres elsewhere, so we'll use `Miquelon'.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Miquelon	-3:44:40 -	LMT	1911 May 15	# St Pierre
			-4:00	-	AST	1980 May
			-3:00	-	PMST	1987 # Pierre & Miquelon Time
			-3:00	Canada	PM%sT

# St Vincent and the Grenadines
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/St_Vincent	-4:04:56 -	LMT	1890		# Kingstown
			-4:04:56 -	KMT	1912	   # Kingstown Mean Time
			-4:00	-	AST

# Turks and Caicos
#
# From Chris Dunn in
# 
# (2007-03-15): In the Turks & Caicos Islands (America/Grand_Turk) the
# daylight saving dates for time changes have been adjusted to match
# the recent U.S. change of dates.
#
# From Brian Inglis (2007-04-28):
# http://www.turksandcaicos.tc/calendar/index.htm [2007-04-26]
# there is an entry for Nov 4 "Daylight Savings Time Ends 2007" and three
# rows before that there is an out of date entry for Oct:
# "Eastern Standard Times Begins 2007
# Clocks are set back one hour at 2:00 a.m. local Daylight Saving Time"
# indicating that the normal ET rules are followed.
#
# From Paul Eggert (2006-05-01):
# Shanks & Pottenger say they use US DST rules, but IATA SSIM (1991/1998)
# says they switch at midnight.  Go with Shanks & Pottenger.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	TC	1979	1986	-	Apr	lastSun	2:00	1:00	D
Rule	TC	1979	2006	-	Oct	lastSun	2:00	0	S
Rule	TC	1987	2006	-	Apr	Sun>=1	2:00	1:00	D
Rule	TC	2007	max	-	Mar	Sun>=8	2:00	1:00	D
Rule	TC	2007	max	-	Nov	Sun>=1	2:00	0	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Grand_Turk	-4:44:32 -	LMT	1890
			-5:07:12 -	KMT	1912 Feb    # Kingston Mean Time
			-5:00	TC	E%sT

# British Virgin Is
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Tortola	-4:18:28 -	LMT	1911 Jul    # Road Town
			-4:00	-	AST

# Virgin Is
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/St_Thomas	-4:19:44 -	LMT	1911 Jul    # Charlotte Amalie
			-4:00	-	AST
joda-time-2.3/src/main/java/org/joda/time/tz/src/southamerica0000644000175000017500000022601012200501234023476 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# This data is by no means authoritative; if you think you know better,
# go ahead and edit the file (and please send any changes to
# tz@iana.org for general use in the future).

# From Paul Eggert (2006-03-22):
# A good source for time zone historical data outside the U.S. is
# Thomas G. Shanks and Rique Pottenger, The International Atlas (6th edition),
# San Diego: ACS Publications, Inc. (2003).
#
# For data circa 1899, a common source is:
# Milne J. Civil time. Geogr J. 1899 Feb;13(2):173-94
# .
#
# Gwillim Law writes that a good source
# for recent time zone data is the International Air Transport
# Association's Standard Schedules Information Manual (IATA SSIM),
# published semiannually.  Law sent in several helpful summaries
# of the IATA's data after 1990.
#
# Except where otherwise noted, Shanks & Pottenger is the source for
# entries through 1990, and IATA SSIM is the source for entries afterwards.
#
# Earlier editions of these tables used the North American style (e.g. ARST and
# ARDT for Argentine Standard and Daylight Time), but the following quote
# suggests that it's better to use European style (e.g. ART and ARST).
#	I suggest the use of _Summer time_ instead of the more cumbersome
#	_daylight-saving time_.  _Summer time_ seems to be in general use
#	in Europe and South America.
#	-- E O Cutler, _New York Times_ (1937-02-14), quoted in
#	H L Mencken, _The American Language: Supplement I_ (1960), p 466
#
# Earlier editions of these tables also used the North American style
# for time zones in Brazil, but this was incorrect, as Brazilians say
# "summer time".  Reinaldo Goulart, a Sao Paulo businessman active in
# the railroad sector, writes (1999-07-06):
#	The subject of time zones is currently a matter of discussion/debate in
#	Brazil.  Let's say that "the Brasilia time" is considered the
#	"official time" because Brasilia is the capital city.
#	The other three time zones are called "Brasilia time "minus one" or
#	"plus one" or "plus two".  As far as I know there is no such
#	name/designation as "Eastern Time" or "Central Time".
# So I invented the following (English-language) abbreviations for now.
# Corrections are welcome!
#		std	dst
#	-2:00	FNT	FNST	Fernando de Noronha
#	-3:00	BRT	BRST	Brasilia
#	-4:00	AMT	AMST	Amazon
#	-5:00	ACT	ACST	Acre

###############################################################################

###############################################################################

# Argentina

# From Bob Devine (1988-01-28):
# Argentina: first Sunday in October to first Sunday in April since 1976.
# Double Summer time from 1969 to 1974.  Switches at midnight.

# From U. S. Naval Observatory (1988-01-199):
# ARGENTINA           3 H BEHIND   UTC

# From Hernan G. Otero (1995-06-26):
# I am sending modifications to the Argentine time zone table...
# AR was chosen because they are the ISO letters that represent Argentina.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Arg	1930	only	-	Dec	 1	0:00	1:00	S
Rule	Arg	1931	only	-	Apr	 1	0:00	0	-
Rule	Arg	1931	only	-	Oct	15	0:00	1:00	S
Rule	Arg	1932	1940	-	Mar	 1	0:00	0	-
Rule	Arg	1932	1939	-	Nov	 1	0:00	1:00	S
Rule	Arg	1940	only	-	Jul	 1	0:00	1:00	S
Rule	Arg	1941	only	-	Jun	15	0:00	0	-
Rule	Arg	1941	only	-	Oct	15	0:00	1:00	S
Rule	Arg	1943	only	-	Aug	 1	0:00	0	-
Rule	Arg	1943	only	-	Oct	15	0:00	1:00	S
Rule	Arg	1946	only	-	Mar	 1	0:00	0	-
Rule	Arg	1946	only	-	Oct	 1	0:00	1:00	S
Rule	Arg	1963	only	-	Oct	 1	0:00	0	-
Rule	Arg	1963	only	-	Dec	15	0:00	1:00	S
Rule	Arg	1964	1966	-	Mar	 1	0:00	0	-
Rule	Arg	1964	1966	-	Oct	15	0:00	1:00	S
Rule	Arg	1967	only	-	Apr	 2	0:00	0	-
Rule	Arg	1967	1968	-	Oct	Sun>=1	0:00	1:00	S
Rule	Arg	1968	1969	-	Apr	Sun>=1	0:00	0	-
Rule	Arg	1974	only	-	Jan	23	0:00	1:00	S
Rule	Arg	1974	only	-	May	 1	0:00	0	-
Rule	Arg	1988	only	-	Dec	 1	0:00	1:00	S
#
# From Hernan G. Otero (1995-06-26):
# These corrections were contributed by InterSoft Argentina S.A.,
# obtaining the data from the:
# Talleres de Hidrografia Naval Argentina
# (Argentine Naval Hydrography Institute)
Rule	Arg	1989	1993	-	Mar	Sun>=1	0:00	0	-
Rule	Arg	1989	1992	-	Oct	Sun>=15	0:00	1:00	S
#
# From Hernan G. Otero (1995-06-26):
# From this moment on, the law that mandated the daylight saving
# time corrections was derogated and no more modifications
# to the time zones (for daylight saving) are now made.
#
# From Rives McDow (2000-01-10):
# On October 3, 1999, 0:00 local, Argentina implemented daylight savings time,
# which did not result in the switch of a time zone, as they stayed 9 hours
# from the International Date Line.
Rule	Arg	1999	only	-	Oct	Sun>=1	0:00	1:00	S
# From Paul Eggert (2007-12-28):
# DST was set to expire on March 5, not March 3, but since it was converted
# to standard time on March 3 it's more convenient for us to pretend that
# it ended on March 3.
Rule	Arg	2000	only	-	Mar	3	0:00	0	-
#
# From Peter Gradelski via Steffen Thorsen (2000-03-01):
# We just checked with our Sao Paulo office and they say the government of
# Argentina decided not to become one of the countries that go on or off DST.
# So Buenos Aires should be -3 hours from GMT at all times.
#
# From Fabian L. Arce Jofre (2000-04-04):
# The law that claimed DST for Argentina was derogated by President Fernando
# de la Rua on March 2, 2000, because it would make people spend more energy
# in the winter time, rather than less.  The change took effect on March 3.
#
# From Mariano Absatz (2001-06-06):
# one of the major newspapers here in Argentina said that the 1999
# Timezone Law (which never was effectively applied) will (would?) be
# in effect.... The article is at
# http://ar.clarin.com/diario/2001-06-06/e-01701.htm
# ... The Law itself is "Ley No 25155", sanctioned on 1999-08-25, enacted
# 1999-09-17, and published 1999-09-21.  The official publication is at:
# http://www.boletin.jus.gov.ar/BON/Primera/1999/09-Septiembre/21/PDF/BO21-09-99LEG.PDF
# Regretfully, you have to subscribe (and pay) for the on-line version....
#
# (2001-06-12):
# the timezone for Argentina will not change next Sunday.
# Apparently it will do so on Sunday 24th....
# http://ar.clarin.com/diario/2001-06-12/s-03501.htm
#
# (2001-06-25):
# Last Friday (yes, the last working day before the date of the change), the
# Senate annulled the 1999 law that introduced the changes later postponed.
# http://www.clarin.com.ar/diario/2001-06-22/s-03601.htm
# It remains the vote of the Deputies..., but it will be the same....
# This kind of things had always been done this way in Argentina.
# We are still -03:00 all year round in all of the country.
#
# From Steffen Thorsen (2007-12-21):
# A user (Leonardo Chaim) reported that Argentina will adopt DST....
# all of the country (all Zone-entries) are affected.  News reports like
# http://www.lanacion.com.ar/opinion/nota.asp?nota_id=973037 indicate
# that Argentina will use DST next year as well, from October to
# March, although exact rules are not given.
#
# From Jesper Norgaard Welen (2007-12-26)
# The last hurdle of Argentina DST is over, the proposal was approved in
# the lower chamber too (Deputados) with a vote 192 for and 2 against.
# By the way thanks to Mariano Absatz and Daniel Mario Vega for the link to
# the original scanned proposal, where the dates and the zero hours are
# clear and unambiguous...This is the article about final approval:
# 
# http://www.lanacion.com.ar/politica/nota.asp?nota_id=973996
# 
#
# From Paul Eggert (2007-12-22):
# For dates after mid-2008, the following rules are my guesses and
# are quite possibly wrong, but are more likely than no DST at all.

# From Alexander Krivenyshev (2008-09-05):
# As per message from Carlos Alberto Fonseca Arauz (Nicaragua),
# Argentina will start DST on Sunday October 19, 2008.
#
# 
# http://www.worldtimezone.com/dst_news/dst_news_argentina03.html
# 
# OR
# 
# http://www.impulsobaires.com.ar/nota.php?id=57832 (in spanish)
# 

# From Rodrigo Severo (2008-10-06):
# Here is some info available at a Gentoo bug related to TZ on Argentina's DST:
# ...
# ------- Comment #1 from [jmdocile]  2008-10-06 16:28 0000 -------
# Hi, there is a problem with timezone-data-2008e and maybe with
# timezone-data-2008f
# Argentinian law [Number] 25.155 is no longer valid.
# 
# http://www.infoleg.gov.ar/infolegInternet/anexos/60000-64999/60036/norma.htm
# 
# The new one is law [Number] 26.350
# 
# http://www.infoleg.gov.ar/infolegInternet/anexos/135000-139999/136191/norma.htm
# 
# So there is no summer time in Argentina for now.

# From Mariano Absatz (2008-10-20):
# Decree 1693/2008 applies Law 26.350 for the summer 2008/2009 establishing DST in Argentina
# From 2008-10-19 until 2009-03-15
# 
# http://www.boletinoficial.gov.ar/Bora.Portal/CustomControls/PdfContent.aspx?fp=16102008&pi=3&pf=4&s=0&sec=01
# 
#
# Decree 1705/2008 excepting 12 Provinces from applying DST in the summer 2008/2009:
# Catamarca, La Rioja, Mendoza, Salta, San Juan, San Luis, La Pampa, Neuquen, Rio Negro, Chubut, Santa Cruz
# and Tierra del Fuego
# 
# http://www.boletinoficial.gov.ar/Bora.Portal/CustomControls/PdfContent.aspx?fp=17102008&pi=1&pf=1&s=0&sec=01
# 
#
# Press release 235 dated Saturday October 18th, from the Government of the Province of Jujuy saying
# it will not apply DST either (even when it was not included in Decree 1705/2008)
# 
# http://www.jujuy.gov.ar/index2/partes_prensa/18_10_08/235-181008.doc
# 

# From fullinet (2009-10-18):
# As announced in
# 
# http://www.argentina.gob.ar/argentina/portal/paginas.dhtml?pagina=356
# 
# (an official .gob.ar) under title: "Sin Cambio de Hora" (english: "No hour change")
#
# "Por el momento, el Gobierno Nacional resolvio no modificar la hora
# oficial, decision que estaba en estudio para su implementacion el
# domingo 18 de octubre. Desde el Ministerio de Planificacion se anuncio
# que la Argentina hoy, en estas condiciones meteorologicas, no necesita
# la modificacion del huso horario, ya que 2009 nos encuentra con
# crecimiento en la produccion y distribucion energetica."

Rule	Arg	2007	only	-	Dec	30	0:00	1:00	S
Rule	Arg	2008	2009	-	Mar	Sun>=15	0:00	0	-
Rule	Arg	2008	only	-	Oct	Sun>=15	0:00	1:00	S

# From Mariano Absatz (2004-05-21):
# Today it was officially published that the Province of Mendoza is changing
# its timezone this winter... starting tomorrow night....
# http://www.gobernac.mendoza.gov.ar/boletin/pdf/20040521-27158-normas.pdf
# From Paul Eggert (2004-05-24):
# It's Law No. 7,210.  This change is due to a public power emergency, so for
# now we'll assume it's for this year only.
#
# From Paul Eggert (2006-03-22):
# 
# Hora de verano para la Republica Argentina (2003-06-08)
#  says that standard time in Argentina from 1894-10-31
# to 1920-05-01 was -4:16:48.25.  Go with this more-precise value
# over Shanks & Pottenger.
#
# From Mariano Absatz (2004-06-05):
# These media articles from a major newspaper mostly cover the current state:
# http://www.lanacion.com.ar/04/05/27/de_604825.asp
# http://www.lanacion.com.ar/04/05/28/de_605203.asp
#
# The following eight (8) provinces pulled clocks back to UTC-04:00 at
# midnight Monday May 31st. (that is, the night between 05/31 and 06/01).
# Apparently, all nine provinces would go back to UTC-03:00 at the same
# time in October 17th.
#
# Catamarca, Chubut, La Rioja, San Juan, San Luis, Santa Cruz,
# Tierra del Fuego, Tucuman.
#
# From Mariano Absatz (2004-06-14):
# ... this weekend, the Province of Tucuman decided it'd go back to UTC-03:00
# yesterday midnight (that is, at 24:00 Saturday 12th), since the people's
# annoyance with the change is much higher than the power savings obtained....
#
# From Gwillim Law (2004-06-14):
# http://www.lanacion.com.ar/04/06/10/de_609078.asp ...
#     "The time change in Tierra del Fuego was a conflicted decision from
#   the start.  The government had decreed that the measure would take
#   effect on June 1, but a normative error forced the new time to begin
#   three days earlier, from a Saturday to a Sunday....
# Our understanding was that the change was originally scheduled to take place
# on June 1 at 00:00 in Chubut, Santa Cruz, Tierra del Fuego (and some other
# provinces).  Sunday was May 30, only two days earlier.  So the article
# contains a contradiction.  I would give more credence to the Saturday/Sunday
# date than the "three days earlier" phrase, and conclude that Tierra del
# Fuego set its clocks back at 2004-05-30 00:00.
#
# From Steffen Thorsen (2004-10-05):
# The previous law 7210 which changed the province of Mendoza's time zone
# back in May have been modified slightly in a new law 7277, which set the
# new end date to 2004-09-26 (original date was 2004-10-17).
# http://www.gobernac.mendoza.gov.ar/boletin/pdf/20040924-27244-normas.pdf
#
# From Mariano Absatz (2004-10-05):
# San Juan changed from UTC-03:00 to UTC-04:00 at midnight between
# Sunday, May 30th and Monday, May 31st.  It changed back to UTC-03:00
# at midnight between Saturday, July 24th and Sunday, July 25th....
# http://www.sanjuan.gov.ar/prensa/archivo/000329.html
# http://www.sanjuan.gov.ar/prensa/archivo/000426.html
# http://www.sanjuan.gov.ar/prensa/archivo/000441.html

# From Alex Krivenyshev (2008-01-17):
# Here are articles that Argentina Province San Luis is planning to end DST
# as earlier as upcoming Monday January 21, 2008 or February 2008:
#
# Provincia argentina retrasa reloj y marca diferencia con resto del pais
# (Argentine Province delayed clock and mark difference with the rest of the
# country)
# 
# http://cl.invertia.com/noticias/noticia.aspx?idNoticia=200801171849_EFE_ET4373&idtel
# 
#
# Es inminente que en San Luis atrasen una hora los relojes
# (It is imminent in San Luis clocks one hour delay)
# 
# http://www.lagaceta.com.ar/vernotae.asp?id_nota=253414
# 
#
# 
# http://www.worldtimezone.net/dst_news/dst_news_argentina02.html
# 

# From Jesper Norgaard Welen (2008-01-18):
# The page of the San Luis provincial government
# 
# http://www.sanluis.gov.ar/notas.asp?idCanal=0&id=22812
# 
# confirms what Alex Krivenyshev has earlier sent to the tz
# emailing list about that San Luis plans to return to standard
# time much earlier than the rest of the country. It also
# confirms that upon request the provinces San Juan and Mendoza
# refused to follow San Luis in this change.
#
# The change is supposed to take place Monday the 21.st at 0:00
# hours. As far as I understand it if this goes ahead, we need
# a new timezone for San Luis (although there are also documented
# independent changes in the southamerica file of San Luis in
# 1990 and 1991 which has not been confirmed).

# From Jesper Norgaard Welen (2008-01-25):
# Unfortunately the below page has become defunct, about the San Luis
# time change. Perhaps because it now is part of a group of pages "Most
# important pages of 2008."
#
# You can use
# 
# http://www.sanluis.gov.ar/notas.asp?idCanal=8141&id=22834
# 
# instead it seems. Or use "Buscador" from the main page of the San Luis
# government, and fill in "huso" and click OK, and you will get 3 pages
# from which the first one is identical to the above.

# From Mariano Absatz (2008-01-28):
# I can confirm that the Province of San Luis (and so far only that
# province) decided to go back to UTC-3 effective midnight Jan 20th 2008
# (that is, Monday 21st at 0:00 is the time the clocks were delayed back
# 1 hour), and they intend to keep UTC-3 as their timezone all year round
# (that is, unless they change their mind any minute now).
#
# So we'll have to add yet another city to 'southamerica' (I think San
# Luis city is the mos populated city in the Province, so it'd be
# America/Argentina/San_Luis... of course I can't remember if San Luis's
# history of particular changes goes along with Mendoza or San Juan :-(
# (I only remember not being able to collect hard facts about San Luis
# back in 2004, when these provinces changed to UTC-4 for a few days, I
# mailed them personally and never got an answer).

# From Paul Eggert (2008-06-30):
# Unless otherwise specified, data are from Shanks & Pottenger through 1992,
# from the IATA otherwise.  As noted below, Shanks & Pottenger say that
# America/Cordoba split into 6 subregions during 1991/1992, one of which
# was America/San_Luis, but we haven't verified this yet so for now we'll
# keep America/Cordoba a single region rather than splitting it into the
# other 5 subregions.

# From Mariano Absatz (2009-03-13):
# Yesterday (with our usual 2-day notice) the Province of San Luis
# decided that next Sunday instead of "staying" @utc-03:00 they will go
# to utc-04:00 until the second Saturday in October...
#
# The press release is at
# 
# http://www.sanluis.gov.ar/SL/Paginas/NoticiaDetalle.asp?TemaId=1&InfoPrensaId=3102
# 
# (I couldn't find the decree, but
# 
# www.sanluis.gov.ar
# 
# is the official page for the Province Government).
#
# There's also a note in only one of the major national papers ...
# http://www.lanacion.com.ar/nota.asp?nota_id=1107912
#
# The press release says [quick and dirty translation]:
# ... announced that next Sunday, at 00:00, Puntanos (the San Luis
# inhabitants) will have to turn back one hour their clocks
#
# Since then, San Luis will establish its own Province timezone. Thus,
# during 2009, this timezone change will run from 00:00 the third Sunday
# in March until 24:00 of the second Saturday in October.

# From Mariano Absatz (2009-10-16):
# ...the Province of San Luis is a case in itself.
#
# The Law at
# 
# is ambiguous because establishes a calendar from the 2nd Sunday in
# October at 0:00 thru the 2nd Saturday in March at 24:00 and the
# complement of that starting on the 2nd Sunday of March at 0:00 and
# ending on the 2nd Saturday of March at 24:00.
#
# This clearly breaks every time the 1st of March or October is a Sunday.
#
# IMHO, the "spirit of the Law" is to make the changes at 0:00 on the 2nd
# Sunday of October and March.
#
# The problem is that the changes in the rest of the Provinces that did
# change in 2007/2008, were made according to the Federal Law and Decrees
# that did so on the 3rd Sunday of October and March.
#
# In fact, San Luis actually switched from UTC-4 to UTC-3 last Sunday
# (October 11th) at 0:00.
#
# So I guess a new set of rules, besides "Arg", must be made and the last
# America/Argentina/San_Luis entries should change to use these...
#
# I'm enclosing a patch that does what I say... regretfully, the San Luis
# timezone must be called "WART/WARST" even when most of the time (like,
# right now) WARST == ART... that is, since last Sunday, all the country
# is using UTC-3, but in my patch, San Luis calls it "WARST" and the rest
# of the country calls it "ART".
# ...

# From Alexander Krivenyshev (2010-04-09):
# According to news reports from El Diario de la Republica Province San
# Luis, Argentina (standard time UTC-04) will keep Daylight Saving Time
# after April 11, 2010--will continue to have same time as rest of
# Argentina (UTC-3) (no DST).
#
# Confirmaron la prórroga del huso horario de verano (Spanish)
# 
# http://www.eldiariodelarepublica.com/index.php?option=com_content&task=view&id=29383&Itemid=9
# 
# or (some English translation):
# 
# http://www.worldtimezone.com/dst_news/dst_news_argentina08.html
# 

# From Mariano Absatz (2010-04-12):
# yes...I can confirm this...and given that San Luis keeps calling
# UTC-03:00 "summer time", we should't just let San Luis go back to "Arg"
# rules...San Luis is still using "Western ARgentina Time" and it got
# stuck on Summer daylight savings time even though the summer is over.

# From Paul Eggert (2013-02-21):
# Milne says Cordoba time was -4:16:48.2.  Round to the nearest second.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
#
# Buenos Aires (BA), Capital Federal (CF),
Zone America/Argentina/Buenos_Aires -3:53:48 - LMT 1894 Oct 31
			-4:16:48 -	CMT	1920 May # Cordoba Mean Time
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	Arg	AR%sT
#
# Cordoba (CB), Santa Fe (SF), Entre Rios (ER), Corrientes (CN), Misiones (MN),
# Chaco (CC), Formosa (FM), Santiago del Estero (SE)
#
# Shanks & Pottenger also make the following claims, which we haven't verified:
# - Formosa switched to -3:00 on 1991-01-07.
# - Misiones switched to -3:00 on 1990-12-29.
# - Chaco switched to -3:00 on 1991-01-04.
# - Santiago del Estero switched to -4:00 on 1991-04-01,
#   then to -3:00 on 1991-04-26.
#
Zone America/Argentina/Cordoba -4:16:48 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1991 Mar  3
			-4:00	-	WART	1991 Oct 20
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	Arg	AR%sT
#
# Salta (SA), La Pampa (LP), Neuquen (NQ), Rio Negro (RN)
Zone America/Argentina/Salta -4:21:40 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1991 Mar  3
			-4:00	-	WART	1991 Oct 20
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART
#
# Tucuman (TM)
Zone America/Argentina/Tucuman -4:20:52 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1991 Mar  3
			-4:00	-	WART	1991 Oct 20
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	-	ART	2004 Jun  1
			-4:00	-	WART	2004 Jun 13
			-3:00	Arg	AR%sT
#
# La Rioja (LR)
Zone America/Argentina/La_Rioja -4:27:24 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1991 Mar  1
			-4:00	-	WART	1991 May  7
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	-	ART	2004 Jun  1
			-4:00	-	WART	2004 Jun 20
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART
#
# San Juan (SJ)
Zone America/Argentina/San_Juan -4:34:04 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1991 Mar  1
			-4:00	-	WART	1991 May  7
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	-	ART	2004 May 31
			-4:00	-	WART	2004 Jul 25
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART
#
# Jujuy (JY)
Zone America/Argentina/Jujuy -4:21:12 -	LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1990 Mar  4
			-4:00	-	WART	1990 Oct 28
			-4:00	1:00	WARST	1991 Mar 17
			-4:00	-	WART	1991 Oct  6
			-3:00	1:00	ARST	1992
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART
#
# Catamarca (CT), Chubut (CH)
Zone America/Argentina/Catamarca -4:23:08 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1991 Mar  3
			-4:00	-	WART	1991 Oct 20
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	-	ART	2004 Jun  1
			-4:00	-	WART	2004 Jun 20
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART
#
# Mendoza (MZ)
Zone America/Argentina/Mendoza -4:35:16 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1990 Mar  4
			-4:00	-	WART	1990 Oct 15
			-4:00	1:00	WARST	1991 Mar  1
			-4:00	-	WART	1991 Oct 15
			-4:00	1:00	WARST	1992 Mar  1
			-4:00	-	WART	1992 Oct 18
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	-	ART	2004 May 23
			-4:00	-	WART	2004 Sep 26
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART
#
# San Luis (SL)

Rule	SanLuis	2008	2009	-	Mar	Sun>=8	0:00	0	-
Rule	SanLuis	2007	2009	-	Oct	Sun>=8	0:00	1:00	S

Zone America/Argentina/San_Luis -4:25:24 - LMT	1894 Oct 31
			-4:16:48 -	CMT	1920 May
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1990
			-3:00	1:00	ARST	1990 Mar 14
			-4:00	-	WART	1990 Oct 15
			-4:00	1:00	WARST	1991 Mar  1
			-4:00	-	WART	1991 Jun  1
			-3:00	-	ART	1999 Oct  3
			-4:00	1:00	WARST	2000 Mar  3
			-3:00	-	ART	2004 May 31
			-4:00	-	WART	2004 Jul 25
			-3:00	Arg	AR%sT	2008 Jan 21
			-4:00	SanLuis	WAR%sT
#
# Santa Cruz (SC)
Zone America/Argentina/Rio_Gallegos -4:36:52 - LMT 1894 Oct 31
			-4:16:48 -	CMT	1920 May # Cordoba Mean Time
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	-	ART	2004 Jun  1
			-4:00	-	WART	2004 Jun 20
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART
#
# Tierra del Fuego, Antartida e Islas del Atlantico Sur (TF)
Zone America/Argentina/Ushuaia -4:33:12 - LMT 1894 Oct 31
			-4:16:48 -	CMT	1920 May # Cordoba Mean Time
			-4:00	-	ART	1930 Dec
			-4:00	Arg	AR%sT	1969 Oct  5
			-3:00	Arg	AR%sT	1999 Oct  3
			-4:00	Arg	AR%sT	2000 Mar  3
			-3:00	-	ART	2004 May 30
			-4:00	-	WART	2004 Jun 20
			-3:00	Arg	AR%sT	2008 Oct 18
			-3:00	-	ART

# Aruba
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Aruba	-4:40:24 -	LMT	1912 Feb 12	# Oranjestad
			-4:30	-	ANT	1965 # Netherlands Antilles Time
			-4:00	-	AST

# Bolivia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/La_Paz	-4:32:36 -	LMT	1890
			-4:32:36 -	CMT	1931 Oct 15 # Calamarca MT
			-4:32:36 1:00	BOST	1932 Mar 21 # Bolivia ST
			-4:00	-	BOT	# Bolivia Time

# Brazil

# From Paul Eggert (1993-11-18):
# The mayor of Rio recently attempted to change the time zone rules
# just in his city, in order to leave more summer time for the tourist trade.
# The rule change lasted only part of the day;
# the federal government refused to follow the city's rules, and business
# was in a chaos, so the mayor backed down that afternoon.

# From IATA SSIM (1996-02):
# _Only_ the following states in BR1 observe DST: Rio Grande do Sul (RS),
# Santa Catarina (SC), Parana (PR), Sao Paulo (SP), Rio de Janeiro (RJ),
# Espirito Santo (ES), Minas Gerais (MG), Bahia (BA), Goias (GO),
# Distrito Federal (DF), Tocantins (TO), Sergipe [SE] and Alagoas [AL].
# [The last three states are new to this issue of the IATA SSIM.]

# From Gwillim Law (1996-10-07):
# Geography, history (Tocantins was part of Goias until 1989), and other
# sources of time zone information lead me to believe that AL, SE, and TO were
# always in BR1, and so the only change was whether or not they observed DST....
# The earliest issue of the SSIM I have is 2/91.  Each issue from then until
# 9/95 says that DST is observed only in the ten states I quoted from 9/95,
# along with Mato Grosso (MT) and Mato Grosso do Sul (MS), which are in BR2
# (UTC-4)....  The other two time zones given for Brazil are BR3, which is
# UTC-5, no DST, and applies only in the state of Acre (AC); and BR4, which is
# UTC-2, and applies to Fernando de Noronha (formerly FN, but I believe it's
# become part of the state of Pernambuco).  The boundary between BR1 and BR2
# has never been clearly stated.  They've simply been called East and West.
# However, some conclusions can be drawn from another IATA manual: the Airline
# Coding Directory, which lists close to 400 airports in Brazil.  For each
# airport it gives a time zone which is coded to the SSIM.  From that
# information, I'm led to conclude that the states of Amapa (AP), Ceara (CE),
# Maranhao (MA), Paraiba (PR), Pernambuco (PE), Piaui (PI), and Rio Grande do
# Norte (RN), and the eastern part of Para (PA) are all in BR1 without DST.

# From Marcos Tadeu (1998-09-27):
# 
# Brazilian official page
# 

# From Jesper Norgaard (2000-11-03):
# [For an official list of which regions in Brazil use which time zones, see:]
# http://pcdsh01.on.br/Fusbr.htm
# http://pcdsh01.on.br/Fusbrhv.htm

# From Celso Doria via David Madeo (2002-10-09):
# The reason for the delay this year has to do with elections in Brazil.
#
# Unlike in the United States, elections in Brazil are 100% computerized and
# the results are known almost immediately.  Yesterday, it was the first
# round of the elections when 115 million Brazilians voted for President,
# Governor, Senators, Federal Deputies, and State Deputies.  Nobody is
# counting (or re-counting) votes anymore and we know there will be a second
# round for the Presidency and also for some Governors.  The 2nd round will
# take place on October 27th.
#
# The reason why the DST will only begin November 3rd is that the thousands
# of electoral machines used cannot have their time changed, and since the
# Constitution says the elections must begin at 8:00 AM and end at 5:00 PM,
# the Government decided to postpone DST, instead of changing the Constitution
# (maybe, for the next elections, it will be possible to change the clock)...

# From Rodrigo Severo (2004-10-04):
# It's just the biannual change made necessary by the much hyped, supposedly
# modern Brazilian eletronic voting machines which, apparently, can't deal
# with a time change between the first and the second rounds of the elections.

# From Steffen Thorsen (2007-09-20):
# Brazil will start DST on 2007-10-14 00:00 and end on 2008-02-17 00:00:
# http://www.mme.gov.br/site/news/detail.do;jsessionid=BBA06811AFCAAC28F0285210913513DA?newsId=13975

# From Paul Schulze (2008-06-24):
# ...by law number 11.662 of April 24, 2008 (published in the "Diario
# Oficial da Uniao"...) in Brazil there are changes in the timezones,
# effective today (00:00am at June 24, 2008) as follows:
#
# a) The timezone UTC+5 is e[x]tinguished, with all the Acre state and the
# part of the Amazonas state that had this timezone now being put to the
# timezone UTC+4
# b) The whole Para state now is put at timezone UTC+3, instead of just
# part of it, as was before.
#
# This change follows a proposal of senator Tiao Viana of Acre state, that
# proposed it due to concerns about open television channels displaying
# programs inappropriate to youths in the states that had the timezone
# UTC+5 too early in the night. In the occasion, some more corrections
# were proposed, trying to unify the timezones of any given state. This
# change modifies timezone rules defined in decree 2.784 of 18 June,
# 1913.

# From Rodrigo Severo (2008-06-24):
# Just correcting the URL:
# 
# https://www.in.gov.br/imprensa/visualiza/index.jsp?jornal=do&secao=1&pagina=1&data=25/04/2008
# 
#
# As a result of the above Decree I believe the America/Rio_Branco
# timezone shall be modified from UTC-5 to UTC-4 and a new timezone shall
# be created to represent the...west side of the Para State. I
# suggest this new timezone be called Santarem as the most
# important/populated city in the affected area.
#
# This new timezone would be the same as the Rio_Branco timezone up to
# the 2008/06/24 change which would be to UTC-3 instead of UTC-4.

# From Alex Krivenyshev (2008-06-24):
# This is a quick reference page for New and Old Brazil Time Zones map.
# 
# http://www.worldtimezone.com/brazil-time-new-old.php
# 
#
# - 4 time zones replaced by 3 time zones-eliminating time zone UTC- 05
# (state Acre and the part of the Amazonas will be UTC/GMT- 04) - western
# part of Par state is moving to one timezone UTC- 03 (from UTC -04).

# From Paul Eggert (2002-10-10):
# The official decrees referenced below are mostly taken from
# 
# Decretos sobre o Horario de Verao no Brasil
# .

# From Steffen Thorsen (2008-08-29):
# As announced by the government and many newspapers in Brazil late
# yesterday, Brazil will start DST on 2008-10-19 (need to change rule) and
# it will end on 2009-02-15 (current rule for Brazil is fine). Based on
# past years experience with the elections, there was a good chance that
# the start was postponed to November, but it did not happen this year.
#
# It has not yet been posted to http://pcdsh01.on.br/DecHV.html
#
# An official page about it:
# 
# http://www.mme.gov.br/site/news/detail.do?newsId=16722
# 
# Note that this link does not always work directly, but must be accessed
# by going to
# 
# http://www.mme.gov.br/first
# 
#
# One example link that works directly:
# 
# http://jornale.com.br/index.php?option=com_content&task=view&id=13530&Itemid=54
# (Portuguese)
# 
#
# We have a written a short article about it as well:
# 
# http://www.timeanddate.com/news/time/brazil-dst-2008-2009.html
# 
#
# From Alexander Krivenyshev (2011-10-04):
# State Bahia will return to Daylight savings time this year after 8 years off.
# The announcement was made by Governor Jaques Wagner in an interview to a
# television station in Salvador.

# In Portuguese:
# 
# http://g1.globo.com/bahia/noticia/2011/10/governador-jaques-wagner-confirma-horario-de-verao-na-bahia.html
#  and
# 
# http://noticias.terra.com.br/brasil/noticias/0,,OI5390887-EI8139,00-Bahia+volta+a+ter+horario+de+verao+apos+oito+anos.html
# 

# From Guilherme Bernardes Rodrigues (2011-10-07):
# There is news in the media, however there is still no decree about it.
# I just send a e-mail to Zulmira Brandao at
# http://pcdsh01.on.br/ the
# official agency about time in Brazil, and she confirmed that the old rule is
# still in force.

# From Guilherme Bernardes Rodrigues (2011-10-14)
# It's official, the President signed a decree that includes Bahia in summer
# time.
#	 [ and in a second message (same day): ]
# I found the decree.
#
# DECRETO No- 7.584, DE 13 DE OUTUBRO DE 2011
# Link :
# 
# http://www.in.gov.br/visualiza/index.jsp?data=13/10/2011&jornal=1000&pagina=6&totalArquivos=6
# 

# From Kelley Cook (2012-10-16):
# The governor of state of Bahia in Brazil announced on Thursday that
# due to public pressure, he is reversing the DST policy they implemented
# last year and will not be going to Summer Time on October 21st....
# http://www.correio24horas.com.br/r/artigo/apos-pressoes-wagner-suspende-horario-de-verao-na-bahia

# From Rodrigo Severo (2012-10-16):
# Tocantins state will have DST.
# http://noticias.terra.com.br/brasil/noticias/0,,OI6232536-EI306.html

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# Decree 20,466 (1931-10-01)
# Decree 21,896 (1932-01-10)
Rule	Brazil	1931	only	-	Oct	 3	11:00	1:00	S
Rule	Brazil	1932	1933	-	Apr	 1	 0:00	0	-
Rule	Brazil	1932	only	-	Oct	 3	 0:00	1:00	S
# Decree 23,195 (1933-10-10)
# revoked DST.
# Decree 27,496 (1949-11-24)
# Decree 27,998 (1950-04-13)
Rule	Brazil	1949	1952	-	Dec	 1	 0:00	1:00	S
Rule	Brazil	1950	only	-	Apr	16	 1:00	0	-
Rule	Brazil	1951	1952	-	Apr	 1	 0:00	0	-
# Decree 32,308 (1953-02-24)
Rule	Brazil	1953	only	-	Mar	 1	 0:00	0	-
# Decree 34,724 (1953-11-30)
# revoked DST.
# Decree 52,700 (1963-10-18)
# established DST from 1963-10-23 00:00 to 1964-02-29 00:00
# in SP, RJ, GB, MG, ES, due to the prolongation of the drought.
# Decree 53,071 (1963-12-03)
# extended the above decree to all of the national territory on 12-09.
Rule	Brazil	1963	only	-	Dec	 9	 0:00	1:00	S
# Decree 53,604 (1964-02-25)
# extended summer time by one day to 1964-03-01 00:00 (start of school).
Rule	Brazil	1964	only	-	Mar	 1	 0:00	0	-
# Decree 55,639 (1965-01-27)
Rule	Brazil	1965	only	-	Jan	31	 0:00	1:00	S
Rule	Brazil	1965	only	-	Mar	31	 0:00	0	-
# Decree 57,303 (1965-11-22)
Rule	Brazil	1965	only	-	Dec	 1	 0:00	1:00	S
# Decree 57,843 (1966-02-18)
Rule	Brazil	1966	1968	-	Mar	 1	 0:00	0	-
Rule	Brazil	1966	1967	-	Nov	 1	 0:00	1:00	S
# Decree 63,429 (1968-10-15)
# revoked DST.
# Decree 91,698 (1985-09-27)
Rule	Brazil	1985	only	-	Nov	 2	 0:00	1:00	S
# Decree 92,310 (1986-01-21)
# Decree 92,463 (1986-03-13)
Rule	Brazil	1986	only	-	Mar	15	 0:00	0	-
# Decree 93,316 (1986-10-01)
Rule	Brazil	1986	only	-	Oct	25	 0:00	1:00	S
Rule	Brazil	1987	only	-	Feb	14	 0:00	0	-
# Decree 94,922 (1987-09-22)
Rule	Brazil	1987	only	-	Oct	25	 0:00	1:00	S
Rule	Brazil	1988	only	-	Feb	 7	 0:00	0	-
# Decree 96,676 (1988-09-12)
# except for the states of AC, AM, PA, RR, RO, and AP (then a territory)
Rule	Brazil	1988	only	-	Oct	16	 0:00	1:00	S
Rule	Brazil	1989	only	-	Jan	29	 0:00	0	-
# Decree 98,077 (1989-08-21)
# with the same exceptions
Rule	Brazil	1989	only	-	Oct	15	 0:00	1:00	S
Rule	Brazil	1990	only	-	Feb	11	 0:00	0	-
# Decree 99,530 (1990-09-17)
# adopted by RS, SC, PR, SP, RJ, ES, MG, GO, MS, DF.
# Decree 99,629 (1990-10-19) adds BA, MT.
Rule	Brazil	1990	only	-	Oct	21	 0:00	1:00	S
Rule	Brazil	1991	only	-	Feb	17	 0:00	0	-
# Unnumbered decree (1991-09-25)
# adopted by RS, SC, PR, SP, RJ, ES, MG, BA, GO, MT, MS, DF.
Rule	Brazil	1991	only	-	Oct	20	 0:00	1:00	S
Rule	Brazil	1992	only	-	Feb	 9	 0:00	0	-
# Unnumbered decree (1992-10-16)
# adopted by same states.
Rule	Brazil	1992	only	-	Oct	25	 0:00	1:00	S
Rule	Brazil	1993	only	-	Jan	31	 0:00	0	-
# Decree 942 (1993-09-28)
# adopted by same states, plus AM.
# Decree 1,252 (1994-09-22;
# web page corrected 2004-01-07) adopted by same states, minus AM.
# Decree 1,636 (1995-09-14)
# adopted by same states, plus MT and TO.
# Decree 1,674 (1995-10-13)
# adds AL, SE.
Rule	Brazil	1993	1995	-	Oct	Sun>=11	 0:00	1:00	S
Rule	Brazil	1994	1995	-	Feb	Sun>=15	 0:00	0	-
Rule	Brazil	1996	only	-	Feb	11	 0:00	0	-
# Decree 2,000 (1996-09-04)
# adopted by same states, minus AL, SE.
Rule	Brazil	1996	only	-	Oct	 6	 0:00	1:00	S
Rule	Brazil	1997	only	-	Feb	16	 0:00	0	-
# From Daniel C. Sobral (1998-02-12):
# In 1997, the DS began on October 6. The stated reason was that
# because international television networks ignored Brazil's policy on DS,
# they bought the wrong times on satellite for coverage of Pope's visit.
# This year, the ending date of DS was postponed to March 1
# to help dealing with the shortages of electric power.
#
# Decree 2,317 (1997-09-04), adopted by same states.
Rule	Brazil	1997	only	-	Oct	 6	 0:00	1:00	S
# Decree 2,495
# (1998-02-10)
Rule	Brazil	1998	only	-	Mar	 1	 0:00	0	-
# Decree 2,780 (1998-09-11)
# adopted by the same states as before.
Rule	Brazil	1998	only	-	Oct	11	 0:00	1:00	S
Rule	Brazil	1999	only	-	Feb	21	 0:00	0	-
# Decree 3,150
# (1999-08-23) adopted by same states.
# Decree 3,188 (1999-09-30)
# adds SE, AL, PB, PE, RN, CE, PI, MA and RR.
Rule	Brazil	1999	only	-	Oct	 3	 0:00	1:00	S
Rule	Brazil	2000	only	-	Feb	27	 0:00	0	-
# Decree 3,592 (2000-09-06)
# adopted by the same states as before.
# Decree 3,630 (2000-10-13)
# repeals DST in PE and RR, effective 2000-10-15 00:00.
# Decree 3,632 (2000-10-17)
# repeals DST in SE, AL, PB, RN, CE, PI and MA, effective 2000-10-22 00:00.
# Decree 3,916
# (2001-09-13) reestablishes DST in AL, CE, MA, PB, PE, PI, RN, SE.
Rule	Brazil	2000	2001	-	Oct	Sun>=8	 0:00	1:00	S
Rule	Brazil	2001	2006	-	Feb	Sun>=15	 0:00	0	-
# Decree 4,399 (2002-10-01) repeals DST in AL, CE, MA, PB, PE, PI, RN, SE.
# 4,399
Rule	Brazil	2002	only	-	Nov	 3	 0:00	1:00	S
# Decree 4,844 (2003-09-24; corrected 2003-09-26) repeals DST in BA, MT, TO.
# 4,844
Rule	Brazil	2003	only	-	Oct	19	 0:00	1:00	S
# Decree 5,223 (2004-10-01) reestablishes DST in MT.
# 5,223
Rule	Brazil	2004	only	-	Nov	 2	 0:00	1:00	S
# Decree 5,539 (2005-09-19),
# adopted by the same states as before.
Rule	Brazil	2005	only	-	Oct	16	 0:00	1:00	S
# Decree 5,920 (2006-10-03),
# adopted by the same states as before.
Rule	Brazil	2006	only	-	Nov	 5	 0:00	1:00	S
Rule	Brazil	2007	only	-	Feb	25	 0:00	0	-
# Decree 6,212 (2007-09-26),
# adopted by the same states as before.
Rule	Brazil	2007	only	-	Oct	Sun>=8	 0:00	1:00	S
# From Frederico A. C. Neves (2008-09-10):
# According to this decree
# 
# http://www.planalto.gov.br/ccivil_03/_Ato2007-2010/2008/Decreto/D6558.htm
# 
# [t]he DST period in Brazil now on will be from the 3rd Oct Sunday to the
# 3rd Feb Sunday. There is an exception on the return date when this is
# the Carnival Sunday then the return date will be the next Sunday...
Rule	Brazil	2008	max	-	Oct	Sun>=15	0:00	1:00	S
Rule	Brazil	2008	2011	-	Feb	Sun>=15	0:00	0	-
Rule	Brazil	2012	only	-	Feb	Sun>=22	0:00	0	-
Rule	Brazil	2013	2014	-	Feb	Sun>=15	0:00	0	-
Rule	Brazil	2015	only	-	Feb	Sun>=22	0:00	0	-
Rule	Brazil	2016	2022	-	Feb	Sun>=15	0:00	0	-
Rule	Brazil	2023	only	-	Feb	Sun>=22	0:00	0	-
Rule	Brazil	2024	2025	-	Feb	Sun>=15	0:00	0	-
Rule	Brazil	2026	only	-	Feb	Sun>=22	0:00	0	-
Rule	Brazil	2027	2033	-	Feb	Sun>=15	0:00	0	-
Rule	Brazil	2034	only	-	Feb	Sun>=22	0:00	0	-
Rule	Brazil	2035	2036	-	Feb	Sun>=15	0:00	0	-
Rule	Brazil	2037	only	-	Feb	Sun>=22	0:00	0	-
# From Arthur David Olson (2008-09-29):
# The next is wrong in some years but is better than nothing.
Rule	Brazil	2038	max	-	Feb	Sun>=15	0:00	0	-

# The latest ruleset listed above says that the following states observe DST:
# DF, ES, GO, MG, MS, MT, PR, RJ, RS, SC, SP.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
#
# Fernando de Noronha (administratively part of PE)
Zone America/Noronha	-2:09:40 -	LMT	1914
			-2:00	Brazil	FN%sT	1990 Sep 17
			-2:00	-	FNT	1999 Sep 30
			-2:00	Brazil	FN%sT	2000 Oct 15
			-2:00	-	FNT	2001 Sep 13
			-2:00	Brazil	FN%sT	2002 Oct  1
			-2:00	-	FNT
# Other Atlantic islands have no permanent settlement.
# These include Trindade and Martin Vaz (administratively part of ES),
# Atol das Rocas (RN), and Penedos de Sao Pedro e Sao Paulo (PE).
# Fernando de Noronha was a separate territory from 1942-09-02 to 1989-01-01;
# it also included the Penedos.
#
# Amapa (AP), east Para (PA)
# East Para includes Belem, Maraba, Serra Norte, and Sao Felix do Xingu.
# The division between east and west Para is the river Xingu.
# In the north a very small part from the river Javary (now Jari I guess,
# the border with Amapa) to the Amazon, then to the Xingu.
Zone America/Belem	-3:13:56 -	LMT	1914
			-3:00	Brazil	BR%sT	1988 Sep 12
			-3:00	-	BRT
#
# west Para (PA)
# West Para includes Altamira, Oribidos, Prainha, Oriximina, and Santarem.
Zone America/Santarem	-3:38:48 -	LMT	1914
			-4:00	Brazil	AM%sT	1988 Sep 12
			-4:00	-	AMT	2008 Jun 24 00:00
			-3:00	-	BRT
#
# Maranhao (MA), Piaui (PI), Ceara (CE), Rio Grande do Norte (RN),
# Paraiba (PB)
Zone America/Fortaleza	-2:34:00 -	LMT	1914
			-3:00	Brazil	BR%sT	1990 Sep 17
			-3:00	-	BRT	1999 Sep 30
			-3:00	Brazil	BR%sT	2000 Oct 22
			-3:00	-	BRT	2001 Sep 13
			-3:00	Brazil	BR%sT	2002 Oct  1
			-3:00	-	BRT
#
# Pernambuco (PE) (except Atlantic islands)
Zone America/Recife	-2:19:36 -	LMT	1914
			-3:00	Brazil	BR%sT	1990 Sep 17
			-3:00	-	BRT	1999 Sep 30
			-3:00	Brazil	BR%sT	2000 Oct 15
			-3:00	-	BRT	2001 Sep 13
			-3:00	Brazil	BR%sT	2002 Oct  1
			-3:00	-	BRT
#
# Tocantins (TO)
Zone America/Araguaina	-3:12:48 -	LMT	1914
			-3:00	Brazil	BR%sT	1990 Sep 17
			-3:00	-	BRT	1995 Sep 14
			-3:00	Brazil	BR%sT	2003 Sep 24
			-3:00	-	BRT	2012 Oct 21
			-3:00	Brazil	BR%sT
#
# Alagoas (AL), Sergipe (SE)
Zone America/Maceio	-2:22:52 -	LMT	1914
			-3:00	Brazil	BR%sT	1990 Sep 17
			-3:00	-	BRT	1995 Oct 13
			-3:00	Brazil	BR%sT	1996 Sep  4
			-3:00	-	BRT	1999 Sep 30
			-3:00	Brazil	BR%sT	2000 Oct 22
			-3:00	-	BRT	2001 Sep 13
			-3:00	Brazil	BR%sT	2002 Oct  1
			-3:00	-	BRT
#
# Bahia (BA)
# There are too many Salvadors elsewhere, so use America/Bahia instead
# of America/Salvador.
Zone America/Bahia	-2:34:04 -	LMT	1914
			-3:00	Brazil	BR%sT	2003 Sep 24
			-3:00	-	BRT	2011 Oct 16
			-3:00	Brazil	BR%sT	2012 Oct 21
			-3:00	-	BRT
#
# Goias (GO), Distrito Federal (DF), Minas Gerais (MG),
# Espirito Santo (ES), Rio de Janeiro (RJ), Sao Paulo (SP), Parana (PR),
# Santa Catarina (SC), Rio Grande do Sul (RS)
Zone America/Sao_Paulo	-3:06:28 -	LMT	1914
			-3:00	Brazil	BR%sT	1963 Oct 23 00:00
			-3:00	1:00	BRST	1964
			-3:00	Brazil	BR%sT
#
# Mato Grosso do Sul (MS)
Zone America/Campo_Grande -3:38:28 -	LMT	1914
			-4:00	Brazil	AM%sT
#
# Mato Grosso (MT)
Zone America/Cuiaba	-3:44:20 -	LMT	1914
			-4:00	Brazil	AM%sT	2003 Sep 24
			-4:00	-	AMT	2004 Oct  1
			-4:00	Brazil	AM%sT
#
# Rondonia (RO)
Zone America/Porto_Velho -4:15:36 -	LMT	1914
			-4:00	Brazil	AM%sT	1988 Sep 12
			-4:00	-	AMT
#
# Roraima (RR)
Zone America/Boa_Vista	-4:02:40 -	LMT	1914
			-4:00	Brazil	AM%sT	1988 Sep 12
			-4:00	-	AMT	1999 Sep 30
			-4:00	Brazil	AM%sT	2000 Oct 15
			-4:00	-	AMT
#
# east Amazonas (AM): Boca do Acre, Jutai, Manaus, Floriano Peixoto
# The great circle line from Tabatinga to Porto Acre divides
# east from west Amazonas.
Zone America/Manaus	-4:00:04 -	LMT	1914
			-4:00	Brazil	AM%sT	1988 Sep 12
			-4:00	-	AMT	1993 Sep 28
			-4:00	Brazil	AM%sT	1994 Sep 22
			-4:00	-	AMT
#
# west Amazonas (AM): Atalaia do Norte, Boca do Maoco, Benjamin Constant,
#	Eirunepe, Envira, Ipixuna
Zone America/Eirunepe	-4:39:28 -	LMT	1914
			-5:00	Brazil	AC%sT	1988 Sep 12
			-5:00	-	ACT	1993 Sep 28
			-5:00	Brazil	AC%sT	1994 Sep 22
			-5:00	-	ACT	2008 Jun 24 00:00
			-4:00	-	AMT
#
# Acre (AC)
Zone America/Rio_Branco	-4:31:12 -	LMT	1914
			-5:00	Brazil	AC%sT	1988 Sep 12
			-5:00	-	ACT	2008 Jun 24 00:00
			-4:00	-	AMT

# Chile

# From Eduardo Krell (1995-10-19):
# The law says to switch to DST at midnight [24:00] on the second SATURDAY
# of October....  The law is the same for March and October.
# (1998-09-29):
# Because of the drought this year, the government decided to go into
# DST earlier (saturday 9/26 at 24:00). This is a one-time change only ...
# (unless there's another dry season next year, I guess).

# From Julio I. Pacheco Troncoso (1999-03-18):
# Because of the same drought, the government decided to end DST later,
# on April 3, (one-time change).

# From Oscar van Vlijmen (2006-10-08):
# http://www.horaoficial.cl/cambio.htm

# From Jesper Norgaard Welen (2006-10-08):
# I think that there are some obvious mistakes in the suggested link
# from Oscar van Vlijmen,... for instance entry 66 says that GMT-4
# ended 1990-09-12 while entry 67 only begins GMT-3 at 1990-09-15
# (they should have been 1990-09-15 and 1990-09-16 respectively), but
# anyhow it clears up some doubts too.

# From Paul Eggert (2006-12-27):
# The following data for Chile and America/Santiago are from
#  (2006-09-20), transcribed by
# Jesper Norgaard Welen.  The data for Pacific/Easter are from Shanks
# & Pottenger, except with DST transitions after 1932 cloned from
# America/Santiago.  The pre-1980 Pacific/Easter data are dubious,
# but we have no other source.

# From German Poo-Caaman~o (2008-03-03):
# Due to drought, Chile extends Daylight Time in three weeks.  This
# is one-time change (Saturday 3/29 at 24:00 for America/Santiago
# and Saturday 3/29 at 22:00 for Pacific/Easter)
# The Supreme Decree is located at
# 
# http://www.shoa.cl/servicios/supremo316.pdf
# 
# and the instructions for 2008 are located in:
# 
# http://www.horaoficial.cl/cambio.htm
# .

# From Jose Miguel Garrido (2008-03-05):
# ...
# You could see the announces of the change on
# 
# http://www.shoa.cl/noticias/2008/04hora/hora.htm
# .

# From Angel Chiang (2010-03-04):
# Subject: DST in Chile exceptionally extended to 3 April due to earthquake
# 
# http://www.gobiernodechile.cl/viewNoticia.aspx?idArticulo=30098
# 
# (in Spanish, last paragraph).
#
# This is breaking news. There should be more information available later.

# From Arthur Daivd Olson (2010-03-06):
# Angel Chiang's message confirmed by Julio Pacheco; Julio provided a patch.

# From Glenn Eychaner (2011-03-02): [geychaner@mac.com]
# It appears that the Chilean government has decided to postpone the
# change from summer time to winter time again, by three weeks to April
# 2nd:
# 
# http://www.emol.com/noticias/nacional/detalle/detallenoticias.asp?idnoticia=467651
# 
#
# This is not yet reflected in the official "cambio de hora" site, but
# probably will be soon:
# 
# http://www.horaoficial.cl/cambio.htm
# 

# From Arthur David Olson (2011-03-02):
# The emol.com article mentions a water shortage as the cause of the
# postponement, which may mean that it's not a permanent change.

# From Glenn Eychaner (2011-03-28):
# The article:
# 
# http://diario.elmercurio.com/2011/03/28/_portada/_portada/noticias/7565897A-CA86-49E6-9E03-660B21A4883E.htm?id=3D{7565897A-CA86-49E6-9E03-660B21A4883E}
# 
#
# In English:
# Chile's clocks will go back an hour this year on the 7th of May instead
# of this Saturday. They will go forward again the 3rd Saturday in
# August, not in October as they have since 1968. This is a pilot plan
# which will be reevaluated in 2012.

# From Mauricio Parada (2012-02-22), translated by Glenn Eychaner (2012-02-23):
# As stated in the website of the Chilean Energy Ministry
# http://www.minenergia.cl/ministerio/noticias/generales/gobierno-anuncia-fechas-de-cambio-de.html
# The Chilean Government has decided to postpone the entrance into winter time
# (to leave DST) from March 11 2012 to April 28th 2012. The decision has not
# been yet formalized but it will within the next days.
# Quote from the website communication:
#
# 6. For the year 2012, the dates of entry into winter time will be as follows:
# a. Saturday April 28, 2012, clocks should go back 60 minutes; that is, at
# 23:59:59, instead of passing to 0:00, the time should be adjusted to be 23:00
# of the same day.
# b. Saturday, September 1, 2012, clocks should go forward 60 minutes; that is,
# at 23:59:59, instead of passing to 0:00, the time should be adjusted to be
# 01:00 on September 2.

# From Steffen Thorsen (2013-02-15):
# According to several news sources, Chile has extended DST this year,
# they will end DST later and start DST earlier than planned.  They
# hope to save energy.  The new end date is 2013-04-28 00:00 and new
# start date is 2013-09-08 00:00....
# http://www.gob.cl/informa/2013/02/15/gobierno-anuncia-fechas-de-cambio-de-hora-para-el-ano-2013.htm

# NOTE: ChileAQ rules for Antarctic bases are stored separately in the
# 'antarctica' file.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Chile	1927	1932	-	Sep	 1	0:00	1:00	S
Rule	Chile	1928	1932	-	Apr	 1	0:00	0	-
Rule	Chile	1942	only	-	Jun	 1	4:00u	0	-
Rule	Chile	1942	only	-	Aug	 1	5:00u	1:00	S
Rule	Chile	1946	only	-	Jul	15	4:00u	1:00	S
Rule	Chile	1946	only	-	Sep	 1	3:00u	0:00	-
Rule	Chile	1947	only	-	Apr	 1	4:00u	0	-
Rule	Chile	1968	only	-	Nov	 3	4:00u	1:00	S
Rule	Chile	1969	only	-	Mar	30	3:00u	0	-
Rule	Chile	1969	only	-	Nov	23	4:00u	1:00	S
Rule	Chile	1970	only	-	Mar	29	3:00u	0	-
Rule	Chile	1971	only	-	Mar	14	3:00u	0	-
Rule	Chile	1970	1972	-	Oct	Sun>=9	4:00u	1:00	S
Rule	Chile	1972	1986	-	Mar	Sun>=9	3:00u	0	-
Rule	Chile	1973	only	-	Sep	30	4:00u	1:00	S
Rule	Chile	1974	1987	-	Oct	Sun>=9	4:00u	1:00	S
Rule	Chile	1987	only	-	Apr	12	3:00u	0	-
Rule	Chile	1988	1989	-	Mar	Sun>=9	3:00u	0	-
Rule	Chile	1988	only	-	Oct	Sun>=1	4:00u	1:00	S
Rule	Chile	1989	only	-	Oct	Sun>=9	4:00u	1:00	S
Rule	Chile	1990	only	-	Mar	18	3:00u	0	-
Rule	Chile	1990	only	-	Sep	16	4:00u	1:00	S
Rule	Chile	1991	1996	-	Mar	Sun>=9	3:00u	0	-
Rule	Chile	1991	1997	-	Oct	Sun>=9	4:00u	1:00	S
Rule	Chile	1997	only	-	Mar	30	3:00u	0	-
Rule	Chile	1998	only	-	Mar	Sun>=9	3:00u	0	-
Rule	Chile	1998	only	-	Sep	27	4:00u	1:00	S
Rule	Chile	1999	only	-	Apr	 4	3:00u	0	-
Rule	Chile	1999	2010	-	Oct	Sun>=9	4:00u	1:00	S
Rule	Chile	2000	2007	-	Mar	Sun>=9	3:00u	0	-
# N.B.: the end of March 29 in Chile is March 30 in Universal time,
# which is used below in specifying the transition.
Rule	Chile	2008	only	-	Mar	30	3:00u	0	-
Rule	Chile	2009	only	-	Mar	Sun>=9	3:00u	0	-
Rule	Chile	2010	only	-	Apr	Sun>=1	3:00u	0	-
Rule	Chile	2011	only	-	May	Sun>=2	3:00u	0	-
Rule	Chile	2011	only	-	Aug	Sun>=16	4:00u	1:00	S
Rule	Chile	2012	max	-	Apr	Sun>=23	3:00u	0	-
Rule	Chile	2012	max	-	Sep	Sun>=2	4:00u	1:00	S
# IATA SSIM anomalies: (1992-02) says 1992-03-14;
# (1996-09) says 1998-03-08.  Ignore these.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Santiago	-4:42:46 -	LMT	1890
			-4:42:46 -	SMT	1910 	    # Santiago Mean Time
			-5:00	-	CLT	1916 Jul  1 # Chile Time
			-4:42:46 -	SMT	1918 Sep  1 # Santiago Mean Time
			-4:00	-	CLT	1919 Jul  1 # Chile Time
			-4:42:46 -	SMT	1927 Sep  1 # Santiago Mean Time
			-5:00	Chile	CL%sT	1947 May 22 # Chile Time
			-4:00	Chile	CL%sT
Zone Pacific/Easter	-7:17:44 -	LMT	1890
			-7:17:28 -	EMT	1932 Sep    # Easter Mean Time
			-7:00	Chile	EAS%sT	1982 Mar 13 21:00 # Easter I Time
			-6:00	Chile	EAS%sT
#
# Sala y Gomez Island is like Pacific/Easter.
# Other Chilean locations, including Juan Fernandez Is, San Ambrosio,
# San Felix, and Antarctic bases, are like America/Santiago.

# Colombia

# Milne gives 4:56:16.4 for Bogota time in 1899; round to nearest.  He writes,
# "A variation of fifteen minutes in the public clocks of Bogota is not rare."

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	CO	1992	only	-	May	 3	0:00	1:00	S
Rule	CO	1993	only	-	Apr	 4	0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Bogota	-4:56:16 -	LMT	1884 Mar 13
			-4:56:16 -	BMT	1914 Nov 23 # Bogota Mean Time
			-5:00	CO	CO%sT	# Colombia Time
# Malpelo, Providencia, San Andres
# no information; probably like America/Bogota

# Curacao

# Milne gives 4:35:46.9 for Curacao mean time; round to nearest.
#
# From Paul Eggert (2006-03-22):
# Shanks & Pottenger say that The Bottom and Philipsburg have been at
# -4:00 since standard time was introduced on 1912-03-02; and that
# Kralendijk and Rincon used Kralendijk Mean Time (-4:33:08) from
# 1912-02-02 to 1965-01-01.  The former is dubious, since S&P also say
# Saba Island has been like Curacao.
# This all predates our 1970 cutoff, though.
#
# By July 2007 Curacao and St Maarten are planned to become
# associated states within the Netherlands, much like Aruba;
# Bonaire, Saba and St Eustatius would become directly part of the
# Netherlands as Kingdom Islands.  This won't affect their time zones
# though, as far as we know.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Curacao	-4:35:47 -	LMT	1912 Feb 12	# Willemstad
			-4:30	-	ANT	1965 # Netherlands Antilles Time
			-4:00	-	AST

# From Arthur David Olson (2011-06-15):
# At least for now, use links for places with new iso3166 codes.
# The name "Lower Prince's Quarter" is both longer than fourteen charaters
# and contains an apostrophe; use "Lower_Princes" below.

Link	America/Curacao	America/Lower_Princes # Sint Maarten
Link	America/Curacao	America/Kralendijk # Bonaire, Sint Estatius and Saba

# Ecuador
#
# Milne says the Sentral and South American Telegraph Company used -5:24:15.
#
# From Paul Eggert (2007-03-04):
# Apparently Ecuador had a failed experiment with DST in 1992.
#  (2007-02-27) and
#  (2006-11-06) both
# talk about "hora Sixto".  Leave this alone for now, as we have no data.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Guayaquil	-5:19:20 -	LMT	1890
			-5:14:00 -	QMT	1931 # Quito Mean Time
			-5:00	-	ECT	     # Ecuador Time
Zone Pacific/Galapagos	-5:58:24 -	LMT	1931 # Puerto Baquerizo Moreno
			-5:00	-	ECT	1986
			-6:00	-	GALT	     # Galapagos Time

# Falklands

# From Paul Eggert (2006-03-22):
# Between 1990 and 2000 inclusive, Shanks & Pottenger and the IATA agree except
# the IATA gives 1996-09-08.  Go with Shanks & Pottenger.

# From Falkland Islands Government Office, London (2001-01-22)
# via Jesper Norgaard:
# ... the clocks revert back to Local Mean Time at 2 am on Sunday 15
# April 2001 and advance one hour to summer time at 2 am on Sunday 2
# September.  It is anticipated that the clocks will revert back at 2
# am on Sunday 21 April 2002 and advance to summer time at 2 am on
# Sunday 1 September.

# From Rives McDow (2001-02-13):
#
# I have communicated several times with people there, and the last
# time I had communications that was helpful was in 1998.  Here is
# what was said then:
#
# "The general rule was that Stanley used daylight saving and the Camp
# did not. However for various reasons many people in the Camp have
# started to use daylight saving (known locally as 'Stanley Time')
# There is no rule as to who uses daylight saving - it is a matter of
# personal choice and so it is impossible to draw a map showing who
# uses it and who does not. Any list would be out of date as soon as
# it was produced. This year daylight saving ended on April 18/19th
# and started again on September 12/13th.  I do not know what the rule
# is, but can find out if you like.  We do not change at the same time
# as UK or Chile."
#
# I did have in my notes that the rule was "Second Saturday in Sep at
# 0:00 until third Saturday in Apr at 0:00".  I think that this does
# not agree in some cases with Shanks; is this true?
#
# Also, there is no mention in the list that some areas in the
# Falklands do not use DST.  I have found in my communications there
# that these areas are on the western half of East Falkland and all of
# West Falkland.  Stanley is the only place that consistently observes
# DST.  Again, as in other places in the world, the farmers don't like
# it.  West Falkland is almost entirely sheep farmers.
#
# I know one lady there that keeps a list of which farm keeps DST and
# which doesn't each year.  She runs a shop in Stanley, and says that
# the list changes each year.  She uses it to communicate to her
# customers, catching them when they are home for lunch or dinner.

# From Paul Eggert (2001-03-05):
# For now, we'll just record the time in Stanley, since we have no
# better info.

# From Steffen Thorsen (2011-04-01):
# The Falkland Islands will not turn back clocks this winter, but stay on
# daylight saving time.
#
# One source:
# 
# http://www.falklandnews.com/public/story.cfm?get=5914&source=3
# 
#
# We have gotten this confirmed by a clerk of the legislative assembly:
# Normally the clocks revert to Local Mean Time (UTC/GMT -4 hours) on the
# third Sunday of April at 0200hrs and advance to Summer Time (UTC/GMT -3
# hours) on the first Sunday of September at 0200hrs.
#
# IMPORTANT NOTE: During 2011, on a trial basis, the Falkland Islands
# will not revert to local mean time, but clocks will remain on Summer
# time (UTC/GMT - 3 hours) throughout the whole of 2011.  Any long term
# change to local time following the trial period will be notified.
#
# From Andrew Newman (2012-02-24)
# A letter from Justin McPhee, Chief Executive,
# Cable & Wireless Falkland Islands (dated 2012-02-22)
# states...
#   The current Atlantic/Stanley entry under South America expects the
#   clocks to go back to standard Falklands Time (FKT) on the 15th April.
#   The database entry states that in 2011 Stanley was staying on fixed
#   summer time on a trial basis only.  FIG need to contact IANA and/or
#   the maintainers of the database to inform them we're adopting
#   the same policy this year and suggest recommendations for future years.
#
# For now we will assume permanent summer time for the Falklands
# until advised differently (to apply for 2012 and beyond, after the 2011
# experiment was apparently successful.)
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Falk	1937	1938	-	Sep	lastSun	0:00	1:00	S
Rule	Falk	1938	1942	-	Mar	Sun>=19	0:00	0	-
Rule	Falk	1939	only	-	Oct	1	0:00	1:00	S
Rule	Falk	1940	1942	-	Sep	lastSun	0:00	1:00	S
Rule	Falk	1943	only	-	Jan	1	0:00	0	-
Rule	Falk	1983	only	-	Sep	lastSun	0:00	1:00	S
Rule	Falk	1984	1985	-	Apr	lastSun	0:00	0	-
Rule	Falk	1984	only	-	Sep	16	0:00	1:00	S
Rule	Falk	1985	2000	-	Sep	Sun>=9	0:00	1:00	S
Rule	Falk	1986	2000	-	Apr	Sun>=16	0:00	0	-
Rule	Falk	2001	2010	-	Apr	Sun>=15	2:00	0	-
Rule	Falk	2001	2010	-	Sep	Sun>=1	2:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Atlantic/Stanley	-3:51:24 -	LMT	1890
			-3:51:24 -	SMT	1912 Mar 12  # Stanley Mean Time
			-4:00	Falk	FK%sT	1983 May     # Falkland Is Time
			-3:00	Falk	FK%sT	1985 Sep 15
			-4:00	Falk	FK%sT	2010 Sep 5 02:00
			-3:00	-	FKST

# French Guiana
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Cayenne	-3:29:20 -	LMT	1911 Jul
			-4:00	-	GFT	1967 Oct # French Guiana Time
			-3:00	-	GFT

# Guyana
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Guyana	-3:52:40 -	LMT	1915 Mar	# Georgetown
			-3:45	-	GBGT	1966 May 26 # Br Guiana Time
			-3:45	-	GYT	1975 Jul 31 # Guyana Time
			-3:00	-	GYT	1991
# IATA SSIM (1996-06) says -4:00.  Assume a 1991 switch.
			-4:00	-	GYT

# Paraguay
# From Paul Eggert (2006-03-22):
# Shanks & Pottenger say that spring transitions are from 01:00 -> 02:00,
# and autumn transitions are from 00:00 -> 23:00.  Go with pre-1999
# editions of Shanks, and with the IATA, who say transitions occur at 00:00.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Para	1975	1988	-	Oct	 1	0:00	1:00	S
Rule	Para	1975	1978	-	Mar	 1	0:00	0	-
Rule	Para	1979	1991	-	Apr	 1	0:00	0	-
Rule	Para	1989	only	-	Oct	22	0:00	1:00	S
Rule	Para	1990	only	-	Oct	 1	0:00	1:00	S
Rule	Para	1991	only	-	Oct	 6	0:00	1:00	S
Rule	Para	1992	only	-	Mar	 1	0:00	0	-
Rule	Para	1992	only	-	Oct	 5	0:00	1:00	S
Rule	Para	1993	only	-	Mar	31	0:00	0	-
Rule	Para	1993	1995	-	Oct	 1	0:00	1:00	S
Rule	Para	1994	1995	-	Feb	lastSun	0:00	0	-
Rule	Para	1996	only	-	Mar	 1	0:00	0	-
# IATA SSIM (2000-02) says 1999-10-10; ignore this for now.
# From Steffen Thorsen (2000-10-02):
# I have three independent reports that Paraguay changed to DST this Sunday
# (10-01).
#
# Translated by Gwillim Law (2001-02-27) from
# 
# Noticias, a daily paper in Asuncion, Paraguay (2000-10-01)
# :
# Starting at 0:00 today, the clock will be set forward 60 minutes, in
# fulfillment of Decree No. 7,273 of the Executive Power....  The time change
# system has been operating for several years.  Formerly there was a separate
# decree each year; the new law has the same effect, but permanently.  Every
# year, the time will change on the first Sunday of October; likewise, the
# clock will be set back on the first Sunday of March.
#
Rule	Para	1996	2001	-	Oct	Sun>=1	0:00	1:00	S
# IATA SSIM (1997-09) says Mar 1; go with Shanks & Pottenger.
Rule	Para	1997	only	-	Feb	lastSun	0:00	0	-
# Shanks & Pottenger say 1999-02-28; IATA SSIM (1999-02) says 1999-02-27, but
# (1999-09) reports no date; go with above sources and Gerd Knops (2001-02-27).
Rule	Para	1998	2001	-	Mar	Sun>=1	0:00	0	-
# From Rives McDow (2002-02-28):
# A decree was issued in Paraguay (no. 16350) on 2002-02-26 that changed the
# dst method to be from the first Sunday in September to the first Sunday in
# April.
Rule	Para	2002	2004	-	Apr	Sun>=1	0:00	0	-
Rule	Para	2002	2003	-	Sep	Sun>=1	0:00	1:00	S
#
# From Jesper Norgaard Welen (2005-01-02):
# There are several sources that claim that Paraguay made
# a timezone rule change in autumn 2004.
# From Steffen Thorsen (2005-01-05):
# Decree 1,867 (2004-03-05)
# From Carlos Raul Perasso via Jesper Norgaard Welen (2006-10-13)
# 
Rule	Para	2004	2009	-	Oct	Sun>=15	0:00	1:00	S
Rule	Para	2005	2009	-	Mar	Sun>=8	0:00	0	-
# From Carlos Raul Perasso (2010-02-18):
# By decree number 3958 issued yesterday (
# 
# http://www.presidencia.gov.py/v1/wp-content/uploads/2010/02/decreto3958.pdf
# 
# )
# Paraguay changes its DST schedule, postponing the March rule to April and
# modifying the October date. The decree reads:
# ...
# Art. 1. It is hereby established that from the second Sunday of the month of
# April of this year (2010), the official time is to be set back 60 minutes,
# and that on the first Sunday of the month of October, it is to be set
# forward 60 minutes, in all the territory of the Paraguayan Republic.
# ...
Rule	Para	2010	max	-	Oct	Sun>=1	0:00	1:00	S
Rule	Para	2010	2012	-	Apr	Sun>=8	0:00	0	-
#
# From Steffen Thorsen (2013-03-07):
# Paraguay will end DST on 2013-03-24 00:00....
# http://www.ande.gov.py/interna.php?id=1075
#
# From Carlos Raul Perasso (2013-03-15):
# The change in Paraguay is now final.  Decree number 10780
# http://www.presidencia.gov.py/uploads/pdf/presidencia-3b86ff4b691c79d4f5927ca964922ec74772ce857c02ca054a52a37b49afc7fb.pdf
Rule	Para	2013	max	-	Mar	Sun>=22	0:00	0	-

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Asuncion	-3:50:40 -	LMT	1890
			-3:50:40 -	AMT	1931 Oct 10 # Asuncion Mean Time
			-4:00	-	PYT	1972 Oct # Paraguay Time
			-3:00	-	PYT	1974 Apr
			-4:00	Para	PY%sT

# Peru
#
# 
# From Evelyn C. Leeper via Mark Brader (2003-10-26):
# When we were in Peru in 1985-1986, they apparently switched over
# sometime between December 29 and January 3 while we were on the Amazon.
#
# From Paul Eggert (2006-03-22):
# Shanks & Pottenger don't have this transition.  Assume 1986 was like 1987.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Peru	1938	only	-	Jan	 1	0:00	1:00	S
Rule	Peru	1938	only	-	Apr	 1	0:00	0	-
Rule	Peru	1938	1939	-	Sep	lastSun	0:00	1:00	S
Rule	Peru	1939	1940	-	Mar	Sun>=24	0:00	0	-
Rule	Peru	1986	1987	-	Jan	 1	0:00	1:00	S
Rule	Peru	1986	1987	-	Apr	 1	0:00	0	-
Rule	Peru	1990	only	-	Jan	 1	0:00	1:00	S
Rule	Peru	1990	only	-	Apr	 1	0:00	0	-
# IATA is ambiguous for 1993/1995; go with Shanks & Pottenger.
Rule	Peru	1994	only	-	Jan	 1	0:00	1:00	S
Rule	Peru	1994	only	-	Apr	 1	0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Lima	-5:08:12 -	LMT	1890
			-5:08:36 -	LMT	1908 Jul 28 # Lima Mean Time?
			-5:00	Peru	PE%sT	# Peru Time

# South Georgia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Atlantic/South_Georgia -2:26:08 -	LMT	1890		# Grytviken
			-2:00	-	GST	# South Georgia Time

# South Sandwich Is
# uninhabited; scientific personnel have wintered

# Suriname
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Paramaribo	-3:40:40 -	LMT	1911
			-3:40:52 -	PMT	1935     # Paramaribo Mean Time
			-3:40:36 -	PMT	1945 Oct # The capital moved?
			-3:30	-	NEGT	1975 Nov 20 # Dutch Guiana Time
			-3:30	-	SRT	1984 Oct # Suriname Time
			-3:00	-	SRT

# Trinidad and Tobago
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Port_of_Spain -4:06:04 -	LMT	1912 Mar 2
			-4:00	-	AST

# Uruguay
# From Paul Eggert (1993-11-18):
# Uruguay wins the prize for the strangest peacetime manipulation of the rules.
# From Shanks & Pottenger:
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# Whitman gives 1923 Oct 1; go with Shanks & Pottenger.
Rule	Uruguay	1923	only	-	Oct	 2	 0:00	0:30	HS
Rule	Uruguay	1924	1926	-	Apr	 1	 0:00	0	-
Rule	Uruguay	1924	1925	-	Oct	 1	 0:00	0:30	HS
Rule	Uruguay	1933	1935	-	Oct	lastSun	 0:00	0:30	HS
# Shanks & Pottenger give 1935 Apr 1 0:00 & 1936 Mar 30 0:00; go with Whitman.
Rule	Uruguay	1934	1936	-	Mar	Sat>=25	23:30s	0	-
Rule	Uruguay	1936	only	-	Nov	 1	 0:00	0:30	HS
Rule	Uruguay	1937	1941	-	Mar	lastSun	 0:00	0	-
# Whitman gives 1937 Oct 3; go with Shanks & Pottenger.
Rule	Uruguay	1937	1940	-	Oct	lastSun	 0:00	0:30	HS
# Whitman gives 1941 Oct 24 - 1942 Mar 27, 1942 Dec 14 - 1943 Apr 13,
# and 1943 Apr 13 ``to present time''; go with Shanks & Pottenger.
Rule	Uruguay	1941	only	-	Aug	 1	 0:00	0:30	HS
Rule	Uruguay	1942	only	-	Jan	 1	 0:00	0	-
Rule	Uruguay	1942	only	-	Dec	14	 0:00	1:00	S
Rule	Uruguay	1943	only	-	Mar	14	 0:00	0	-
Rule	Uruguay	1959	only	-	May	24	 0:00	1:00	S
Rule	Uruguay	1959	only	-	Nov	15	 0:00	0	-
Rule	Uruguay	1960	only	-	Jan	17	 0:00	1:00	S
Rule	Uruguay	1960	only	-	Mar	 6	 0:00	0	-
Rule	Uruguay	1965	1967	-	Apr	Sun>=1	 0:00	1:00	S
Rule	Uruguay	1965	only	-	Sep	26	 0:00	0	-
Rule	Uruguay	1966	1967	-	Oct	31	 0:00	0	-
Rule	Uruguay	1968	1970	-	May	27	 0:00	0:30	HS
Rule	Uruguay	1968	1970	-	Dec	 2	 0:00	0	-
Rule	Uruguay	1972	only	-	Apr	24	 0:00	1:00	S
Rule	Uruguay	1972	only	-	Aug	15	 0:00	0	-
Rule	Uruguay	1974	only	-	Mar	10	 0:00	0:30	HS
Rule	Uruguay	1974	only	-	Dec	22	 0:00	1:00	S
Rule	Uruguay	1976	only	-	Oct	 1	 0:00	0	-
Rule	Uruguay	1977	only	-	Dec	 4	 0:00	1:00	S
Rule	Uruguay	1978	only	-	Apr	 1	 0:00	0	-
Rule	Uruguay	1979	only	-	Oct	 1	 0:00	1:00	S
Rule	Uruguay	1980	only	-	May	 1	 0:00	0	-
Rule	Uruguay	1987	only	-	Dec	14	 0:00	1:00	S
Rule	Uruguay	1988	only	-	Mar	14	 0:00	0	-
Rule	Uruguay	1988	only	-	Dec	11	 0:00	1:00	S
Rule	Uruguay	1989	only	-	Mar	12	 0:00	0	-
Rule	Uruguay	1989	only	-	Oct	29	 0:00	1:00	S
# Shanks & Pottenger say no DST was observed in 1990/1 and 1991/2,
# and that 1992/3's DST was from 10-25 to 03-01.  Go with IATA.
Rule	Uruguay	1990	1992	-	Mar	Sun>=1	 0:00	0	-
Rule	Uruguay	1990	1991	-	Oct	Sun>=21	 0:00	1:00	S
Rule	Uruguay	1992	only	-	Oct	18	 0:00	1:00	S
Rule	Uruguay	1993	only	-	Feb	28	 0:00	0	-
# From Eduardo Cota (2004-09-20):
# The uruguayan government has decreed a change in the local time....
# http://www.presidencia.gub.uy/decretos/2004091502.htm
Rule	Uruguay	2004	only	-	Sep	19	 0:00	1:00	S
# From Steffen Thorsen (2005-03-11):
# Uruguay's DST was scheduled to end on Sunday, 2005-03-13, but in order to
# save energy ... it was postponed two weeks....
# http://www.presidencia.gub.uy/_Web/noticias/2005/03/2005031005.htm
Rule	Uruguay	2005	only	-	Mar	27	 2:00	0	-
# From Eduardo Cota (2005-09-27):
# http://www.presidencia.gub.uy/_Web/decretos/2005/09/CM%20119_09%2009%202005_00001.PDF
# This means that from 2005-10-09 at 02:00 local time, until 2006-03-12 at
# 02:00 local time, official time in Uruguay will be at GMT -2.
Rule	Uruguay	2005	only	-	Oct	 9	 2:00	1:00	S
Rule	Uruguay	2006	only	-	Mar	12	 2:00	0	-
# From Jesper Norgaard Welen (2006-09-06):
# http://www.presidencia.gub.uy/_web/decretos/2006/09/CM%20210_08%2006%202006_00001.PDF
Rule	Uruguay	2006	max	-	Oct	Sun>=1	 2:00	1:00	S
Rule	Uruguay	2007	max	-	Mar	Sun>=8	 2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Montevideo	-3:44:44 -	LMT	1898 Jun 28
			-3:44:44 -	MMT	1920 May  1	# Montevideo MT
			-3:30	Uruguay	UY%sT	1942 Dec 14	# Uruguay Time
			-3:00	Uruguay	UY%sT

# Venezuela
#
# From John Stainforth (2007-11-28):
# ... the change for Venezuela originally expected for 2007-12-31 has
# been brought forward to 2007-12-09.  The official announcement was
# published today in the "Gaceta Oficial de la Republica Bolivariana
# de Venezuela, numero 38.819" (official document for all laws or
# resolution publication)
# http://www.globovision.com/news.php?nid=72208

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	America/Caracas	-4:27:44 -	LMT	1890
			-4:27:40 -	CMT	1912 Feb 12 # Caracas Mean Time?
			-4:30	-	VET	1965	     # Venezuela Time
			-4:00	-	VET	2007 Dec  9 03:00
			-4:30	-	VET
joda-time-2.3/src/main/java/org/joda/time/tz/src/etcetera0000644000175000017500000000561312137470245022632 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# These entries are mostly present for historical reasons, so that
# people in areas not otherwise covered by the tz files could "zic -l"
# to a time zone that was right for their area.  These days, the
# tz files cover almost all the inhabited world, and the only practical
# need now for the entries that are not on UTC are for ships at sea
# that cannot use POSIX TZ settings.

Zone	Etc/GMT		0	-	GMT
Zone	Etc/UTC		0	-	UTC
Zone	Etc/UCT		0	-	UCT

# The following link uses older naming conventions,
# but it belongs here, not in the file `backward',
# as functions like gmtime load the "GMT" file to handle leap seconds properly.
# We want this to work even on installations that omit the other older names.
Link	Etc/GMT				GMT

Link	Etc/UTC				Etc/Universal
Link	Etc/UTC				Etc/Zulu

Link	Etc/GMT				Etc/Greenwich
Link	Etc/GMT				Etc/GMT-0
Link	Etc/GMT				Etc/GMT+0
Link	Etc/GMT				Etc/GMT0

# We use POSIX-style signs in the Zone names and the output abbreviations,
# even though this is the opposite of what many people expect.
# POSIX has positive signs west of Greenwich, but many people expect
# positive signs east of Greenwich.  For example, TZ='Etc/GMT+4' uses
# the abbreviation "GMT+4" and corresponds to 4 hours behind UTC
# (i.e. west of Greenwich) even though many people would expect it to
# mean 4 hours ahead of UTC (i.e. east of Greenwich).
#
# In the draft 5 of POSIX 1003.1-200x, the angle bracket notation allows for
# TZ='+4'; if you want time zone abbreviations conforming to
# ISO 8601 you can use TZ='<-0400>+4'.  Thus the commonly-expected
# offset is kept within the angle bracket (and is used for display)
# while the POSIX sign is kept outside the angle bracket (and is used
# for calculation).
#
# Do not use a TZ setting like TZ='GMT+4', which is four hours behind
# GMT but uses the completely misleading abbreviation "GMT".

# Earlier incarnations of this package were not POSIX-compliant,
# and had lines such as
#		Zone	GMT-12		-12	-	GMT-1200
# We did not want things to change quietly if someone accustomed to the old
# way does a
#		zic -l GMT-12
# so we moved the names into the Etc subdirectory.

Zone	Etc/GMT-14	14	-	GMT-14	# 14 hours ahead of GMT
Zone	Etc/GMT-13	13	-	GMT-13
Zone	Etc/GMT-12	12	-	GMT-12
Zone	Etc/GMT-11	11	-	GMT-11
Zone	Etc/GMT-10	10	-	GMT-10
Zone	Etc/GMT-9	9	-	GMT-9
Zone	Etc/GMT-8	8	-	GMT-8
Zone	Etc/GMT-7	7	-	GMT-7
Zone	Etc/GMT-6	6	-	GMT-6
Zone	Etc/GMT-5	5	-	GMT-5
Zone	Etc/GMT-4	4	-	GMT-4
Zone	Etc/GMT-3	3	-	GMT-3
Zone	Etc/GMT-2	2	-	GMT-2
Zone	Etc/GMT-1	1	-	GMT-1
Zone	Etc/GMT+1	-1	-	GMT+1
Zone	Etc/GMT+2	-2	-	GMT+2
Zone	Etc/GMT+3	-3	-	GMT+3
Zone	Etc/GMT+4	-4	-	GMT+4
Zone	Etc/GMT+5	-5	-	GMT+5
Zone	Etc/GMT+6	-6	-	GMT+6
Zone	Etc/GMT+7	-7	-	GMT+7
Zone	Etc/GMT+8	-8	-	GMT+8
Zone	Etc/GMT+9	-9	-	GMT+9
Zone	Etc/GMT+10	-10	-	GMT+10
Zone	Etc/GMT+11	-11	-	GMT+11
Zone	Etc/GMT+12	-12	-	GMT+12
joda-time-2.3/src/main/java/org/joda/time/tz/src/Readme.txt0000644000175000017500000000020412200501234023020 0ustar  ebourgebourgThe data files in this directory were obtained from the public tz database,
http://www.twinsun.com/tz/tz-link.htm, version 2013d.
joda-time-2.3/src/main/java/org/joda/time/tz/src/europe0000644000175000017500000037425012200501234022323 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# This data is by no means authoritative; if you think you know better,
# go ahead and edit the file (and please send any changes to
# tz@iana.org for general use in the future).

# From Paul Eggert (2006-03-22):
# A good source for time zone historical data outside the U.S. is
# Thomas G. Shanks and Rique Pottenger, The International Atlas (6th edition),
# San Diego: ACS Publications, Inc. (2003).
#
# Gwillim Law writes that a good source
# for recent time zone data is the International Air Transport
# Association's Standard Schedules Information Manual (IATA SSIM),
# published semiannually.  Law sent in several helpful summaries
# of the IATA's data after 1990.
#
# Except where otherwise noted, Shanks & Pottenger is the source for
# entries through 1991, and IATA SSIM is the source for entries afterwards.
#
# Other sources occasionally used include:
#
#	Edward W. Whitman, World Time Differences,
#	Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated),
#	which I found in the UCLA library.
#
#	
#	William Willett, The Waste of Daylight, 19th edition
#	 (1914-03)
#
#	Milne J. Civil time. Geogr J. 1899 Feb;13(2):173-94
#	.  He writes:
#	"It is requested that corrections and additions to these tables
#	may be sent to Mr. John Milne, Royal Geographical Society,
#	Savile Row, London."  Nowadays please email them to tz@iana.org.
#
#	Brazil's Departamento Servico da Hora (DSH),
#	
#	History of Summer Time
#	 (1998-09-21, in Portuguese)

#
# I invented the abbreviations marked `*' in the following table;
# the rest are from earlier versions of this file, or from other sources.
# Corrections are welcome!
#                   std dst  2dst
#                   LMT           Local Mean Time
#       -4:00       AST ADT       Atlantic
#       -3:00       WGT WGST      Western Greenland*
#       -1:00       EGT EGST      Eastern Greenland*
#        0:00       GMT BST  BDST Greenwich, British Summer
#        0:00       GMT IST       Greenwich, Irish Summer
#        0:00       WET WEST WEMT Western Europe
#        0:19:32.13 AMT NST       Amsterdam, Netherlands Summer (1835-1937)*
#        0:20       NET NEST      Netherlands (1937-1940)*
#        1:00       CET CEST CEMT Central Europe
#        1:00:14    SET           Swedish (1879-1899)*
#        2:00       EET EEST      Eastern Europe
#        3:00       MSK MSD       Moscow
#
# A reliable and entertaining source about time zones, especially in Britain,
# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997).

# From Peter Ilieve (1994-12-04),
# The original six [EU members]: Belgium, France, (West) Germany, Italy,
# Luxembourg, the Netherlands.
# Plus, from 1 Jan 73: Denmark, Ireland, United Kingdom.
# Plus, from 1 Jan 81: Greece.
# Plus, from 1 Jan 86: Spain, Portugal.
# Plus, from 1 Jan 95: Austria, Finland, Sweden. (Norway negotiated terms for
# entry but in a referendum on 28 Nov 94 the people voted No by 52.2% to 47.8%
# on a turnout of 88.6%. This was almost the same result as Norway's previous
# referendum in 1972, they are the only country to have said No twice.
# Referendums in the other three countries voted Yes.)
# ...
# Estonia ... uses EU dates but not at 01:00 GMT, they use midnight GMT.
# I don't think they know yet what they will do from 1996 onwards.
# ...
# There shouldn't be any [current members who are not using EU rules].
# A Directive has the force of law, member states are obliged to enact
# national law to implement it. The only contentious issue was the
# different end date for the UK and Ireland, and this was always allowed
# in the Directive.


###############################################################################

# Britain (United Kingdom) and Ireland (Eire)

# From Peter Ilieve (1994-07-06):
#
# On 17 Jan 1994 the Independent, a UK quality newspaper, had a piece about
# historical vistas along the Thames in west London. There was a photo
# and a sketch map showing some of the sightlines involved. One paragraph
# of the text said:
#
# `An old stone obelisk marking a forgotten terrestrial meridian stands
# beside the river at Kew. In the 18th century, before time and longitude
# was standardised by the Royal Observatory in Greenwich, scholars observed
# this stone and the movement of stars from Kew Observatory nearby. They
# made their calculations and set the time for the Horse Guards and Parliament,
# but now the stone is obscured by scrubwood and can only be seen by walking
# along the towpath within a few yards of it.'
#
# I have a one inch to one mile map of London and my estimate of the stone's
# position is 51 deg. 28' 30" N, 0 deg. 18' 45" W. The longitude should
# be within about +-2". The Ordnance Survey grid reference is TQ172761.
#
# [This yields GMTOFF = -0:01:15 for London LMT in the 18th century.]

# From Paul Eggert (1993-11-18):
#
# Howse writes that Britain was the first country to use standard time.
# The railways cared most about the inconsistencies of local mean time,
# and it was they who forced a uniform time on the country.
# The original idea was credited to Dr. William Hyde Wollaston (1766-1828)
# and was popularized by Abraham Follett Osler (1808-1903).
# The first railway to adopt London time was the Great Western Railway
# in November 1840; other railways followed suit, and by 1847 most
# (though not all) railways used London time.  On 1847-09-22 the
# Railway Clearing House, an industry standards body, recommended that GMT be
# adopted at all stations as soon as the General Post Office permitted it.
# The transition occurred on 12-01 for the L&NW, the Caledonian,
# and presumably other railways; the January 1848 Bradshaw's lists many
# railways as using GMT.  By 1855 the vast majority of public
# clocks in Britain were set to GMT (though some, like the great clock
# on Tom Tower at Christ Church, Oxford, were fitted with two minute hands,
# one for local time and one for GMT).  The last major holdout was the legal
# system, which stubbornly stuck to local time for many years, leading
# to oddities like polls opening at 08:13 and closing at 16:13.
# The legal system finally switched to GMT when the Statutes (Definition
# of Time) Act took effect; it received the Royal Assent on 1880-08-02.
#
# In the tables below, we condense this complicated story into a single
# transition date for London, namely 1847-12-01.  We don't know as much
# about Dublin, so we use 1880-08-02, the legal transition time.

# From Paul Eggert (2003-09-27):
# Summer Time was first seriously proposed by William Willett (1857-1915),
# a London builder and member of the Royal Astronomical Society
# who circulated a pamphlet ``The Waste of Daylight'' (1907)
# that proposed advancing clocks 20 minutes on each of four Sundays in April,
# and retarding them by the same amount on four Sundays in September.
# A bill was drafted in 1909 and introduced in Parliament several times,
# but it met with ridicule and opposition, especially from farming interests.
# Later editions of the pamphlet proposed one-hour summer time, and
# it was eventually adopted as a wartime measure in 1916.
# See: Summer Time Arrives Early, The Times (2000-05-18).
# A monument to Willett was unveiled on 1927-05-21, in an open space in
# a 45-acre wood near Chislehurst, Kent that was purchased by popular
# subscription and open to the public.  On the south face of the monolith,
# designed by G. W. Miller, is the...William Willett Memorial Sundial,
# which is permanently set to Summer Time.

# From Winston Churchill (1934-04-28):
# It is one of the paradoxes of history that we should owe the boon of
# summer time, which gives every year to the people of this country
# between 160 and 170 hours more daylight leisure, to a war which
# plunged Europe into darkness for four years, and shook the
# foundations of civilization throughout the world.
#	-- 
#	"A Silent Toast to William Willett", Pictorial Weekly
#	

# From Paul Eggert (1996-09-03):
# The OED Supplement says that the English originally said ``Daylight Saving''
# when they were debating the adoption of DST in 1908; but by 1916 this
# term appears only in quotes taken from DST's opponents, whereas the
# proponents (who eventually won the argument) are quoted as using ``Summer''.

# From Arthur David Olson (1989-01-19):
#
# A source at the British Information Office in New York avers that it's
# known as "British" Summer Time in all parts of the United Kingdom.

# Date: 4 Jan 89 08:57:25 GMT (Wed)
# From: Jonathan Leffler
# [British Summer Time] is fixed annually by Act of Parliament.
# If you can predict what Parliament will do, you should be in
# politics making a fortune, not computing.

# From Chris Carrier (1996-06-14):
# I remember reading in various wartime issues of the London Times the
# acronym BDST for British Double Summer Time.  Look for the published
# time of sunrise and sunset in The Times, when BDST was in effect, and
# if you find a zone reference it will say, "All times B.D.S.T."

# From Joseph S. Myers (1999-09-02):
# ... some military cables (WO 219/4100 - this is a copy from the
# main SHAEF archives held in the US National Archives, SHAEF/5252/8/516)
# agree that the usage is BDST (this appears in a message dated 17 Feb 1945).

# From Joseph S. Myers (2000-10-03):
# On 18th April 1941, Sir Stephen Tallents of the BBC wrote to Sir
# Alexander Maxwell of the Home Office asking whether there was any
# official designation; the reply of the 21st was that there wasn't
# but he couldn't think of anything better than the "Double British
# Summer Time" that the BBC had been using informally.
# http://student.cusu.cam.ac.uk/~jsm28/british-time/bbc-19410418.png
# http://student.cusu.cam.ac.uk/~jsm28/british-time/ho-19410421.png

# From Sir Alexander Maxwell in the above-mentioned letter (1941-04-21):
# [N]o official designation has as far as I know been adopted for the time
# which is to be introduced in May....
# I cannot think of anything better than "Double British Summer Time"
# which could not be said to run counter to any official description.

# From Paul Eggert (2000-10-02):
# Howse writes (p 157) `DBST' too, but `BDST' seems to have been common
# and follows the more usual convention of putting the location name first,
# so we use `BDST'.

# Peter Ilieve (1998-04-19) described at length
# the history of summer time legislation in the United Kingdom.
# Since 1998 Joseph S. Myers has been updating
# and extending this list, which can be found in
# http://student.cusu.cam.ac.uk/~jsm28/british-time/
# 
# History of legal time in Britain
# 
# Rob Crowther (2012-01-04) reports that that URL no longer
# exists, and the article can now be found at:
# 
# http://www.polyomino.org.uk/british-time/
# 

# From Joseph S. Myers (1998-01-06):
#
# The legal time in the UK outside of summer time is definitely GMT, not UTC;
# see Lord Tanlaw's speech
# 
# (Lords Hansard 11 June 1997 columns 964 to 976)
# .

# From Paul Eggert (2006-03-22):
#
# For lack of other data, follow Shanks & Pottenger for Eire in 1940-1948.
#
# Given Ilieve and Myers's data, the following claims by Shanks & Pottenger
# are incorrect:
#     * Wales did not switch from GMT to daylight saving time until
#	1921 Apr 3, when they began to conform with the rest of Great Britain.
# Actually, Wales was identical after 1880.
#     * Eire had two transitions on 1916 Oct 1.
# It actually just had one transition.
#     * Northern Ireland used single daylight saving time throughout WW II.
# Actually, it conformed to Britain.
#     * GB-Eire changed standard time to 1 hour ahead of GMT on 1968-02-18.
# Actually, that date saw the usual switch to summer time.
# Standard time was not changed until 1968-10-27 (the clocks didn't change).
#
# Here is another incorrect claim by Shanks & Pottenger:
#     * Jersey, Guernsey, and the Isle of Man did not switch from GMT
#	to daylight saving time until 1921 Apr 3, when they began to
#	conform with Great Britain.
# S.R.&O. 1916, No. 382 and HO 45/10811/312364 (quoted above) say otherwise.
#
# The following claim by Shanks & Pottenger is possible though doubtful;
# we'll ignore it for now.
#     * Dublin's 1971-10-31 switch was at 02:00, even though London's was 03:00.
#
#
# Whitman says Dublin Mean Time was -0:25:21, which is more precise than
# Shanks & Pottenger.
# Perhaps this was Dunsink Observatory Time, as Dunsink Observatory
# (8 km NW of Dublin's center) seemingly was to Dublin as Greenwich was
# to London.  For example:
#
#   "Timeball on the ballast office is down.  Dunsink time."
#   -- James Joyce, Ulysses

# From Joseph S. Myers (2005-01-26):
# Irish laws are available online at www.irishstatutebook.ie.  These include
# various relating to legal time, for example:
#
# ZZA13Y1923.html ZZA12Y1924.html ZZA8Y1925.html ZZSIV20PG1267.html
#
# ZZSI71Y1947.html ZZSI128Y1948.html ZZSI23Y1949.html ZZSI41Y1950.html
# ZZSI27Y1951.html ZZSI73Y1952.html
#
# ZZSI11Y1961.html ZZSI232Y1961.html ZZSI182Y1962.html
# ZZSI167Y1963.html ZZSI257Y1964.html ZZSI198Y1967.html
# ZZA23Y1968.html ZZA17Y1971.html
#
# ZZSI67Y1981.html ZZSI212Y1982.html ZZSI45Y1986.html
# ZZSI264Y1988.html ZZSI52Y1990.html ZZSI371Y1992.html
# ZZSI395Y1994.html ZZSI484Y1997.html ZZSI506Y2001.html
#
# [These are all relative to the root, e.g., the first is
# .]
#
# (These are those I found, but there could be more.  In any case these
# should allow various updates to the comments in the europe file to cover
# the laws applicable in Ireland.)
#
# (Note that the time in the Republic of Ireland since 1968 has been defined
# in terms of standard time being GMT+1 with a period of winter time when it
# is GMT, rather than standard time being GMT with a period of summer time
# being GMT+1.)

# From Paul Eggert (1999-03-28):
# Clive Feather (, 1997-03-31)
# reports that Folkestone (Cheriton) Shuttle Terminal uses Concession Time
# (CT), equivalent to French civil time.
# Julian Hill (, 1998-09-30) reports that
# trains between Dollands Moor (the freight facility next door)
# and Frethun run in CT.
# My admittedly uninformed guess is that the terminal has two authorities,
# the French concession operators and the British civil authorities,
# and that the time depends on who you're talking to.
# If, say, the British police were called to the station for some reason,
# I would expect the official police report to use GMT/BST and not CET/CEST.
# This is a borderline case, but for now let's stick to GMT/BST.

# From an anonymous contributor (1996-06-02):
# The law governing time in Ireland is under Statutory Instrument SI 395/94,
# which gives force to European Union 7th Council Directive # 94/21/EC.
# Under this directive, the Minister for Justice in Ireland makes appropriate
# regulations. I spoke this morning with the Secretary of the Department of
# Justice (tel +353 1 678 9711) who confirmed to me that the correct name is
# "Irish Summer Time", abbreviated to "IST".

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# Summer Time Act, 1916
Rule	GB-Eire	1916	only	-	May	21	2:00s	1:00	BST
Rule	GB-Eire	1916	only	-	Oct	 1	2:00s	0	GMT
# S.R.&O. 1917, No. 358
Rule	GB-Eire	1917	only	-	Apr	 8	2:00s	1:00	BST
Rule	GB-Eire	1917	only	-	Sep	17	2:00s	0	GMT
# S.R.&O. 1918, No. 274
Rule	GB-Eire	1918	only	-	Mar	24	2:00s	1:00	BST
Rule	GB-Eire	1918	only	-	Sep	30	2:00s	0	GMT
# S.R.&O. 1919, No. 297
Rule	GB-Eire	1919	only	-	Mar	30	2:00s	1:00	BST
Rule	GB-Eire	1919	only	-	Sep	29	2:00s	0	GMT
# S.R.&O. 1920, No. 458
Rule	GB-Eire	1920	only	-	Mar	28	2:00s	1:00	BST
# S.R.&O. 1920, No. 1844
Rule	GB-Eire	1920	only	-	Oct	25	2:00s	0	GMT
# S.R.&O. 1921, No. 363
Rule	GB-Eire	1921	only	-	Apr	 3	2:00s	1:00	BST
Rule	GB-Eire	1921	only	-	Oct	 3	2:00s	0	GMT
# S.R.&O. 1922, No. 264
Rule	GB-Eire	1922	only	-	Mar	26	2:00s	1:00	BST
Rule	GB-Eire	1922	only	-	Oct	 8	2:00s	0	GMT
# The Summer Time Act, 1922
Rule	GB-Eire	1923	only	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1923	1924	-	Sep	Sun>=16	2:00s	0	GMT
Rule	GB-Eire	1924	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1925	1926	-	Apr	Sun>=16	2:00s	1:00	BST
# The Summer Time Act, 1925
Rule	GB-Eire	1925	1938	-	Oct	Sun>=2	2:00s	0	GMT
Rule	GB-Eire	1927	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1928	1929	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1930	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1931	1932	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1933	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1934	only	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1935	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1936	1937	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1938	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1939	only	-	Apr	Sun>=16	2:00s	1:00	BST
# S.R.&O. 1939, No. 1379
Rule	GB-Eire	1939	only	-	Nov	Sun>=16	2:00s	0	GMT
# S.R.&O. 1940, No. 172 and No. 1883
Rule	GB-Eire	1940	only	-	Feb	Sun>=23	2:00s	1:00	BST
# S.R.&O. 1941, No. 476
Rule	GB-Eire	1941	only	-	May	Sun>=2	1:00s	2:00	BDST
Rule	GB-Eire	1941	1943	-	Aug	Sun>=9	1:00s	1:00	BST
# S.R.&O. 1942, No. 506
Rule	GB-Eire	1942	1944	-	Apr	Sun>=2	1:00s	2:00	BDST
# S.R.&O. 1944, No. 932
Rule	GB-Eire	1944	only	-	Sep	Sun>=16	1:00s	1:00	BST
# S.R.&O. 1945, No. 312
Rule	GB-Eire	1945	only	-	Apr	Mon>=2	1:00s	2:00	BDST
Rule	GB-Eire	1945	only	-	Jul	Sun>=9	1:00s	1:00	BST
# S.R.&O. 1945, No. 1208
Rule	GB-Eire	1945	1946	-	Oct	Sun>=2	2:00s	0	GMT
Rule	GB-Eire	1946	only	-	Apr	Sun>=9	2:00s	1:00	BST
# The Summer Time Act, 1947
Rule	GB-Eire	1947	only	-	Mar	16	2:00s	1:00	BST
Rule	GB-Eire	1947	only	-	Apr	13	1:00s	2:00	BDST
Rule	GB-Eire	1947	only	-	Aug	10	1:00s	1:00	BST
Rule	GB-Eire	1947	only	-	Nov	 2	2:00s	0	GMT
# Summer Time Order, 1948 (S.I. 1948/495)
Rule	GB-Eire	1948	only	-	Mar	14	2:00s	1:00	BST
Rule	GB-Eire	1948	only	-	Oct	31	2:00s	0	GMT
# Summer Time Order, 1949 (S.I. 1949/373)
Rule	GB-Eire	1949	only	-	Apr	 3	2:00s	1:00	BST
Rule	GB-Eire	1949	only	-	Oct	30	2:00s	0	GMT
# Summer Time Order, 1950 (S.I. 1950/518)
# Summer Time Order, 1951 (S.I. 1951/430)
# Summer Time Order, 1952 (S.I. 1952/451)
Rule	GB-Eire	1950	1952	-	Apr	Sun>=14	2:00s	1:00	BST
Rule	GB-Eire	1950	1952	-	Oct	Sun>=21	2:00s	0	GMT
# revert to the rules of the Summer Time Act, 1925
Rule	GB-Eire	1953	only	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1953	1960	-	Oct	Sun>=2	2:00s	0	GMT
Rule	GB-Eire	1954	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1955	1956	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1957	only	-	Apr	Sun>=9	2:00s	1:00	BST
Rule	GB-Eire	1958	1959	-	Apr	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1960	only	-	Apr	Sun>=9	2:00s	1:00	BST
# Summer Time Order, 1961 (S.I. 1961/71)
# Summer Time (1962) Order, 1961 (S.I. 1961/2465)
# Summer Time Order, 1963 (S.I. 1963/81)
Rule	GB-Eire	1961	1963	-	Mar	lastSun	2:00s	1:00	BST
Rule	GB-Eire	1961	1968	-	Oct	Sun>=23	2:00s	0	GMT
# Summer Time (1964) Order, 1963 (S.I. 1963/2101)
# Summer Time Order, 1964 (S.I. 1964/1201)
# Summer Time Order, 1967 (S.I. 1967/1148)
Rule	GB-Eire	1964	1967	-	Mar	Sun>=19	2:00s	1:00	BST
# Summer Time Order, 1968 (S.I. 1968/117)
Rule	GB-Eire	1968	only	-	Feb	18	2:00s	1:00	BST
# The British Standard Time Act, 1968
#	(no summer time)
# The Summer Time Act, 1972
Rule	GB-Eire	1972	1980	-	Mar	Sun>=16	2:00s	1:00	BST
Rule	GB-Eire	1972	1980	-	Oct	Sun>=23	2:00s	0	GMT
# Summer Time Order, 1980 (S.I. 1980/1089)
# Summer Time Order, 1982 (S.I. 1982/1673)
# Summer Time Order, 1986 (S.I. 1986/223)
# Summer Time Order, 1988 (S.I. 1988/931)
Rule	GB-Eire	1981	1995	-	Mar	lastSun	1:00u	1:00	BST
Rule	GB-Eire 1981	1989	-	Oct	Sun>=23	1:00u	0	GMT
# Summer Time Order, 1989 (S.I. 1989/985)
# Summer Time Order, 1992 (S.I. 1992/1729)
# Summer Time Order 1994 (S.I. 1994/2798)
Rule	GB-Eire 1990	1995	-	Oct	Sun>=22	1:00u	0	GMT
# Summer Time Order 1997 (S.I. 1997/2982)
# See EU for rules starting in 1996.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/London	-0:01:15 -	LMT	1847 Dec  1 0:00s
			 0:00	GB-Eire	%s	1968 Oct 27
			 1:00	-	BST	1971 Oct 31 2:00u
			 0:00	GB-Eire	%s	1996
			 0:00	EU	GMT/BST
Link	Europe/London	Europe/Jersey
Link	Europe/London	Europe/Guernsey
Link	Europe/London	Europe/Isle_of_Man
Zone	Europe/Dublin	-0:25:00 -	LMT	1880 Aug  2
			-0:25:21 -	DMT	1916 May 21 2:00
			-0:25:21 1:00	IST	1916 Oct  1 2:00s
			 0:00	GB-Eire	%s	1921 Dec  6 # independence
			 0:00	GB-Eire	GMT/IST	1940 Feb 25 2:00
			 0:00	1:00	IST	1946 Oct  6 2:00
			 0:00	-	GMT	1947 Mar 16 2:00
			 0:00	1:00	IST	1947 Nov  2 2:00
			 0:00	-	GMT	1948 Apr 18 2:00
			 0:00	GB-Eire	GMT/IST	1968 Oct 27
			 1:00	-	IST	1971 Oct 31 2:00u
			 0:00	GB-Eire	GMT/IST	1996
			 0:00	EU	GMT/IST

###############################################################################

# Europe

# EU rules are for the European Union, previously known as the EC, EEC,
# Common Market, etc.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	EU	1977	1980	-	Apr	Sun>=1	 1:00u	1:00	S
Rule	EU	1977	only	-	Sep	lastSun	 1:00u	0	-
Rule	EU	1978	only	-	Oct	 1	 1:00u	0	-
Rule	EU	1979	1995	-	Sep	lastSun	 1:00u	0	-
Rule	EU	1981	max	-	Mar	lastSun	 1:00u	1:00	S
Rule	EU	1996	max	-	Oct	lastSun	 1:00u	0	-
# The most recent directive covers the years starting in 2002.  See:
# 
# Directive 2000/84/EC of the European Parliament and of the Council
# of 19 January 2001 on summer-time arrangements.
# 

# W-Eur differs from EU only in that W-Eur uses standard time.
Rule	W-Eur	1977	1980	-	Apr	Sun>=1	 1:00s	1:00	S
Rule	W-Eur	1977	only	-	Sep	lastSun	 1:00s	0	-
Rule	W-Eur	1978	only	-	Oct	 1	 1:00s	0	-
Rule	W-Eur	1979	1995	-	Sep	lastSun	 1:00s	0	-
Rule	W-Eur	1981	max	-	Mar	lastSun	 1:00s	1:00	S
Rule	W-Eur	1996	max	-	Oct	lastSun	 1:00s	0	-

# Older C-Eur rules are for convenience in the tables.
# From 1977 on, C-Eur differs from EU only in that C-Eur uses standard time.
Rule	C-Eur	1916	only	-	Apr	30	23:00	1:00	S
Rule	C-Eur	1916	only	-	Oct	 1	 1:00	0	-
Rule	C-Eur	1917	1918	-	Apr	Mon>=15	 2:00s	1:00	S
Rule	C-Eur	1917	1918	-	Sep	Mon>=15	 2:00s	0	-
Rule	C-Eur	1940	only	-	Apr	 1	 2:00s	1:00	S
Rule	C-Eur	1942	only	-	Nov	 2	 2:00s	0	-
Rule	C-Eur	1943	only	-	Mar	29	 2:00s	1:00	S
Rule	C-Eur	1943	only	-	Oct	 4	 2:00s	0	-
Rule	C-Eur	1944	1945	-	Apr	Mon>=1	 2:00s	1:00	S
# Whitman gives 1944 Oct 7; go with Shanks & Pottenger.
Rule	C-Eur	1944	only	-	Oct	 2	 2:00s	0	-
# From Jesper Norgaard Welen (2008-07-13):
#
# I found what is probably a typo of 2:00 which should perhaps be 2:00s
# in the C-Eur rule from tz database version 2008d (this part was
# corrected in version 2008d). The circumstancial evidence is simply the
# tz database itself, as seen below:
#
# Zone Europe/Paris 0:09:21 - LMT 1891 Mar 15  0:01
#    0:00 France WE%sT 1945 Sep 16  3:00
#
# Zone Europe/Monaco 0:29:32 - LMT 1891 Mar 15
#    0:00 France WE%sT 1945 Sep 16 3:00
#
# Zone Europe/Belgrade 1:22:00 - LMT 1884
#    1:00 1:00 CEST 1945 Sep 16  2:00s
#
# Rule France 1945 only - Sep 16  3:00 0 -
# Rule Belgium 1945 only - Sep 16  2:00s 0 -
# Rule Neth 1945 only - Sep 16 2:00s 0 -
#
# The rule line to be changed is:
#
# Rule C-Eur 1945 only - Sep 16  2:00 0 -
#
# It seems that Paris, Monaco, Rule France, Rule Belgium all agree on
# 2:00 standard time, e.g. 3:00 local time.  However there are no
# countries that use C-Eur rules in September 1945, so the only items
# affected are apparently these fictitious zones that translate acronyms
# CET and MET:
#
# Zone CET  1:00 C-Eur CE%sT
# Zone MET  1:00 C-Eur ME%sT
#
# It this is right then the corrected version would look like:
#
# Rule C-Eur 1945 only - Sep 16  2:00s 0 -
#
# A small step for mankind though 8-)
Rule	C-Eur	1945	only	-	Sep	16	 2:00s	0	-
Rule	C-Eur	1977	1980	-	Apr	Sun>=1	 2:00s	1:00	S
Rule	C-Eur	1977	only	-	Sep	lastSun	 2:00s	0	-
Rule	C-Eur	1978	only	-	Oct	 1	 2:00s	0	-
Rule	C-Eur	1979	1995	-	Sep	lastSun	 2:00s	0	-
Rule	C-Eur	1981	max	-	Mar	lastSun	 2:00s	1:00	S
Rule	C-Eur	1996	max	-	Oct	lastSun	 2:00s	0	-

# E-Eur differs from EU only in that E-Eur switches at midnight local time.
Rule	E-Eur	1977	1980	-	Apr	Sun>=1	 0:00	1:00	S
Rule	E-Eur	1977	only	-	Sep	lastSun	 0:00	0	-
Rule	E-Eur	1978	only	-	Oct	 1	 0:00	0	-
Rule	E-Eur	1979	1995	-	Sep	lastSun	 0:00	0	-
Rule	E-Eur	1981	max	-	Mar	lastSun	 0:00	1:00	S
Rule	E-Eur	1996	max	-	Oct	lastSun	 0:00	0	-

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Russia	1917	only	-	Jul	 1	23:00	1:00	MST	# Moscow Summer Time
Rule	Russia	1917	only	-	Dec	28	 0:00	0	MMT	# Moscow Mean Time
Rule	Russia	1918	only	-	May	31	22:00	2:00	MDST	# Moscow Double Summer Time
Rule	Russia	1918	only	-	Sep	16	 1:00	1:00	MST
Rule	Russia	1919	only	-	May	31	23:00	2:00	MDST
Rule	Russia	1919	only	-	Jul	 1	 2:00	1:00	S
Rule	Russia	1919	only	-	Aug	16	 0:00	0	-
Rule	Russia	1921	only	-	Feb	14	23:00	1:00	S
Rule	Russia	1921	only	-	Mar	20	23:00	2:00	M # Midsummer
Rule	Russia	1921	only	-	Sep	 1	 0:00	1:00	S
Rule	Russia	1921	only	-	Oct	 1	 0:00	0	-
# Act No.925 of the Council of Ministers of the USSR (1980-10-24):
Rule	Russia	1981	1984	-	Apr	 1	 0:00	1:00	S
Rule	Russia	1981	1983	-	Oct	 1	 0:00	0	-
# Act No.967 of the Council of Ministers of the USSR (1984-09-13), repeated in
# Act No.227 of the Council of Ministers of the USSR (1989-03-14):
Rule	Russia	1984	1991	-	Sep	lastSun	 2:00s	0	-
Rule	Russia	1985	1991	-	Mar	lastSun	 2:00s	1:00	S
#
Rule	Russia	1992	only	-	Mar	lastSat	 23:00	1:00	S
Rule	Russia	1992	only	-	Sep	lastSat	 23:00	0	-
Rule	Russia	1993	2010	-	Mar	lastSun	 2:00s	1:00	S
Rule	Russia	1993	1995	-	Sep	lastSun	 2:00s	0	-
Rule	Russia	1996	2010	-	Oct	lastSun	 2:00s	0	-

# From Alexander Krivenyshev (2011-06-14):
# According to Kremlin press service, Russian President Dmitry Medvedev
# signed a federal law "On calculation of time" on June 9, 2011.
# According to the law Russia is abolishing daylight saving time.
#
# Medvedev signed a law "On the Calculation of Time" (in russian):
# 
# http://bmockbe.ru/events/?ID=7583
# 
#
# Medvedev signed a law on the calculation of the time (in russian):
# 
# http://www.regnum.ru/news/polit/1413906.html
# 

# From Arthur David Olson (2011-06-15):
# Take "abolishing daylight saving time" to mean that time is now considered
# to be standard.

# These are for backward compatibility with older versions.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	WET		0:00	EU	WE%sT
Zone	CET		1:00	C-Eur	CE%sT
Zone	MET		1:00	C-Eur	ME%sT
Zone	EET		2:00	EU	EE%sT

# Previous editions of this database used abbreviations like MET DST
# for Central European Summer Time, but this didn't agree with common usage.

# From Markus Kuhn (1996-07-12):
# The official German names ... are
#
#	Mitteleuropaeische Zeit (MEZ)         = UTC+01:00
#	Mitteleuropaeische Sommerzeit (MESZ)  = UTC+02:00
#
# as defined in the German Time Act (Gesetz ueber die Zeitbestimmung (ZeitG),
# 1978-07-25, Bundesgesetzblatt, Jahrgang 1978, Teil I, S. 1110-1111)....
# I wrote ... to the German Federal Physical-Technical Institution
#
#	Physikalisch-Technische Bundesanstalt (PTB)
#	Laboratorium 4.41 "Zeiteinheit"
#	Postfach 3345
#	D-38023 Braunschweig
#	phone: +49 531 592-0
#
# ... I received today an answer letter from Dr. Peter Hetzel, head of the PTB
# department for time and frequency transmission.  He explained that the
# PTB translates MEZ and MESZ into English as
#
#	Central European Time (CET)         = UTC+01:00
#	Central European Summer Time (CEST) = UTC+02:00


# Albania
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Albania	1940	only	-	Jun	16	0:00	1:00	S
Rule	Albania	1942	only	-	Nov	 2	3:00	0	-
Rule	Albania	1943	only	-	Mar	29	2:00	1:00	S
Rule	Albania	1943	only	-	Apr	10	3:00	0	-
Rule	Albania	1974	only	-	May	 4	0:00	1:00	S
Rule	Albania	1974	only	-	Oct	 2	0:00	0	-
Rule	Albania	1975	only	-	May	 1	0:00	1:00	S
Rule	Albania	1975	only	-	Oct	 2	0:00	0	-
Rule	Albania	1976	only	-	May	 2	0:00	1:00	S
Rule	Albania	1976	only	-	Oct	 3	0:00	0	-
Rule	Albania	1977	only	-	May	 8	0:00	1:00	S
Rule	Albania	1977	only	-	Oct	 2	0:00	0	-
Rule	Albania	1978	only	-	May	 6	0:00	1:00	S
Rule	Albania	1978	only	-	Oct	 1	0:00	0	-
Rule	Albania	1979	only	-	May	 5	0:00	1:00	S
Rule	Albania	1979	only	-	Sep	30	0:00	0	-
Rule	Albania	1980	only	-	May	 3	0:00	1:00	S
Rule	Albania	1980	only	-	Oct	 4	0:00	0	-
Rule	Albania	1981	only	-	Apr	26	0:00	1:00	S
Rule	Albania	1981	only	-	Sep	27	0:00	0	-
Rule	Albania	1982	only	-	May	 2	0:00	1:00	S
Rule	Albania	1982	only	-	Oct	 3	0:00	0	-
Rule	Albania	1983	only	-	Apr	18	0:00	1:00	S
Rule	Albania	1983	only	-	Oct	 1	0:00	0	-
Rule	Albania	1984	only	-	Apr	 1	0:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Tirane	1:19:20 -	LMT	1914
			1:00	-	CET	1940 Jun 16
			1:00	Albania	CE%sT	1984 Jul
			1:00	EU	CE%sT

# Andorra
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Andorra	0:06:04 -	LMT	1901
			0:00	-	WET	1946 Sep 30
			1:00	-	CET	1985 Mar 31 2:00
			1:00	EU	CE%sT

# Austria

# Milne says Vienna time was 1:05:21.

# From Paul Eggert (2006-03-22): Shanks & Pottenger give 1918-06-16 and
# 1945-11-18, but the Austrian Federal Office of Metrology and
# Surveying (BEV) gives 1918-09-16 and for Vienna gives the "alleged"
# date of 1945-04-12 with no time.  For the 1980-04-06 transition
# Shanks & Pottenger give 02:00, the BEV 00:00.  Go with the BEV,
# and guess 02:00 for 1945-04-12.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Austria	1920	only	-	Apr	 5	2:00s	1:00	S
Rule	Austria	1920	only	-	Sep	13	2:00s	0	-
Rule	Austria	1946	only	-	Apr	14	2:00s	1:00	S
Rule	Austria	1946	1948	-	Oct	Sun>=1	2:00s	0	-
Rule	Austria	1947	only	-	Apr	 6	2:00s	1:00	S
Rule	Austria	1948	only	-	Apr	18	2:00s	1:00	S
Rule	Austria	1980	only	-	Apr	 6	0:00	1:00	S
Rule	Austria	1980	only	-	Sep	28	0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Vienna	1:05:21 -	LMT	1893 Apr
			1:00	C-Eur	CE%sT	1920
			1:00	Austria	CE%sT	1940 Apr  1 2:00s
			1:00	C-Eur	CE%sT	1945 Apr  2 2:00s
			1:00	1:00	CEST	1945 Apr 12 2:00s
			1:00	-	CET	1946
			1:00	Austria	CE%sT	1981
			1:00	EU	CE%sT

# Belarus
# From Yauhen Kharuzhy (2011-09-16):
# By latest Belarus government act Europe/Minsk timezone was changed to
# GMT+3 without DST (was GMT+2 with DST).
#
# Sources (Russian language):
# 1.
# 
# http://www.belta.by/ru/all_news/society/V-Belarusi-otmenjaetsja-perexod-na-sezonnoe-vremja_i_572952.html
# 
# 2.
# 
# http://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/
# 
# 3.
# 
# http://news.tut.by/society/250578.html
# 
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Minsk	1:50:16 -	LMT	1880
			1:50	-	MMT	1924 May 2 # Minsk Mean Time
			2:00	-	EET	1930 Jun 21
			3:00	-	MSK	1941 Jun 28
			1:00	C-Eur	CE%sT	1944 Jul  3
			3:00	Russia	MSK/MSD	1990
			3:00	-	MSK	1991 Mar 31 2:00s
			2:00	1:00	EEST	1991 Sep 29 2:00s
			2:00	-	EET	1992 Mar 29 0:00s
			2:00	1:00	EEST	1992 Sep 27 0:00s
			2:00	Russia	EE%sT	2011 Mar 27 2:00s
			3:00	-	FET # Further-eastern European Time

# Belgium
#
# From Paul Eggert (1997-07-02):
# Entries from 1918 through 1991 are taken from:
#	Annuaire de L'Observatoire Royal de Belgique,
#	Avenue Circulaire, 3, B-1180 BRUXELLES, CLVIIe annee, 1991
#	(Imprimerie HAYEZ, s.p.r.l., Rue Fin, 4, 1080 BRUXELLES, MCMXC),
#	pp 8-9.
# LMT before 1892 was 0:17:30, according to the official journal of Belgium:
#	Moniteur Belge, Samedi 30 Avril 1892, N.121.
# Thanks to Pascal Delmoitie for these references.
# The 1918 rules are listed for completeness; they apply to unoccupied Belgium.
# Assume Brussels switched to WET in 1918 when the armistice took effect.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Belgium	1918	only	-	Mar	 9	 0:00s	1:00	S
Rule	Belgium	1918	1919	-	Oct	Sat>=1	23:00s	0	-
Rule	Belgium	1919	only	-	Mar	 1	23:00s	1:00	S
Rule	Belgium	1920	only	-	Feb	14	23:00s	1:00	S
Rule	Belgium	1920	only	-	Oct	23	23:00s	0	-
Rule	Belgium	1921	only	-	Mar	14	23:00s	1:00	S
Rule	Belgium	1921	only	-	Oct	25	23:00s	0	-
Rule	Belgium	1922	only	-	Mar	25	23:00s	1:00	S
Rule	Belgium	1922	1927	-	Oct	Sat>=1	23:00s	0	-
Rule	Belgium	1923	only	-	Apr	21	23:00s	1:00	S
Rule	Belgium	1924	only	-	Mar	29	23:00s	1:00	S
Rule	Belgium	1925	only	-	Apr	 4	23:00s	1:00	S
# DSH writes that a royal decree of 1926-02-22 specified the Sun following 3rd
# Sat in Apr (except if it's Easter, in which case it's one Sunday earlier),
# to Sun following 1st Sat in Oct, and that a royal decree of 1928-09-15
# changed the transition times to 02:00 GMT.
Rule	Belgium	1926	only	-	Apr	17	23:00s	1:00	S
Rule	Belgium	1927	only	-	Apr	 9	23:00s	1:00	S
Rule	Belgium	1928	only	-	Apr	14	23:00s	1:00	S
Rule	Belgium	1928	1938	-	Oct	Sun>=2	 2:00s	0	-
Rule	Belgium	1929	only	-	Apr	21	 2:00s	1:00	S
Rule	Belgium	1930	only	-	Apr	13	 2:00s	1:00	S
Rule	Belgium	1931	only	-	Apr	19	 2:00s	1:00	S
Rule	Belgium	1932	only	-	Apr	 3	 2:00s	1:00	S
Rule	Belgium	1933	only	-	Mar	26	 2:00s	1:00	S
Rule	Belgium	1934	only	-	Apr	 8	 2:00s	1:00	S
Rule	Belgium	1935	only	-	Mar	31	 2:00s	1:00	S
Rule	Belgium	1936	only	-	Apr	19	 2:00s	1:00	S
Rule	Belgium	1937	only	-	Apr	 4	 2:00s	1:00	S
Rule	Belgium	1938	only	-	Mar	27	 2:00s	1:00	S
Rule	Belgium	1939	only	-	Apr	16	 2:00s	1:00	S
Rule	Belgium	1939	only	-	Nov	19	 2:00s	0	-
Rule	Belgium	1940	only	-	Feb	25	 2:00s	1:00	S
Rule	Belgium	1944	only	-	Sep	17	 2:00s	0	-
Rule	Belgium	1945	only	-	Apr	 2	 2:00s	1:00	S
Rule	Belgium	1945	only	-	Sep	16	 2:00s	0	-
Rule	Belgium	1946	only	-	May	19	 2:00s	1:00	S
Rule	Belgium	1946	only	-	Oct	 7	 2:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Brussels	0:17:30 -	LMT	1880
			0:17:30	-	BMT	1892 May  1 12:00 # Brussels MT
			0:00	-	WET	1914 Nov  8
			1:00	-	CET	1916 May  1  0:00
			1:00	C-Eur	CE%sT	1918 Nov 11 11:00u
			0:00	Belgium	WE%sT	1940 May 20  2:00s
			1:00	C-Eur	CE%sT	1944 Sep  3
			1:00	Belgium	CE%sT	1977
			1:00	EU	CE%sT

# Bosnia and Herzegovina
# see Serbia

# Bulgaria
#
# From Plamen Simenov via Steffen Thorsen (1999-09-09):
# A document of Government of Bulgaria (No.94/1997) says:
# EET --> EETDST is in 03:00 Local time in last Sunday of March ...
# EETDST --> EET is in 04:00 Local time in last Sunday of October
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Bulg	1979	only	-	Mar	31	23:00	1:00	S
Rule	Bulg	1979	only	-	Oct	 1	 1:00	0	-
Rule	Bulg	1980	1982	-	Apr	Sat>=1	23:00	1:00	S
Rule	Bulg	1980	only	-	Sep	29	 1:00	0	-
Rule	Bulg	1981	only	-	Sep	27	 2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Sofia	1:33:16 -	LMT	1880
			1:56:56	-	IMT	1894 Nov 30 # Istanbul MT?
			2:00	-	EET	1942 Nov  2  3:00
			1:00	C-Eur	CE%sT	1945
			1:00	-	CET	1945 Apr 2 3:00
			2:00	-	EET	1979 Mar 31 23:00
			2:00	Bulg	EE%sT	1982 Sep 26  2:00
			2:00	C-Eur	EE%sT	1991
			2:00	E-Eur	EE%sT	1997
			2:00	EU	EE%sT

# Croatia
# see Serbia

# Cyprus
# Please see the `asia' file for Asia/Nicosia.

# Czech Republic
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Czech	1945	only	-	Apr	 8	2:00s	1:00	S
Rule	Czech	1945	only	-	Nov	18	2:00s	0	-
Rule	Czech	1946	only	-	May	 6	2:00s	1:00	S
Rule	Czech	1946	1949	-	Oct	Sun>=1	2:00s	0	-
Rule	Czech	1947	only	-	Apr	20	2:00s	1:00	S
Rule	Czech	1948	only	-	Apr	18	2:00s	1:00	S
Rule	Czech	1949	only	-	Apr	 9	2:00s	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Prague	0:57:44 -	LMT	1850
			0:57:44	-	PMT	1891 Oct     # Prague Mean Time
			1:00	C-Eur	CE%sT	1944 Sep 17 2:00s
			1:00	Czech	CE%sT	1979
			1:00	EU	CE%sT

# Denmark, Faroe Islands, and Greenland

# From Jesper Norgaard Welen (2005-04-26):
# http://www.hum.aau.dk/~poe/tid/tine/DanskTid.htm says that the law
# [introducing standard time] was in effect from 1894-01-01....
# The page http://www.retsinfo.dk/_GETDOCI_/ACCN/A18930008330-REGL
# confirms this, and states that the law was put forth 1893-03-29.
#
# The EU treaty with effect from 1973:
# http://www.retsinfo.dk/_GETDOCI_/ACCN/A19722110030-REGL
#
# This provoked a new law from 1974 to make possible summer time changes
# in subsequenet decrees with the law
# http://www.retsinfo.dk/_GETDOCI_/ACCN/A19740022330-REGL
#
# It seems however that no decree was set forward until 1980.  I have
# not found any decree, but in another related law, the effecting DST
# changes are stated explicitly to be from 1980-04-06 at 02:00 to
# 1980-09-28 at 02:00.  If this is true, this differs slightly from
# the EU rule in that DST runs to 02:00, not 03:00.  We don't know
# when Denmark began using the EU rule correctly, but we have only
# confirmation of the 1980-time, so I presume it was correct in 1981:
# The law is about the management of the extra hour, concerning
# working hours reported and effect on obligatory-rest rules (which
# was suspended on that night):
# http://www.retsinfo.dk/_GETDOCI_/ACCN/C19801120554-REGL

# From Jesper Norgaard Welen (2005-06-11):
# The Herning Folkeblad (1980-09-26) reported that the night between
# Saturday and Sunday the clock is set back from three to two.

# From Paul Eggert (2005-06-11):
# Hence the "02:00" of the 1980 law refers to standard time, not
# wall-clock time, and so the EU rules were in effect in 1980.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Denmark	1916	only	-	May	14	23:00	1:00	S
Rule	Denmark	1916	only	-	Sep	30	23:00	0	-
Rule	Denmark	1940	only	-	May	15	 0:00	1:00	S
Rule	Denmark	1945	only	-	Apr	 2	 2:00s	1:00	S
Rule	Denmark	1945	only	-	Aug	15	 2:00s	0	-
Rule	Denmark	1946	only	-	May	 1	 2:00s	1:00	S
Rule	Denmark	1946	only	-	Sep	 1	 2:00s	0	-
Rule	Denmark	1947	only	-	May	 4	 2:00s	1:00	S
Rule	Denmark	1947	only	-	Aug	10	 2:00s	0	-
Rule	Denmark	1948	only	-	May	 9	 2:00s	1:00	S
Rule	Denmark	1948	only	-	Aug	 8	 2:00s	0	-
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Europe/Copenhagen	 0:50:20 -	LMT	1890
			 0:50:20 -	CMT	1894 Jan  1 # Copenhagen MT
			 1:00	Denmark	CE%sT	1942 Nov  2 2:00s
			 1:00	C-Eur	CE%sT	1945 Apr  2 2:00
			 1:00	Denmark	CE%sT	1980
			 1:00	EU	CE%sT
Zone Atlantic/Faroe	-0:27:04 -	LMT	1908 Jan 11	# Torshavn
			 0:00	-	WET	1981
			 0:00	EU	WE%sT
#
# From Paul Eggert (2004-10-31):
# During World War II, Germany maintained secret manned weather stations in
# East Greenland and Franz Josef Land, but we don't know their time zones.
# My source for this is Wilhelm Dege's book mentioned under Svalbard.
#
# From Paul Eggert (2006-03-22):
# Greenland joined the EU as part of Denmark, obtained home rule on 1979-05-01,
# and left the EU on 1985-02-01.  It therefore should have been using EU
# rules at least through 1984.  Shanks & Pottenger say Scoresbysund and Godthab
# used C-Eur rules after 1980, but IATA SSIM (1991/1996) says they use EU
# rules since at least 1991.  Assume EU rules since 1980.

# From Gwillin Law (2001-06-06), citing
#  (2001-03-15),
# and with translations corrected by Steffen Thorsen:
#
# Greenland has four local times, and the relation to UTC
# is according to the following time line:
#
# The military zone near Thule	UTC-4
# Standard Greenland time	UTC-3
# Scoresbysund			UTC-1
# Danmarkshavn			UTC
#
# In the military area near Thule and in Danmarkshavn DST will not be
# introduced.

# From Rives McDow (2001-11-01):
#
# I correspond regularly with the Dansk Polarcenter, and wrote them at
# the time to clarify the situation in Thule.  Unfortunately, I have
# not heard back from them regarding my recent letter.  [But I have
# info from earlier correspondence.]
#
# According to the center, a very small local time zone around Thule
# Air Base keeps the time according to UTC-4, implementing daylight
# savings using North America rules, changing the time at 02:00 local time....
#
# The east coast of Greenland north of the community of Scoresbysund
# uses UTC in the same way as in Iceland, year round, with no dst.
# There are just a few stations on this coast, including the
# Danmarkshavn ICAO weather station mentioned in your September 29th
# email.  The other stations are two sledge patrol stations in
# Mestersvig and Daneborg, the air force base at Station Nord, and the
# DPC research station at Zackenberg.
#
# Scoresbysund and two small villages nearby keep time UTC-1 and use
# the same daylight savings time period as in West Greenland (Godthab).
#
# The rest of Greenland, including Godthab (this area, although it
# includes central Greenland, is known as west Greenland), keeps time
# UTC-3, with daylight savings methods according to European rules.
#
# It is common procedure to use UTC 0 in the wilderness of East and
# North Greenland, because it is mainly Icelandic aircraft operators
# maintaining traffic in these areas.  However, the official status of
# this area is that it sticks with Godthab time.  This area might be
# considered a dual time zone in some respects because of this.

# From Rives McDow (2001-11-19):
# I heard back from someone stationed at Thule; the time change took place
# there at 2:00 AM.

# From Paul Eggert (2006-03-22):
# From 1997 on the CIA map shows Danmarkshavn on GMT;
# the 1995 map as like Godthab.
# For lack of better info, assume they were like Godthab before 1996.
# startkart.no says Thule does not observe DST, but this is clearly an error,
# so go with Shanks & Pottenger for Thule transitions until this year.
# For 2007 on assume Thule will stay in sync with US DST rules.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Thule	1991	1992	-	Mar	lastSun	2:00	1:00	D
Rule	Thule	1991	1992	-	Sep	lastSun	2:00	0	S
Rule	Thule	1993	2006	-	Apr	Sun>=1	2:00	1:00	D
Rule	Thule	1993	2006	-	Oct	lastSun	2:00	0	S
Rule	Thule	2007	max	-	Mar	Sun>=8	2:00	1:00	D
Rule	Thule	2007	max	-	Nov	Sun>=1	2:00	0	S
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone America/Danmarkshavn -1:14:40 -	LMT	1916 Jul 28
			-3:00	-	WGT	1980 Apr  6 2:00
			-3:00	EU	WG%sT	1996
			0:00	-	GMT
Zone America/Scoresbysund -1:27:52 -	LMT	1916 Jul 28 # Ittoqqortoormiit
			-2:00	-	CGT	1980 Apr  6 2:00
			-2:00	C-Eur	CG%sT	1981 Mar 29
			-1:00	EU	EG%sT
Zone America/Godthab	-3:26:56 -	LMT	1916 Jul 28 # Nuuk
			-3:00	-	WGT	1980 Apr  6 2:00
			-3:00	EU	WG%sT
Zone America/Thule	-4:35:08 -	LMT	1916 Jul 28 # Pituffik air base
			-4:00	Thule	A%sT

# Estonia
# From Peter Ilieve (1994-10-15):
# A relative in Tallinn confirms the accuracy of the data for 1989 onwards
# [through 1994] and gives the legal authority for it,
# a regulation of the Government of Estonia, No. 111 of 1989....
#
# From Peter Ilieve (1996-10-28):
# [IATA SSIM (1992/1996) claims that the Baltic republics switch at 01:00s,
# but a relative confirms that Estonia still switches at 02:00s, writing:]
# ``I do not [know] exactly but there are some little different
# (confusing) rules for International Air and Railway Transport Schedules
# conversion in Sunday connected with end of summer time in Estonia....
# A discussion is running about the summer time efficiency and effect on
# human physiology.  It seems that Estonia maybe will not change to
# summer time next spring.''

# From Peter Ilieve (1998-11-04), heavily edited:
# 
# The 1998-09-22 Estonian time law
# 
# refers to the Eighth Directive and cites the association agreement between
# the EU and Estonia, ratified by the Estonian law (RT II 1995, 22--27, 120).
#
# I also asked [my relative] whether they use any standard abbreviation
# for their standard and summer times. He says no, they use "suveaeg"
# (summer time) and "talveaeg" (winter time).

# From The Baltic Times (1999-09-09)
# via Steffen Thorsen:
# This year will mark the last time Estonia shifts to summer time,
# a council of the ruling coalition announced Sept. 6....
# But what this could mean for Estonia's chances of joining the European
# Union are still unclear.  In 1994, the EU declared summer time compulsory
# for all member states until 2001.  Brussels has yet to decide what to do
# after that.

# From Mart Oruaas (2000-01-29):
# Regulation no. 301 (1999-10-12) obsoletes previous regulation
# no. 206 (1998-09-22) and thus sticks Estonia to +02:00 GMT for all
# the year round.  The regulation is effective 1999-11-01.

# From Toomas Soome (2002-02-21):
# The Estonian government has changed once again timezone politics.
# Now we are using again EU rules.
#
# From Urmet Jaanes (2002-03-28):
# The legislative reference is Government decree No. 84 on 2002-02-21.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Tallinn	1:39:00	-	LMT	1880
			1:39:00	-	TMT	1918 Feb # Tallinn Mean Time
			1:00	C-Eur	CE%sT	1919 Jul
			1:39:00	-	TMT	1921 May
			2:00	-	EET	1940 Aug  6
			3:00	-	MSK	1941 Sep 15
			1:00	C-Eur	CE%sT	1944 Sep 22
			3:00	Russia	MSK/MSD	1989 Mar 26 2:00s
			2:00	1:00	EEST	1989 Sep 24 2:00s
			2:00	C-Eur	EE%sT	1998 Sep 22
			2:00	EU	EE%sT	1999 Nov  1
			2:00	-	EET	2002 Feb 21
			2:00	EU	EE%sT

# Finland

# From Hannu Strang (1994-09-25 06:03:37 UTC):
# Well, here in Helsinki we're just changing from summer time to regular one,
# and it's supposed to change at 4am...

# From Janne Snabb (2010-0715):
#
# I noticed that the Finland data is not accurate for years 1981 and 1982.
# During these two first trial years the DST adjustment was made one hour
# earlier than in forthcoming years. Starting 1983 the adjustment was made
# according to the central European standards.
#
# This is documented in Heikki Oja: Aikakirja 2007, published by The Almanac
# Office of University of Helsinki, ISBN 952-10-3221-9, available online (in
# Finnish) at
#
# 
# http://almanakka.helsinki.fi/aikakirja/Aikakirja2007kokonaan.pdf
# 
#
# Page 105 (56 in PDF version) has a handy table of all past daylight savings
# transitions. It is easy enough to interpret without Finnish skills.
#
# This is also confirmed by Finnish Broadcasting Company's archive at:
#
# 
# http://www.yle.fi/elavaarkisto/?s=s&g=1&ag=5&t=&a=3401
# 
#
# The news clip from 1981 says that "the time between 2 and 3 o'clock does not
# exist tonight."

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Finland	1942	only	-	Apr	3	0:00	1:00	S
Rule	Finland	1942	only	-	Oct	3	0:00	0	-
Rule	Finland	1981	1982	-	Mar	lastSun	2:00	1:00	S
Rule	Finland	1981	1982	-	Sep	lastSun	3:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Helsinki	1:39:52 -	LMT	1878 May 31
			1:39:52	-	HMT	1921 May    # Helsinki Mean Time
			2:00	Finland	EE%sT	1983
			2:00	EU	EE%sT

# Aaland Is
Link	Europe/Helsinki	Europe/Mariehamn


# France

# From Ciro Discepolo (2000-12-20):
#
# Henri Le Corre, Regimes Horaires pour le monde entier, Editions
# Traditionnelles - Paris 2 books, 1993
#
# Gabriel, Traite de l'heure dans le monde, Guy Tredaniel editeur,
# Paris, 1991
#
# Francoise Gauquelin, Problemes de l'heure resolus en astrologie,
# Guy tredaniel, Paris 1987


#
# Shank & Pottenger seem to use `24:00' ambiguously; resolve it with Whitman.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	France	1916	only	-	Jun	14	23:00s	1:00	S
Rule	France	1916	1919	-	Oct	Sun>=1	23:00s	0	-
Rule	France	1917	only	-	Mar	24	23:00s	1:00	S
Rule	France	1918	only	-	Mar	 9	23:00s	1:00	S
Rule	France	1919	only	-	Mar	 1	23:00s	1:00	S
Rule	France	1920	only	-	Feb	14	23:00s	1:00	S
Rule	France	1920	only	-	Oct	23	23:00s	0	-
Rule	France	1921	only	-	Mar	14	23:00s	1:00	S
Rule	France	1921	only	-	Oct	25	23:00s	0	-
Rule	France	1922	only	-	Mar	25	23:00s	1:00	S
# DSH writes that a law of 1923-05-24 specified 3rd Sat in Apr at 23:00 to 1st
# Sat in Oct at 24:00; and that in 1930, because of Easter, the transitions
# were Apr 12 and Oct 5.  Go with Shanks & Pottenger.
Rule	France	1922	1938	-	Oct	Sat>=1	23:00s	0	-
Rule	France	1923	only	-	May	26	23:00s	1:00	S
Rule	France	1924	only	-	Mar	29	23:00s	1:00	S
Rule	France	1925	only	-	Apr	 4	23:00s	1:00	S
Rule	France	1926	only	-	Apr	17	23:00s	1:00	S
Rule	France	1927	only	-	Apr	 9	23:00s	1:00	S
Rule	France	1928	only	-	Apr	14	23:00s	1:00	S
Rule	France	1929	only	-	Apr	20	23:00s	1:00	S
Rule	France	1930	only	-	Apr	12	23:00s	1:00	S
Rule	France	1931	only	-	Apr	18	23:00s	1:00	S
Rule	France	1932	only	-	Apr	 2	23:00s	1:00	S
Rule	France	1933	only	-	Mar	25	23:00s	1:00	S
Rule	France	1934	only	-	Apr	 7	23:00s	1:00	S
Rule	France	1935	only	-	Mar	30	23:00s	1:00	S
Rule	France	1936	only	-	Apr	18	23:00s	1:00	S
Rule	France	1937	only	-	Apr	 3	23:00s	1:00	S
Rule	France	1938	only	-	Mar	26	23:00s	1:00	S
Rule	France	1939	only	-	Apr	15	23:00s	1:00	S
Rule	France	1939	only	-	Nov	18	23:00s	0	-
Rule	France	1940	only	-	Feb	25	 2:00	1:00	S
# The French rules for 1941-1944 were not used in Paris, but Shanks & Pottenger
# write that they were used in Monaco and in many French locations.
# Le Corre writes that the upper limit of the free zone was Arneguy, Orthez,
# Mont-de-Marsan, Bazas, Langon, Lamotte-Montravel, Marouil, La
# Rochefoucault, Champagne-Mouton, La Roche-Posay, La Haye-Descartes,
# Loches, Montrichard, Vierzon, Bourges, Moulins, Digoin,
# Paray-le-Monial, Montceau-les-Mines, Chalons-sur-Saone, Arbois,
# Dole, Morez, St-Claude, and Collonges (Haute-Savoie).
Rule	France	1941	only	-	May	 5	 0:00	2:00	M # Midsummer
# Shanks & Pottenger say this transition occurred at Oct 6 1:00,
# but go with Denis Excoffier (1997-12-12),
# who quotes the Ephemerides Astronomiques for 1998 from Bureau des Longitudes
# as saying 5/10/41 22hUT.
Rule	France	1941	only	-	Oct	 6	 0:00	1:00	S
Rule	France	1942	only	-	Mar	 9	 0:00	2:00	M
Rule	France	1942	only	-	Nov	 2	 3:00	1:00	S
Rule	France	1943	only	-	Mar	29	 2:00	2:00	M
Rule	France	1943	only	-	Oct	 4	 3:00	1:00	S
Rule	France	1944	only	-	Apr	 3	 2:00	2:00	M
Rule	France	1944	only	-	Oct	 8	 1:00	1:00	S
Rule	France	1945	only	-	Apr	 2	 2:00	2:00	M
Rule	France	1945	only	-	Sep	16	 3:00	0	-
# Shanks & Pottenger give Mar 28 2:00 and Sep 26 3:00;
# go with Excoffier's 28/3/76 0hUT and 25/9/76 23hUT.
Rule	France	1976	only	-	Mar	28	 1:00	1:00	S
Rule	France	1976	only	-	Sep	26	 1:00	0	-
# Shanks & Pottenger give 0:09:20 for Paris Mean Time, and Whitman 0:09:05,
# but Howse quotes the actual French legislation as saying 0:09:21.
# Go with Howse.  Howse writes that the time in France was officially based
# on PMT-0:09:21 until 1978-08-09, when the time base finally switched to UTC.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Paris	0:09:21 -	LMT	1891 Mar 15  0:01
			0:09:21	-	PMT	1911 Mar 11  0:01  # Paris MT
# Shanks & Pottenger give 1940 Jun 14 0:00; go with Excoffier and Le Corre.
			0:00	France	WE%sT	1940 Jun 14 23:00
# Le Corre says Paris stuck with occupied-France time after the liberation;
# go with Shanks & Pottenger.
			1:00	C-Eur	CE%sT	1944 Aug 25
			0:00	France	WE%sT	1945 Sep 16  3:00
			1:00	France	CE%sT	1977
			1:00	EU	CE%sT

# Germany

# From Markus Kuhn (1998-09-29):
# The German time zone web site by the Physikalisch-Technische
# Bundesanstalt contains DST information back to 1916.
# [See tz-link.htm for the URL.]

# From Joerg Schilling (2002-10-23):
# In 1945, Berlin was switched to Moscow Summer time (GMT+4) by
# 
# General [Nikolai] Bersarin.

# From Paul Eggert (2003-03-08):
# 
# http://www.parlament-berlin.de/pds-fraktion.nsf/727459127c8b66ee8525662300459099/defc77cb784f180ac1256c2b0030274b/$FILE/bersarint.pdf
# 
# says that Bersarin issued an order to use Moscow time on May 20.
# However, Moscow did not observe daylight saving in 1945, so
# this was equivalent to CEMT (GMT+3), not GMT+4.


# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Germany	1946	only	-	Apr	14	2:00s	1:00	S
Rule	Germany	1946	only	-	Oct	 7	2:00s	0	-
Rule	Germany	1947	1949	-	Oct	Sun>=1	2:00s	0	-
# http://www.ptb.de/de/org/4/44/441/salt.htm says the following transition
# occurred at 3:00 MEZ, not the 2:00 MEZ given in Shanks & Pottenger.
# Go with the PTB.
Rule	Germany	1947	only	-	Apr	 6	3:00s	1:00	S
Rule	Germany	1947	only	-	May	11	2:00s	2:00	M
Rule	Germany	1947	only	-	Jun	29	3:00	1:00	S
Rule	Germany	1948	only	-	Apr	18	2:00s	1:00	S
Rule	Germany	1949	only	-	Apr	10	2:00s	1:00	S

Rule SovietZone	1945	only	-	May	24	2:00	2:00	M # Midsummer
Rule SovietZone	1945	only	-	Sep	24	3:00	1:00	S
Rule SovietZone	1945	only	-	Nov	18	2:00s	0	-

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Berlin	0:53:28 -	LMT	1893 Apr
			1:00	C-Eur	CE%sT	1945 May 24 2:00
			1:00 SovietZone	CE%sT	1946
			1:00	Germany	CE%sT	1980
			1:00	EU	CE%sT

# From Tobias Conradi (2011-09-12):
# Busingen , surrounded by the Swiss canton
# Schaffhausen, did not start observing DST in 1980 as the rest of DE
# (West Germany at that time) and DD (East Germany at that time) did.
# DD merged into DE, the area is currently covered by code DE in ISO 3166-1,
# which in turn is covered by the zone Europe/Berlin.
#
# Source for the time in Busingen 1980:
# http://www.srf.ch/player/video?id=c012c029-03b7-4c2b-9164-aa5902cd58d3

# From Arthur David Olson (2012-03-03):
# Busingen and Zurich have shared clocks since 1970.

Link	Europe/Zurich	Europe/Busingen

# Georgia
# Please see the "asia" file for Asia/Tbilisi.
# Herodotus (Histories, IV.45) says Georgia north of the Phasis (now Rioni)
# is in Europe.  Our reference location Tbilisi is in the Asian part.

# Gibraltar
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Europe/Gibraltar	-0:21:24 -	LMT	1880 Aug  2 0:00s
			0:00	GB-Eire	%s	1957 Apr 14 2:00
			1:00	-	CET	1982
			1:00	EU	CE%sT

# Greece
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# Whitman gives 1932 Jul 5 - Nov 1; go with Shanks & Pottenger.
Rule	Greece	1932	only	-	Jul	 7	0:00	1:00	S
Rule	Greece	1932	only	-	Sep	 1	0:00	0	-
# Whitman gives 1941 Apr 25 - ?; go with Shanks & Pottenger.
Rule	Greece	1941	only	-	Apr	 7	0:00	1:00	S
# Whitman gives 1942 Feb 2 - ?; go with Shanks & Pottenger.
Rule	Greece	1942	only	-	Nov	 2	3:00	0	-
Rule	Greece	1943	only	-	Mar	30	0:00	1:00	S
Rule	Greece	1943	only	-	Oct	 4	0:00	0	-
# Whitman gives 1944 Oct 3 - Oct 31; go with Shanks & Pottenger.
Rule	Greece	1952	only	-	Jul	 1	0:00	1:00	S
Rule	Greece	1952	only	-	Nov	 2	0:00	0	-
Rule	Greece	1975	only	-	Apr	12	0:00s	1:00	S
Rule	Greece	1975	only	-	Nov	26	0:00s	0	-
Rule	Greece	1976	only	-	Apr	11	2:00s	1:00	S
Rule	Greece	1976	only	-	Oct	10	2:00s	0	-
Rule	Greece	1977	1978	-	Apr	Sun>=1	2:00s	1:00	S
Rule	Greece	1977	only	-	Sep	26	2:00s	0	-
Rule	Greece	1978	only	-	Sep	24	4:00	0	-
Rule	Greece	1979	only	-	Apr	 1	9:00	1:00	S
Rule	Greece	1979	only	-	Sep	29	2:00	0	-
Rule	Greece	1980	only	-	Apr	 1	0:00	1:00	S
Rule	Greece	1980	only	-	Sep	28	0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Athens	1:34:52 -	LMT	1895 Sep 14
			1:34:52	-	AMT	1916 Jul 28 0:01     # Athens MT
			2:00	Greece	EE%sT	1941 Apr 30
			1:00	Greece	CE%sT	1944 Apr  4
			2:00	Greece	EE%sT	1981
			# Shanks & Pottenger say it switched to C-Eur in 1981;
			# go with EU instead, since Greece joined it on Jan 1.
			2:00	EU	EE%sT

# Hungary
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Hungary	1918	only	-	Apr	 1	 3:00	1:00	S
Rule	Hungary	1918	only	-	Sep	29	 3:00	0	-
Rule	Hungary	1919	only	-	Apr	15	 3:00	1:00	S
Rule	Hungary	1919	only	-	Sep	15	 3:00	0	-
Rule	Hungary	1920	only	-	Apr	 5	 3:00	1:00	S
Rule	Hungary	1920	only	-	Sep	30	 3:00	0	-
Rule	Hungary	1945	only	-	May	 1	23:00	1:00	S
Rule	Hungary	1945	only	-	Nov	 3	 0:00	0	-
Rule	Hungary	1946	only	-	Mar	31	 2:00s	1:00	S
Rule	Hungary	1946	1949	-	Oct	Sun>=1	 2:00s	0	-
Rule	Hungary	1947	1949	-	Apr	Sun>=4	 2:00s	1:00	S
Rule	Hungary	1950	only	-	Apr	17	 2:00s	1:00	S
Rule	Hungary	1950	only	-	Oct	23	 2:00s	0	-
Rule	Hungary	1954	1955	-	May	23	 0:00	1:00	S
Rule	Hungary	1954	1955	-	Oct	 3	 0:00	0	-
Rule	Hungary	1956	only	-	Jun	Sun>=1	 0:00	1:00	S
Rule	Hungary	1956	only	-	Sep	lastSun	 0:00	0	-
Rule	Hungary	1957	only	-	Jun	Sun>=1	 1:00	1:00	S
Rule	Hungary	1957	only	-	Sep	lastSun	 3:00	0	-
Rule	Hungary	1980	only	-	Apr	 6	 1:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Budapest	1:16:20 -	LMT	1890 Oct
			1:00	C-Eur	CE%sT	1918
			1:00	Hungary	CE%sT	1941 Apr  6  2:00
			1:00	C-Eur	CE%sT	1945
			1:00	Hungary	CE%sT	1980 Sep 28  2:00s
			1:00	EU	CE%sT

# Iceland
#
# From Adam David (1993-11-06):
# The name of the timezone in Iceland for system / mail / news purposes is GMT.
#
# (1993-12-05):
# This material is paraphrased from the 1988 edition of the University of
# Iceland Almanak.
#
# From January 1st, 1908 the whole of Iceland was standardised at 1 hour
# behind GMT. Previously, local mean solar time was used in different parts
# of Iceland, the almanak had been based on Reykjavik mean solar time which
# was 1 hour and 28 minutes behind GMT.
#
# "first day of winter" referred to [below] means the first day of the 26 weeks
# of winter, according to the old icelandic calendar that dates back to the
# time the norsemen first settled Iceland.  The first day of winter is always
# Saturday, but is not dependent on the Julian or Gregorian calendars.
#
# (1993-12-10):
# I have a reference from the Oxford Icelandic-English dictionary for the
# beginning of winter, which ties it to the ecclesiastical calendar (and thus
# to the julian/gregorian calendar) over the period in question.
#	the winter begins on the Saturday next before St. Luke's day
#	(old style), or on St. Luke's day, if a Saturday.
# St. Luke's day ought to be traceable from ecclesiastical sources. "old style"
# might be a reference to the Julian calendar as opposed to Gregorian, or it
# might mean something else (???).
#
# From Paul Eggert (2006-03-22):
# The Iceland Almanak, Shanks & Pottenger, and Whitman disagree on many points.
# We go with the Almanak, except for one claim from Shanks & Pottenger, namely
# that Reykavik was 21W57 from 1837 to 1908, local mean time before that.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Iceland	1917	1918	-	Feb	19	23:00	1:00	S
Rule	Iceland	1917	only	-	Oct	21	 1:00	0	-
Rule	Iceland	1918	only	-	Nov	16	 1:00	0	-
Rule	Iceland	1939	only	-	Apr	29	23:00	1:00	S
Rule	Iceland	1939	only	-	Nov	29	 2:00	0	-
Rule	Iceland	1940	only	-	Feb	25	 2:00	1:00	S
Rule	Iceland	1940	only	-	Nov	 3	 2:00	0	-
Rule	Iceland	1941	only	-	Mar	 2	 1:00s	1:00	S
Rule	Iceland	1941	only	-	Nov	 2	 1:00s	0	-
Rule	Iceland	1942	only	-	Mar	 8	 1:00s	1:00	S
Rule	Iceland	1942	only	-	Oct	25	 1:00s	0	-
# 1943-1946 - first Sunday in March until first Sunday in winter
Rule	Iceland	1943	1946	-	Mar	Sun>=1	 1:00s	1:00	S
Rule	Iceland	1943	1948	-	Oct	Sun>=22	 1:00s	0	-
# 1947-1967 - first Sunday in April until first Sunday in winter
Rule	Iceland	1947	1967	-	Apr	Sun>=1	 1:00s	1:00	S
# 1949 Oct transition delayed by 1 week
Rule	Iceland	1949	only	-	Oct	30	 1:00s	0	-
Rule	Iceland	1950	1966	-	Oct	Sun>=22	 1:00s	0	-
Rule	Iceland	1967	only	-	Oct	29	 1:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Atlantic/Reykjavik	-1:27:24 -	LMT	1837
			-1:27:48 -	RMT	1908 # Reykjavik Mean Time?
			-1:00	Iceland	IS%sT	1968 Apr 7 1:00s
			 0:00	-	GMT

# Italy
#
# From Paul Eggert (2001-03-06):
# Sicily and Sardinia each had their own time zones from 1866 to 1893,
# called Palermo Time (+00:53:28) and Cagliari Time (+00:36:32).
# During World War II, German-controlled Italy used German time.
# But these events all occurred before the 1970 cutoff,
# so record only the time in Rome.
#
# From Paul Eggert (2006-03-22):
# For Italian DST we have three sources: Shanks & Pottenger, Whitman, and
# F. Pollastri
# 
# Day-light Saving Time in Italy (2006-02-03)
# 
# (`FP' below), taken from an Italian National Electrotechnical Institute
# publication. When the three sources disagree, guess who's right, as follows:
#
# year	FP	Shanks&P. (S)	Whitman (W)	Go with:
# 1916	06-03	06-03 24:00	06-03 00:00	FP & W
#	09-30	09-30 24:00	09-30 01:00	FP; guess 24:00s
# 1917	04-01	03-31 24:00	03-31 00:00	FP & S
#	09-30	09-29 24:00	09-30 01:00	FP & W
# 1918	03-09	03-09 24:00	03-09 00:00	FP & S
#	10-06	10-05 24:00	10-06 01:00	FP & W
# 1919	03-01	03-01 24:00	03-01 00:00	FP & S
#	10-04	10-04 24:00	10-04 01:00	FP; guess 24:00s
# 1920	03-20	03-20 24:00	03-20 00:00	FP & S
#	09-18	09-18 24:00	10-01 01:00	FP; guess 24:00s
# 1944	04-02	04-03 02:00			S (see C-Eur)
#	09-16	10-02 03:00			FP; guess 24:00s
# 1945	09-14	09-16 24:00			FP; guess 24:00s
# 1970	05-21	05-31 00:00			S
#	09-20	09-27 00:00			S
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Italy	1916	only	-	Jun	 3	0:00s	1:00	S
Rule	Italy	1916	only	-	Oct	 1	0:00s	0	-
Rule	Italy	1917	only	-	Apr	 1	0:00s	1:00	S
Rule	Italy	1917	only	-	Sep	30	0:00s	0	-
Rule	Italy	1918	only	-	Mar	10	0:00s	1:00	S
Rule	Italy	1918	1919	-	Oct	Sun>=1	0:00s	0	-
Rule	Italy	1919	only	-	Mar	 2	0:00s	1:00	S
Rule	Italy	1920	only	-	Mar	21	0:00s	1:00	S
Rule	Italy	1920	only	-	Sep	19	0:00s	0	-
Rule	Italy	1940	only	-	Jun	15	0:00s	1:00	S
Rule	Italy	1944	only	-	Sep	17	0:00s	0	-
Rule	Italy	1945	only	-	Apr	 2	2:00	1:00	S
Rule	Italy	1945	only	-	Sep	15	0:00s	0	-
Rule	Italy	1946	only	-	Mar	17	2:00s	1:00	S
Rule	Italy	1946	only	-	Oct	 6	2:00s	0	-
Rule	Italy	1947	only	-	Mar	16	0:00s	1:00	S
Rule	Italy	1947	only	-	Oct	 5	0:00s	0	-
Rule	Italy	1948	only	-	Feb	29	2:00s	1:00	S
Rule	Italy	1948	only	-	Oct	 3	2:00s	0	-
Rule	Italy	1966	1968	-	May	Sun>=22	0:00	1:00	S
Rule	Italy	1966	1969	-	Sep	Sun>=22	0:00	0	-
Rule	Italy	1969	only	-	Jun	 1	0:00	1:00	S
Rule	Italy	1970	only	-	May	31	0:00	1:00	S
Rule	Italy	1970	only	-	Sep	lastSun	0:00	0	-
Rule	Italy	1971	1972	-	May	Sun>=22	0:00	1:00	S
Rule	Italy	1971	only	-	Sep	lastSun	1:00	0	-
Rule	Italy	1972	only	-	Oct	 1	0:00	0	-
Rule	Italy	1973	only	-	Jun	 3	0:00	1:00	S
Rule	Italy	1973	1974	-	Sep	lastSun	0:00	0	-
Rule	Italy	1974	only	-	May	26	0:00	1:00	S
Rule	Italy	1975	only	-	Jun	 1	0:00s	1:00	S
Rule	Italy	1975	1977	-	Sep	lastSun	0:00s	0	-
Rule	Italy	1976	only	-	May	30	0:00s	1:00	S
Rule	Italy	1977	1979	-	May	Sun>=22	0:00s	1:00	S
Rule	Italy	1978	only	-	Oct	 1	0:00s	0	-
Rule	Italy	1979	only	-	Sep	30	0:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Rome	0:49:56 -	LMT	1866 Sep 22
			0:49:56	-	RMT	1893 Nov  1 0:00s # Rome Mean
			1:00	Italy	CE%sT	1942 Nov  2 2:00s
			1:00	C-Eur	CE%sT	1944 Jul
			1:00	Italy	CE%sT	1980
			1:00	EU	CE%sT

Link	Europe/Rome	Europe/Vatican
Link	Europe/Rome	Europe/San_Marino

# Latvia

# From Liene Kanepe (1998-09-17):

# I asked about this matter Scientific Secretary of the Institute of Astronomy
# of The University of Latvia Dr. paed Mr. Ilgonis Vilks. I also searched the
# correct data in juridical acts and I found some juridical documents about
# changes in the counting of time in Latvia from 1981....
#
# Act No.35 of the Council of Ministers of Latvian SSR of 1981-01-22 ...
# according to the Act No.925 of the Council of Ministers of USSR of 1980-10-24
# ...: all year round the time of 2nd time zone + 1 hour, in addition turning
# the hands of the clock 1 hour forward on 1 April at 00:00 (GMT 31 March 21:00)
# and 1 hour backward on the 1 October at 00:00 (GMT 30 September 20:00).
#
# Act No.592 of the Council of Ministers of Latvian SSR of 1984-09-24 ...
# according to the Act No.967 of the Council of Ministers of USSR of 1984-09-13
# ...: all year round the time of 2nd time zone + 1 hour, in addition turning
# the hands of the clock 1 hour forward on the last Sunday of March at 02:00
# (GMT 23:00 on the previous day) and 1 hour backward on the last Sunday of
# September at 03:00 (GMT 23:00 on the previous day).
#
# Act No.81 of the Council of Ministers of Latvian SSR of 1989-03-22 ...
# according to the Act No.227 of the Council of Ministers of USSR of 1989-03-14
# ...: since the last Sunday of March 1989 in Lithuanian SSR, Latvian SSR,
# Estonian SSR and Kaliningrad region of Russian Federation all year round the
# time of 2nd time zone (Moscow time minus one hour). On the territory of Latvia
# transition to summer time is performed on the last Sunday of March at 02:00
# (GMT 00:00), turning the hands of the clock 1 hour forward.  The end of
# daylight saving time is performed on the last Sunday of September at 03:00
# (GMT 00:00), turning the hands of the clock 1 hour backward. Exception is
# 1989-03-26, when we must not turn the hands of the clock....
#
# The Regulations of the Cabinet of Ministers of the Republic of Latvia of
# 1997-01-21 on transition to Summer time ... established the same order of
# daylight savings time settings as in the States of the European Union.

# From Andrei Ivanov (2000-03-06):
# This year Latvia will not switch to Daylight Savings Time (as specified in
# 
# The Regulations of the Cabinet of Ministers of the Rep. of Latvia of
# 29-Feb-2000 (#79), in Latvian for subscribers only).

# 
# From RFE/RL Newsline (2001-01-03), noted after a heads-up by Rives McDow:
# 
# The Latvian government on 2 January decided that the country will
# institute daylight-saving time this spring, LETA reported.
# Last February the three Baltic states decided not to turn back their
# clocks one hour in the spring....
# Minister of Economy Aigars Kalvitis noted that Latvia had too few
# daylight hours and thus decided to comply with a draft European
# Commission directive that provides for instituting daylight-saving
# time in EU countries between 2002 and 2006. The Latvian government
# urged Lithuania and Estonia to adopt a similar time policy, but it
# appears that they will not do so....

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Latvia	1989	1996	-	Mar	lastSun	 2:00s	1:00	S
Rule	Latvia	1989	1996	-	Sep	lastSun	 2:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Riga	1:36:24	-	LMT	1880
			1:36:24	-	RMT	1918 Apr 15 2:00 #Riga Mean Time
			1:36:24	1:00	LST	1918 Sep 16 3:00 #Latvian Summer
			1:36:24	-	RMT	1919 Apr  1 2:00
			1:36:24	1:00	LST	1919 May 22 3:00
			1:36:24	-	RMT	1926 May 11
			2:00	-	EET	1940 Aug  5
			3:00	-	MSK	1941 Jul
			1:00	C-Eur	CE%sT	1944 Oct 13
			3:00	Russia	MSK/MSD	1989 Mar lastSun 2:00s
			2:00	1:00	EEST	1989 Sep lastSun 2:00s
			2:00	Latvia	EE%sT	1997 Jan 21
			2:00	EU	EE%sT	2000 Feb 29
			2:00	-	EET	2001 Jan  2
			2:00	EU	EE%sT

# Liechtenstein
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Vaduz	0:38:04 -	LMT	1894 Jun
			1:00	-	CET	1981
			1:00	EU	CE%sT

# Lithuania

# From Paul Eggert (1996-11-22):
# IATA SSIM (1992/1996) says Lithuania uses W-Eur rules, but since it is
# known to be wrong about Estonia and Latvia, assume it's wrong here too.

# From Marius Gedminas (1998-08-07):
# I would like to inform that in this year Lithuanian time zone
# (Europe/Vilnius) was changed.

# From ELTA No. 972 (2582) (1999-09-29),
# via Steffen Thorsen:
# Lithuania has shifted back to the second time zone (GMT plus two hours)
# to be valid here starting from October 31,
# as decided by the national government on Wednesday....
# The Lithuanian government also announced plans to consider a
# motion to give up shifting to summer time in spring, as it was
# already done by Estonia.

# From the 
# Fact File, Lithuanian State Department of Tourism
#  (2000-03-27): Local time is GMT+2 hours ..., no daylight saving.

# From a user via Klaus Marten (2003-02-07):
# As a candidate for membership of the European Union, Lithuania will
# observe Summer Time in 2003, changing its clocks at the times laid
# down in EU Directive 2000/84 of 19.I.01 (i.e. at the same times as its
# neighbour Latvia). The text of the Lithuanian government Order of
# 7.XI.02 to this effect can be found at
# http://www.lrvk.lt/nut/11/n1749.htm


# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Vilnius	1:41:16	-	LMT	1880
			1:24:00	-	WMT	1917	    # Warsaw Mean Time
			1:35:36	-	KMT	1919 Oct 10 # Kaunas Mean Time
			1:00	-	CET	1920 Jul 12
			2:00	-	EET	1920 Oct  9
			1:00	-	CET	1940 Aug  3
			3:00	-	MSK	1941 Jun 24
			1:00	C-Eur	CE%sT	1944 Aug
			3:00	Russia	MSK/MSD	1991 Mar 31 2:00s
			2:00	1:00	EEST	1991 Sep 29 2:00s
			2:00	C-Eur	EE%sT	1998
			2:00	-	EET	1998 Mar 29 1:00u
			1:00	EU	CE%sT	1999 Oct 31 1:00u
			2:00	-	EET	2003 Jan  1
			2:00	EU	EE%sT

# Luxembourg
# Whitman disagrees with most of these dates in minor ways;
# go with Shanks & Pottenger.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Lux	1916	only	-	May	14	23:00	1:00	S
Rule	Lux	1916	only	-	Oct	 1	 1:00	0	-
Rule	Lux	1917	only	-	Apr	28	23:00	1:00	S
Rule	Lux	1917	only	-	Sep	17	 1:00	0	-
Rule	Lux	1918	only	-	Apr	Mon>=15	 2:00s	1:00	S
Rule	Lux	1918	only	-	Sep	Mon>=15	 2:00s	0	-
Rule	Lux	1919	only	-	Mar	 1	23:00	1:00	S
Rule	Lux	1919	only	-	Oct	 5	 3:00	0	-
Rule	Lux	1920	only	-	Feb	14	23:00	1:00	S
Rule	Lux	1920	only	-	Oct	24	 2:00	0	-
Rule	Lux	1921	only	-	Mar	14	23:00	1:00	S
Rule	Lux	1921	only	-	Oct	26	 2:00	0	-
Rule	Lux	1922	only	-	Mar	25	23:00	1:00	S
Rule	Lux	1922	only	-	Oct	Sun>=2	 1:00	0	-
Rule	Lux	1923	only	-	Apr	21	23:00	1:00	S
Rule	Lux	1923	only	-	Oct	Sun>=2	 2:00	0	-
Rule	Lux	1924	only	-	Mar	29	23:00	1:00	S
Rule	Lux	1924	1928	-	Oct	Sun>=2	 1:00	0	-
Rule	Lux	1925	only	-	Apr	 5	23:00	1:00	S
Rule	Lux	1926	only	-	Apr	17	23:00	1:00	S
Rule	Lux	1927	only	-	Apr	 9	23:00	1:00	S
Rule	Lux	1928	only	-	Apr	14	23:00	1:00	S
Rule	Lux	1929	only	-	Apr	20	23:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Europe/Luxembourg	0:24:36 -	LMT	1904 Jun
			1:00	Lux	CE%sT	1918 Nov 25
			0:00	Lux	WE%sT	1929 Oct  6 2:00s
			0:00	Belgium	WE%sT	1940 May 14 3:00
			1:00	C-Eur	WE%sT	1944 Sep 18 3:00
			1:00	Belgium	CE%sT	1977
			1:00	EU	CE%sT

# Macedonia
# see Serbia

# Malta
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Malta	1973	only	-	Mar	31	0:00s	1:00	S
Rule	Malta	1973	only	-	Sep	29	0:00s	0	-
Rule	Malta	1974	only	-	Apr	21	0:00s	1:00	S
Rule	Malta	1974	only	-	Sep	16	0:00s	0	-
Rule	Malta	1975	1979	-	Apr	Sun>=15	2:00	1:00	S
Rule	Malta	1975	1980	-	Sep	Sun>=15	2:00	0	-
Rule	Malta	1980	only	-	Mar	31	2:00	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Malta	0:58:04 -	LMT	1893 Nov  2 0:00s # Valletta
			1:00	Italy	CE%sT	1942 Nov  2 2:00s
			1:00	C-Eur	CE%sT	1945 Apr  2 2:00s
			1:00	Italy	CE%sT	1973 Mar 31
			1:00	Malta	CE%sT	1981
			1:00	EU	CE%sT

# Moldova

# From Paul Eggert (2006-03-22):
# A previous version of this database followed Shanks & Pottenger, who write
# that Tiraspol switched to Moscow time on 1992-01-19 at 02:00.
# However, this is most likely an error, as Moldova declared independence
# on 1991-08-27 (the 1992-01-19 date is that of a Russian decree).
# In early 1992 there was large-scale interethnic violence in the area
# and it's possible that some Russophones continued to observe Moscow time.
# But [two people] separately reported via
# Jesper Norgaard that as of 2001-01-24 Tiraspol was like Chisinau.
# The Tiraspol entry has therefore been removed for now.
#
# From Alexander Krivenyshev (2011-10-17):
# Pridnestrovian Moldavian Republic (PMR, also known as
# "Pridnestrovie") has abolished seasonal clock change (no transition
# to the Winter Time).
#
# News (in Russian):
# 
# http://www.kyivpost.ua/russia/news/pridnestrove-otkazalos-ot-perehoda-na-zimnee-vremya-30954.html
# 
#
# 
# http://www.allmoldova.com/moldova-news/1249064116.html
# 
#
# The substance of this change (reinstatement of the Tiraspol entry)
# is from a patch from Petr Machata (2011-10-17)
#
# From Tim Parenti (2011-10-19)
# In addition, being situated at +4651+2938 would give Tiraspol
# a pre-1880 LMT offset of 1:58:32.
#
# (which agrees with the earlier entry that had been removed)
#
# From Alexander Krivenyshev (2011-10-26)
# NO need to divide Moldova into two timezones at this point.
# As of today, Transnistria (Pridnestrovie)- Tiraspol reversed its own
# decision to abolish DST this winter.
# Following Moldova and neighboring Ukraine- Transnistria (Pridnestrovie)-
# Tiraspol will go back to winter time on October 30, 2011.
# News from Moldova (in russian):
# 
# http://ru.publika.md/link_317061.html
# 


# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Chisinau	1:55:20 -	LMT	1880
			1:55	-	CMT	1918 Feb 15 # Chisinau MT
			1:44:24	-	BMT	1931 Jul 24 # Bucharest MT
			2:00	Romania	EE%sT	1940 Aug 15
			2:00	1:00	EEST	1941 Jul 17
			1:00	C-Eur	CE%sT	1944 Aug 24
			3:00	Russia	MSK/MSD	1990
			3:00	-	MSK	1990 May 6
			2:00	-	EET	1991
			2:00	Russia	EE%sT	1992
			2:00	E-Eur	EE%sT	1997
# See Romania commentary for the guessed 1997 transition to EU rules.
			2:00	EU	EE%sT

# Monaco
# Shanks & Pottenger give 0:09:20 for Paris Mean Time; go with Howse's
# more precise 0:09:21.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Monaco	0:29:32 -	LMT	1891 Mar 15
			0:09:21	-	PMT	1911 Mar 11    # Paris Mean Time
			0:00	France	WE%sT	1945 Sep 16 3:00
			1:00	France	CE%sT	1977
			1:00	EU	CE%sT

# Montenegro
# see Serbia

# Netherlands

# Howse writes that the Netherlands' railways used GMT between 1892 and 1940,
# but for other purposes the Netherlands used Amsterdam mean time.

# However, Robert H. van Gent writes (2001-04-01):
# Howse's statement is only correct up to 1909. From 1909-05-01 (00:00:00
# Amsterdam mean time) onwards, the whole of the Netherlands (including
# the Dutch railways) was required by law to observe Amsterdam mean time
# (19 minutes 32.13 seconds ahead of GMT). This had already been the
# common practice (except for the railways) for many decades but it was
# not until 1909 when the Dutch government finally defined this by law.
# On 1937-07-01 this was changed to 20 minutes (exactly) ahead of GMT and
# was generally known as Dutch Time ("Nederlandse Tijd").
#
# (2001-04-08):
# 1892-05-01 was the date when the Dutch railways were by law required to
# observe GMT while the remainder of the Netherlands adhered to the common
# practice of following Amsterdam mean time.
#
# (2001-04-09):
# In 1835 the authorities of the province of North Holland requested the
# municipal authorities of the towns and cities in the province to observe
# Amsterdam mean time but I do not know in how many cases this request was
# actually followed.
#
# From 1852 onwards the Dutch telegraph offices were by law required to
# observe Amsterdam mean time. As the time signals from the observatory of
# Leiden were also distributed by the telegraph system, I assume that most
# places linked up with the telegraph (and railway) system automatically
# adopted Amsterdam mean time.
#
# Although the early Dutch railway companies initially observed a variety
# of times, most of them had adopted Amsterdam mean time by 1858 but it
# was not until 1866 when they were all required by law to observe
# Amsterdam mean time.

# The data before 1945 are taken from
# .

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Neth	1916	only	-	May	 1	0:00	1:00	NST	# Netherlands Summer Time
Rule	Neth	1916	only	-	Oct	 1	0:00	0	AMT	# Amsterdam Mean Time
Rule	Neth	1917	only	-	Apr	16	2:00s	1:00	NST
Rule	Neth	1917	only	-	Sep	17	2:00s	0	AMT
Rule	Neth	1918	1921	-	Apr	Mon>=1	2:00s	1:00	NST
Rule	Neth	1918	1921	-	Sep	lastMon	2:00s	0	AMT
Rule	Neth	1922	only	-	Mar	lastSun	2:00s	1:00	NST
Rule	Neth	1922	1936	-	Oct	Sun>=2	2:00s	0	AMT
Rule	Neth	1923	only	-	Jun	Fri>=1	2:00s	1:00	NST
Rule	Neth	1924	only	-	Mar	lastSun	2:00s	1:00	NST
Rule	Neth	1925	only	-	Jun	Fri>=1	2:00s	1:00	NST
# From 1926 through 1939 DST began 05-15, except that it was delayed by a week
# in years when 05-15 fell in the Pentecost weekend.
Rule	Neth	1926	1931	-	May	15	2:00s	1:00	NST
Rule	Neth	1932	only	-	May	22	2:00s	1:00	NST
Rule	Neth	1933	1936	-	May	15	2:00s	1:00	NST
Rule	Neth	1937	only	-	May	22	2:00s	1:00	NST
Rule	Neth	1937	only	-	Jul	 1	0:00	1:00	S
Rule	Neth	1937	1939	-	Oct	Sun>=2	2:00s	0	-
Rule	Neth	1938	1939	-	May	15	2:00s	1:00	S
Rule	Neth	1945	only	-	Apr	 2	2:00s	1:00	S
Rule	Neth	1945	only	-	Sep	16	2:00s	0	-
#
# Amsterdam Mean Time was +00:19:32.13 exactly, but the .13 is omitted
# below because the current format requires GMTOFF to be an integer.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Europe/Amsterdam	0:19:32 -	LMT	1835
			0:19:32	Neth	%s	1937 Jul  1
			0:20	Neth	NE%sT	1940 May 16 0:00 # Dutch Time
			1:00	C-Eur	CE%sT	1945 Apr  2 2:00
			1:00	Neth	CE%sT	1977
			1:00	EU	CE%sT

# Norway
# http://met.no/met/met_lex/q_u/sommertid.html (2004-01) agrees with Shanks &
# Pottenger.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Norway	1916	only	-	May	22	1:00	1:00	S
Rule	Norway	1916	only	-	Sep	30	0:00	0	-
Rule	Norway	1945	only	-	Apr	 2	2:00s	1:00	S
Rule	Norway	1945	only	-	Oct	 1	2:00s	0	-
Rule	Norway	1959	1964	-	Mar	Sun>=15	2:00s	1:00	S
Rule	Norway	1959	1965	-	Sep	Sun>=15	2:00s	0	-
Rule	Norway	1965	only	-	Apr	25	2:00s	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Oslo	0:43:00 -	LMT	1895 Jan  1
			1:00	Norway	CE%sT	1940 Aug 10 23:00
			1:00	C-Eur	CE%sT	1945 Apr  2  2:00
			1:00	Norway	CE%sT	1980
			1:00	EU	CE%sT

# Svalbard & Jan Mayen

# From Steffen Thorsen (2001-05-01):
# Although I could not find it explicitly, it seems that Jan Mayen and
# Svalbard have been using the same time as Norway at least since the
# time they were declared as parts of Norway.  Svalbard was declared
# as a part of Norway by law of 1925-07-17 no 11, section 4 and Jan
# Mayen by law of 1930-02-27 no 2, section 2. (From
# http://www.lovdata.no/all/nl-19250717-011.html and
# http://www.lovdata.no/all/nl-19300227-002.html).  The law/regulation
# for normal/standard time in Norway is from 1894-06-29 no 1 (came
# into operation on 1895-01-01) and Svalbard/Jan Mayen seem to be a
# part of this law since 1925/1930. (From
# http://www.lovdata.no/all/nl-18940629-001.html ) I have not been
# able to find if Jan Mayen used a different time zone (e.g. -0100)
# before 1930. Jan Mayen has only been "inhabitated" since 1921 by
# Norwegian meteorologists and maybe used the same time as Norway ever
# since 1921.  Svalbard (Arctic/Longyearbyen) has been inhabited since
# before 1895, and therefore probably changed the local time somewhere
# between 1895 and 1925 (inclusive).

# From Paul Eggert (2001-05-01):
#
# Actually, Jan Mayen was never occupied by Germany during World War II,
# so it must have diverged from Oslo time during the war, as Oslo was
# keeping Berlin time.
#
#  says that the meteorologists
# burned down their station in 1940 and left the island, but returned in
# 1941 with a small Norwegian garrison and continued operations despite
# frequent air ttacks from Germans.  In 1943 the Americans established a
# radiolocating station on the island, called "Atlantic City".  Possibly
# the UTC offset changed during the war, but I think it unlikely that
# Jan Mayen used German daylight-saving rules.
#
# Svalbard is more complicated, as it was raided in August 1941 by an
# Allied party that evacuated the civilian population to England (says
# ).  The Svalbard FAQ
#  says that the Germans were
# expelled on 1942-05-14.  However, small parties of Germans did return,
# and according to Wilhelm Dege's book "War North of 80" (1954)
# 
# the German armed forces at the Svalbard weather station code-named
# Haudegen did not surrender to the Allies until September 1945.
#
# All these events predate our cutoff date of 1970.  Unless we can
# come up with more definitive info about the timekeeping during the
# war years it's probably best just do...the following for now:
Link	Europe/Oslo	Arctic/Longyearbyen

# Poland
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Poland	1918	1919	-	Sep	16	2:00s	0	-
Rule	Poland	1919	only	-	Apr	15	2:00s	1:00	S
Rule	Poland	1944	only	-	Apr	 3	2:00s	1:00	S
# Whitman gives 1944 Nov 30; go with Shanks & Pottenger.
Rule	Poland	1944	only	-	Oct	 4	2:00	0	-
# For 1944-1948 Whitman gives the previous day; go with Shanks & Pottenger.
Rule	Poland	1945	only	-	Apr	29	0:00	1:00	S
Rule	Poland	1945	only	-	Nov	 1	0:00	0	-
# For 1946 on the source is Kazimierz Borkowski,
# Torun Center for Astronomy, Dept. of Radio Astronomy, Nicolaus Copernicus U.,
# 
# Thanks to Przemyslaw Augustyniak (2005-05-28) for this reference.
# He also gives these further references:
# Mon Pol nr 13, poz 162 (1995) 
# Druk nr 2180 (2003) 
Rule	Poland	1946	only	-	Apr	14	0:00s	1:00	S
Rule	Poland	1946	only	-	Oct	 7	2:00s	0	-
Rule	Poland	1947	only	-	May	 4	2:00s	1:00	S
Rule	Poland	1947	1949	-	Oct	Sun>=1	2:00s	0	-
Rule	Poland	1948	only	-	Apr	18	2:00s	1:00	S
Rule	Poland	1949	only	-	Apr	10	2:00s	1:00	S
Rule	Poland	1957	only	-	Jun	 2	1:00s	1:00	S
Rule	Poland	1957	1958	-	Sep	lastSun	1:00s	0	-
Rule	Poland	1958	only	-	Mar	30	1:00s	1:00	S
Rule	Poland	1959	only	-	May	31	1:00s	1:00	S
Rule	Poland	1959	1961	-	Oct	Sun>=1	1:00s	0	-
Rule	Poland	1960	only	-	Apr	 3	1:00s	1:00	S
Rule	Poland	1961	1964	-	May	lastSun	1:00s	1:00	S
Rule	Poland	1962	1964	-	Sep	lastSun	1:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Warsaw	1:24:00 -	LMT	1880
			1:24:00	-	WMT	1915 Aug  5   # Warsaw Mean Time
			1:00	C-Eur	CE%sT	1918 Sep 16 3:00
			2:00	Poland	EE%sT	1922 Jun
			1:00	Poland	CE%sT	1940 Jun 23 2:00
			1:00	C-Eur	CE%sT	1944 Oct
			1:00	Poland	CE%sT	1977
			1:00	W-Eur	CE%sT	1988
			1:00	EU	CE%sT

# Portugal
#
# From Rui Pedro Salgueiro (1992-11-12):
# Portugal has recently (September, 27) changed timezone
# (from WET to MET or CET) to harmonize with EEC.
#
# Martin Bruckmann (1996-02-29) reports via Peter Ilieve
# that Portugal is reverting to 0:00 by not moving its clocks this spring.
# The new Prime Minister was fed up with getting up in the dark in the winter.
#
# From Paul Eggert (1996-11-12):
# IATA SSIM (1991-09) reports several 1991-09 and 1992-09 transitions
# at 02:00u, not 01:00u.  Assume that these are typos.
# IATA SSIM (1991/1992) reports that the Azores were at -1:00.
# IATA SSIM (1993-02) says +0:00; later issues (through 1996-09) say -1:00.
# Guess that the Azores changed to EU rules in 1992 (since that's when Portugal
# harmonized with the EU), and that they stayed +0:00 that winter.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# DSH writes that despite Decree 1,469 (1915), the change to the clocks was not
# done every year, depending on what Spain did, because of railroad schedules.
# Go with Shanks & Pottenger.
Rule	Port	1916	only	-	Jun	17	23:00	1:00	S
# Whitman gives 1916 Oct 31; go with Shanks & Pottenger.
Rule	Port	1916	only	-	Nov	 1	 1:00	0	-
Rule	Port	1917	only	-	Feb	28	23:00s	1:00	S
Rule	Port	1917	1921	-	Oct	14	23:00s	0	-
Rule	Port	1918	only	-	Mar	 1	23:00s	1:00	S
Rule	Port	1919	only	-	Feb	28	23:00s	1:00	S
Rule	Port	1920	only	-	Feb	29	23:00s	1:00	S
Rule	Port	1921	only	-	Feb	28	23:00s	1:00	S
Rule	Port	1924	only	-	Apr	16	23:00s	1:00	S
Rule	Port	1924	only	-	Oct	14	23:00s	0	-
Rule	Port	1926	only	-	Apr	17	23:00s	1:00	S
Rule	Port	1926	1929	-	Oct	Sat>=1	23:00s	0	-
Rule	Port	1927	only	-	Apr	 9	23:00s	1:00	S
Rule	Port	1928	only	-	Apr	14	23:00s	1:00	S
Rule	Port	1929	only	-	Apr	20	23:00s	1:00	S
Rule	Port	1931	only	-	Apr	18	23:00s	1:00	S
# Whitman gives 1931 Oct 8; go with Shanks & Pottenger.
Rule	Port	1931	1932	-	Oct	Sat>=1	23:00s	0	-
Rule	Port	1932	only	-	Apr	 2	23:00s	1:00	S
Rule	Port	1934	only	-	Apr	 7	23:00s	1:00	S
# Whitman gives 1934 Oct 5; go with Shanks & Pottenger.
Rule	Port	1934	1938	-	Oct	Sat>=1	23:00s	0	-
# Shanks & Pottenger give 1935 Apr 30; go with Whitman.
Rule	Port	1935	only	-	Mar	30	23:00s	1:00	S
Rule	Port	1936	only	-	Apr	18	23:00s	1:00	S
# Whitman gives 1937 Apr 2; go with Shanks & Pottenger.
Rule	Port	1937	only	-	Apr	 3	23:00s	1:00	S
Rule	Port	1938	only	-	Mar	26	23:00s	1:00	S
Rule	Port	1939	only	-	Apr	15	23:00s	1:00	S
# Whitman gives 1939 Oct 7; go with Shanks & Pottenger.
Rule	Port	1939	only	-	Nov	18	23:00s	0	-
Rule	Port	1940	only	-	Feb	24	23:00s	1:00	S
# Shanks & Pottenger give 1940 Oct 7; go with Whitman.
Rule	Port	1940	1941	-	Oct	 5	23:00s	0	-
Rule	Port	1941	only	-	Apr	 5	23:00s	1:00	S
Rule	Port	1942	1945	-	Mar	Sat>=8	23:00s	1:00	S
Rule	Port	1942	only	-	Apr	25	22:00s	2:00	M # Midsummer
Rule	Port	1942	only	-	Aug	15	22:00s	1:00	S
Rule	Port	1942	1945	-	Oct	Sat>=24	23:00s	0	-
Rule	Port	1943	only	-	Apr	17	22:00s	2:00	M
Rule	Port	1943	1945	-	Aug	Sat>=25	22:00s	1:00	S
Rule	Port	1944	1945	-	Apr	Sat>=21	22:00s	2:00	M
Rule	Port	1946	only	-	Apr	Sat>=1	23:00s	1:00	S
Rule	Port	1946	only	-	Oct	Sat>=1	23:00s	0	-
Rule	Port	1947	1949	-	Apr	Sun>=1	 2:00s	1:00	S
Rule	Port	1947	1949	-	Oct	Sun>=1	 2:00s	0	-
# Shanks & Pottenger say DST was observed in 1950; go with Whitman.
# Whitman gives Oct lastSun for 1952 on; go with Shanks & Pottenger.
Rule	Port	1951	1965	-	Apr	Sun>=1	 2:00s	1:00	S
Rule	Port	1951	1965	-	Oct	Sun>=1	 2:00s	0	-
Rule	Port	1977	only	-	Mar	27	 0:00s	1:00	S
Rule	Port	1977	only	-	Sep	25	 0:00s	0	-
Rule	Port	1978	1979	-	Apr	Sun>=1	 0:00s	1:00	S
Rule	Port	1978	only	-	Oct	 1	 0:00s	0	-
Rule	Port	1979	1982	-	Sep	lastSun	 1:00s	0	-
Rule	Port	1980	only	-	Mar	lastSun	 0:00s	1:00	S
Rule	Port	1981	1982	-	Mar	lastSun	 1:00s	1:00	S
Rule	Port	1983	only	-	Mar	lastSun	 2:00s	1:00	S
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# Shanks & Pottenger say the transition from LMT to WET occurred 1911-05-24;
# Willett says 1912-01-01.  Go with Willett.
Zone	Europe/Lisbon	-0:36:32 -	LMT	1884
			-0:36:32 -	LMT	1912 Jan  1  # Lisbon Mean Time
			 0:00	Port	WE%sT	1966 Apr  3 2:00
			 1:00	-	CET	1976 Sep 26 1:00
			 0:00	Port	WE%sT	1983 Sep 25 1:00s
			 0:00	W-Eur	WE%sT	1992 Sep 27 1:00s
			 1:00	EU	CE%sT	1996 Mar 31 1:00u
			 0:00	EU	WE%sT
Zone Atlantic/Azores	-1:42:40 -	LMT	1884		# Ponta Delgada
			-1:54:32 -	HMT	1911 May 24  # Horta Mean Time
			-2:00	Port	AZO%sT	1966 Apr  3 2:00 # Azores Time
			-1:00	Port	AZO%sT	1983 Sep 25 1:00s
			-1:00	W-Eur	AZO%sT	1992 Sep 27 1:00s
			 0:00	EU	WE%sT	1993 Mar 28 1:00u
			-1:00	EU	AZO%sT
Zone Atlantic/Madeira	-1:07:36 -	LMT	1884		# Funchal
			-1:07:36 -	FMT	1911 May 24  # Funchal Mean Time
			-1:00	Port	MAD%sT	1966 Apr  3 2:00 # Madeira Time
			 0:00	Port	WE%sT	1983 Sep 25 1:00s
			 0:00	EU	WE%sT

# Romania
#
# From Paul Eggert (1999-10-07):
# 
# Nine O'clock (1998-10-23) reports that the switch occurred at
# 04:00 local time in fall 1998.  For lack of better info,
# assume that Romania and Moldova switched to EU rules in 1997,
# the same year as Bulgaria.
#
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Romania	1932	only	-	May	21	 0:00s	1:00	S
Rule	Romania	1932	1939	-	Oct	Sun>=1	 0:00s	0	-
Rule	Romania	1933	1939	-	Apr	Sun>=2	 0:00s	1:00	S
Rule	Romania	1979	only	-	May	27	 0:00	1:00	S
Rule	Romania	1979	only	-	Sep	lastSun	 0:00	0	-
Rule	Romania	1980	only	-	Apr	 5	23:00	1:00	S
Rule	Romania	1980	only	-	Sep	lastSun	 1:00	0	-
Rule	Romania	1991	1993	-	Mar	lastSun	 0:00s	1:00	S
Rule	Romania	1991	1993	-	Sep	lastSun	 0:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Europe/Bucharest	1:44:24 -	LMT	1891 Oct
			1:44:24	-	BMT	1931 Jul 24	# Bucharest MT
			2:00	Romania	EE%sT	1981 Mar 29 2:00s
			2:00	C-Eur	EE%sT	1991
			2:00	Romania	EE%sT	1994
			2:00	E-Eur	EE%sT	1997
			2:00	EU	EE%sT

# Russia

# From Alexander Krivenyshev (2011-09-15):
# Based on last Russian Government Decree # 725 on August 31, 2011
# (Government document
# 
# http://www.government.ru/gov/results/16355/print/
# 
# in Russian)
# there are few corrections have to be made for some Russian time zones...
# All updated Russian Time Zones were placed in table and translated to English
# by WorldTimeZone.com at the link below:
# 
# http://www.worldtimezone.com/dst_news/dst_news_russia36.htm
# 

# From Sanjeev Gupta (2011-09-27):
# Scans of [Decree #23 of January 8, 1992] are available at:
# 
# http://government.consultant.ru/page.aspx?1223966
# They are in Cyrillic letters (presumably Russian).

# From Arthur David Olson (2012-05-09):
# Regarding the instant when clocks in time-zone-shifting parts of Russia
# changed in September 2011:
#
# One source is
# < a href="http://government.ru/gov/results/16355/>
# http://government.ru/gov/results/16355/
# 
# which, according to translate.google.com, begins "Decree of August 31,
# 2011 No 725" and contains no other dates or "effective date" information.
#
# Another source is
# 
# http://www.rg.ru/2011/09/06/chas-zona-dok.html
# 
# which, according to translate.google.com, begins "Resolution of the
# Government of the Russian Federation on August 31, 2011 N 725" and also
# contains "Date first official publication: September 6, 2011 Posted on:
# in the 'RG' - Federal Issue number 5573 September 6, 2011" but which
# does not contain any "effective date" information.
#
# Another source is
# 
# http://en.wikipedia.org/wiki/Oymyakonsky_District#cite_note-RuTime-7
# 
# which, in note 8, contains "Resolution #725 of August 31, 2011...
# Effective as of after 7 days following the day of the official publication"
# but which does not contain any reference to September 6, 2011.
#
# The Wikipedia article refers to
# 
# http://base.consultant.ru/cons/cgi/online.cgi?req=doc;base=LAW;n=118896
# 
# which seems to copy the text of the government.ru page.
#
# Tobias Conradi combines Wikipedia's
# "as of after 7 days following the day of the official publication"
# with www.rg.ru's "Date of first official publication: September 6, 2011" to get
# September 13, 2011 as the cutover date (unusually, a Tuesday, as Tobias Conradi notes).
#
# None of the sources indicates a time of day for changing clocks.
#
# Go with 2011-09-13 0:00s.

# From Paul Eggert (2006-03-22):
# Except for Moscow after 1919-07-01, I invented the time zone abbreviations.
# Moscow time zone abbreviations after 1919-07-01, and Moscow rules after 1991,
# are from Andrey A. Chernov.  The rest is from Shanks & Pottenger,
# except we follow Chernov's report that 1992 DST transitions were Sat
# 23:00, not Sun 02:00s.
#
# From Stanislaw A. Kuzikowski (1994-06-29):
# But now it is some months since Novosibirsk is 3 hours ahead of Moscow!
# I do not know why they have decided to make this change;
# as far as I remember it was done exactly during winter->summer switching
# so we (Novosibirsk) simply did not switch.
#
# From Andrey A. Chernov (1996-10-04):
# `MSK' and `MSD' were born and used initially on Moscow computers with
# UNIX-like OSes by several developer groups (e.g. Demos group, Kiae group)....
# The next step was the UUCP network, the Relcom predecessor
# (used mainly for mail), and MSK/MSD was actively used there.
#
# From Chris Carrier (1996-10-30):
# According to a friend of mine who rode the Trans-Siberian Railroad from
# Moscow to Irkutsk in 1995, public air and rail transport in Russia ...
# still follows Moscow time, no matter where in Russia it is located.
#
# For Grozny, Chechnya, we have the following story from
# John Daniszewski, "Scavengers in the Rubble", Los Angeles Times (2001-02-07):
# News--often false--is spread by word of mouth.  A rumor that it was
# time to move the clocks back put this whole city out of sync with
# the rest of Russia for two weeks--even soldiers stationed here began
# enforcing curfew at the wrong time.
#
# From Gwillim Law (2001-06-05):
# There's considerable evidence that Sakhalin Island used to be in
# UTC+11, and has changed to UTC+10, in this decade.  I start with the
# SSIM, which listed Yuzhno-Sakhalinsk in zone RU10 along with Magadan
# until February 1997, and then in RU9 with Khabarovsk and Vladivostok
# since September 1997....  Although the Kuril Islands are
# administratively part of Sakhalin oblast', they appear to have
# remained on UTC+11 along with Magadan.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
#
# Kaliningradskaya oblast'.
Zone Europe/Kaliningrad	 1:22:00 -	LMT	1893 Apr
			 1:00	C-Eur	CE%sT	1945
			 2:00	Poland	CE%sT	1946
			 3:00	Russia	MSK/MSD	1991 Mar 31 2:00s
			 2:00	Russia	EE%sT	2011 Mar 27 2:00s
			 3:00	-	FET # Further-eastern European Time
#
# From Oscar van Vlijmen (2001-08-25): [This region consists of]
# Respublika Adygeya, Arkhangel'skaya oblast',
# Belgorodskaya oblast', Bryanskaya oblast', Vladimirskaya oblast',
# Vologodskaya oblast', Voronezhskaya oblast',
# Respublika Dagestan, Ivanovskaya oblast', Respublika Ingushetiya,
# Kabarbino-Balkarskaya Respublika, Respublika Kalmykiya,
# Kalyzhskaya oblast', Respublika Karachaevo-Cherkessiya,
# Respublika Kareliya, Respublika Komi,
# Kostromskaya oblast', Krasnodarskij kraj, Kurskaya oblast',
# Leningradskaya oblast', Lipetskaya oblast', Respublika Marij El,
# Respublika Mordoviya, Moskva, Moskovskaya oblast',
# Murmanskaya oblast', Nenetskij avtonomnyj okrug,
# Nizhegorodskaya oblast', Novgorodskaya oblast', Orlovskaya oblast',
# Penzenskaya oblast', Pskovskaya oblast', Rostovskaya oblast',
# Ryazanskaya oblast', Sankt-Peterburg,
# Respublika Severnaya Osetiya, Smolenskaya oblast',
# Stavropol'skij kraj, Tambovskaya oblast', Respublika Tatarstan,
# Tverskaya oblast', Tyl'skaya oblast', Ul'yanovskaya oblast',
# Chechenskaya Respublika, Chuvashskaya oblast',
# Yaroslavskaya oblast'
Zone Europe/Moscow	 2:30:20 -	LMT	1880
			 2:30	-	MMT	1916 Jul  3 # Moscow Mean Time
			 2:30:48 Russia	%s	1919 Jul  1 2:00
			 3:00	Russia	MSK/MSD	1922 Oct
			 2:00	-	EET	1930 Jun 21
			 3:00	Russia	MSK/MSD	1991 Mar 31 2:00s
			 2:00	Russia	EE%sT	1992 Jan 19 2:00s
			 3:00	Russia	MSK/MSD	2011 Mar 27 2:00s
			 4:00	-	MSK
#
# Astrakhanskaya oblast', Kirovskaya oblast', Saratovskaya oblast',
# Volgogradskaya oblast'.  Shanks & Pottenger say Kirov is still at +0400
# but Wikipedia (2006-05-09) says +0300.  Perhaps it switched after the
# others?  But we have no data.
Zone Europe/Volgograd	 2:57:40 -	LMT	1920 Jan  3
			 3:00	-	TSAT	1925 Apr  6 # Tsaritsyn Time
			 3:00	-	STAT	1930 Jun 21 # Stalingrad Time
			 4:00	-	STAT	1961 Nov 11
			 4:00	Russia	VOL%sT	1989 Mar 26 2:00s # Volgograd T
			 3:00	Russia	VOL%sT	1991 Mar 31 2:00s
			 4:00	-	VOLT	1992 Mar 29 2:00s
			 3:00	Russia	VOL%sT	2011 Mar 27 2:00s
			 4:00	-	VOLT
#
# From Oscar van Vlijmen (2001-08-25): [This region consists of]
# Samarskaya oblast', Udmyrtskaya respublika
Zone Europe/Samara	 3:20:36 -	LMT	1919 Jul  1 2:00
			 3:00	-	SAMT	1930 Jun 21
			 4:00	-	SAMT	1935 Jan 27
			 4:00	Russia	KUY%sT	1989 Mar 26 2:00s # Kuybyshev
			 3:00	Russia	KUY%sT	1991 Mar 31 2:00s
			 2:00	Russia	KUY%sT	1991 Sep 29 2:00s
			 3:00	-	KUYT	1991 Oct 20 3:00
			 4:00	Russia	SAM%sT	2010 Mar 28 2:00s # Samara Time
			 3:00	Russia	SAM%sT	2011 Mar 27 2:00s
			 4:00	-	SAMT

#
# From Oscar van Vlijmen (2001-08-25): [This region consists of]
# Respublika Bashkortostan, Komi-Permyatskij avtonomnyj okrug,
# Kurganskaya oblast', Orenburgskaya oblast', Permskaya oblast',
# Sverdlovskaya oblast', Tyumenskaya oblast',
# Khanty-Manskijskij avtonomnyj okrug, Chelyabinskaya oblast',
# Yamalo-Nenetskij avtonomnyj okrug.
Zone Asia/Yekaterinburg	 4:02:24 -	LMT	1919 Jul 15 4:00
			 4:00	-	SVET	1930 Jun 21 # Sverdlovsk Time
			 5:00	Russia	SVE%sT	1991 Mar 31 2:00s
			 4:00	Russia	SVE%sT	1992 Jan 19 2:00s
			 5:00	Russia	YEK%sT	2011 Mar 27 2:00s
			 6:00	-	YEKT	# Yekaterinburg Time
#
# From Oscar van Vlijmen (2001-08-25): [This region consists of]
# Respublika Altaj, Altajskij kraj, Omskaya oblast'.
Zone Asia/Omsk		 4:53:36 -	LMT	1919 Nov 14
			 5:00	-	OMST	1930 Jun 21 # Omsk TIme
			 6:00	Russia	OMS%sT	1991 Mar 31 2:00s
			 5:00	Russia	OMS%sT	1992 Jan 19 2:00s
			 6:00	Russia	OMS%sT	2011 Mar 27 2:00s
			 7:00	-	OMST
#
# From Paul Eggert (2006-08-19): I'm guessing about Tomsk here; it's
# not clear when it switched from +7 to +6.
# Novosibirskaya oblast', Tomskaya oblast'.
Zone Asia/Novosibirsk	 5:31:40 -	LMT	1919 Dec 14 6:00
			 6:00	-	NOVT	1930 Jun 21 # Novosibirsk Time
			 7:00	Russia	NOV%sT	1991 Mar 31 2:00s
			 6:00	Russia	NOV%sT	1992 Jan 19 2:00s
			 7:00	Russia	NOV%sT	1993 May 23 # say Shanks & P.
			 6:00	Russia	NOV%sT	2011 Mar 27 2:00s
			 7:00	-	NOVT

# From Alexander Krivenyshev (2009-10-13):
# Kemerovo oblast' (Kemerovo region) in Russia will change current time zone on
# March 28, 2010:
# from current Russia Zone 6 - Krasnoyarsk Time Zone (KRA) UTC +0700
# to Russia Zone 5 - Novosibirsk Time Zone (NOV) UTC +0600
#
# This is according to Government of Russia decree # 740, on September
# 14, 2009 "Application in the territory of the Kemerovo region the Fifth
# time zone." ("Russia Zone 5" or old "USSR Zone 5" is GMT +0600)
#
# Russian Government web site (Russian language)
# 
# http://www.government.ru/content/governmentactivity/rfgovernmentdecisions/archive/2009/09/14/991633.htm
# 
# or Russian-English translation by WorldTimeZone.com with reference
# map to local region and new Russia Time Zone map after March 28, 2010
# 
# http://www.worldtimezone.com/dst_news/dst_news_russia03.html
# 
#
# Thus, when Russia will switch to DST on the night of March 28, 2010
# Kemerovo region (Kemerovo oblast') will not change the clock.
#
# As a result, Kemerovo oblast' will be in the same time zone as
# Novosibirsk, Omsk, Tomsk, Barnaul and Altai Republic.

Zone Asia/Novokuznetsk	 5:48:48 -	NMT	1920 Jan  6
			 6:00	-	KRAT	1930 Jun 21 # Krasnoyarsk Time
			 7:00	Russia	KRA%sT	1991 Mar 31 2:00s
			 6:00	Russia	KRA%sT	1992 Jan 19 2:00s
			 7:00	Russia	KRA%sT	2010 Mar 28 2:00s
			 6:00	Russia	NOV%sT	2011 Mar 27 2:00s
			 7:00	-	NOVT # Novosibirsk/Novokuznetsk Time

#
# From Oscar van Vlijmen (2001-08-25): [This region consists of]
# Krasnoyarskij kraj,
# Tajmyrskij (Dolgano-Nenetskij) avtonomnyj okrug,
# Respublika Tuva, Respublika Khakasiya, Evenkijskij avtonomnyj okrug.
Zone Asia/Krasnoyarsk	 6:11:20 -	LMT	1920 Jan  6
			 6:00	-	KRAT	1930 Jun 21 # Krasnoyarsk Time
			 7:00	Russia	KRA%sT	1991 Mar 31 2:00s
			 6:00	Russia	KRA%sT	1992 Jan 19 2:00s
			 7:00	Russia	KRA%sT	2011 Mar 27 2:00s
			 8:00	-	KRAT
#
# From Oscar van Vlijmen (2001-08-25): [This region consists of]
# Respublika Buryatiya, Irkutskaya oblast',
# Ust'-Ordynskij Buryatskij avtonomnyj okrug.
Zone Asia/Irkutsk	 6:57:20 -	LMT	1880
			 6:57:20 -	IMT	1920 Jan 25 # Irkutsk Mean Time
			 7:00	-	IRKT	1930 Jun 21 # Irkutsk Time
			 8:00	Russia	IRK%sT	1991 Mar 31 2:00s
			 7:00	Russia	IRK%sT	1992 Jan 19 2:00s
			 8:00	Russia	IRK%sT	2011 Mar 27 2:00s
			 9:00	-	IRKT
#
# From Oscar van Vlijmen (2003-10-18): [This region consists of]
# Aginskij Buryatskij avtonomnyj okrug, Amurskaya oblast',
# [parts of] Respublika Sakha (Yakutiya), Chitinskaya oblast'.

# From Oscar van Vlijmen (2009-11-29):
# ...some regions of [Russia] were merged with others since 2005...
# Some names were changed, no big deal, except for one instance: a new name.
# YAK/YAKST: UTC+9 Zabajkal'skij kraj.

# From Oscar van Vlijmen (2009-11-29):
# The Sakha districts are: Aldanskij, Amginskij, Anabarskij,
# Verkhnevilyujskij, Vilyujskij, Gornyj,
# Zhiganskij, Kobyajskij, Lenskij, Megino-Kangalasskij, Mirninskij,
# Namskij, Nyurbinskij, Olenyokskij, Olyokminskij,
# Suntarskij, Tattinskij, Ust'-Aldanskij, Khangalasskij,
# Churapchinskij, Eveno-Bytantajskij Natsional'nij.

Zone Asia/Yakutsk	 8:38:40 -	LMT	1919 Dec 15
			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
			 9:00	Russia	YAK%sT	1991 Mar 31 2:00s
			 8:00	Russia	YAK%sT	1992 Jan 19 2:00s
			 9:00	Russia	YAK%sT	2011 Mar 27 2:00s
			 10:00	-	YAKT
#
# From Oscar van Vlijmen (2003-10-18): [This region consists of]
# Evrejskaya avtonomnaya oblast', Khabarovskij kraj, Primorskij kraj,
# [parts of] Respublika Sakha (Yakutiya).

# From Oscar van Vlijmen (2009-11-29):
# The Sakha districts are: Bulunskij, Verkhoyanskij, ... Ust'-Yanskij.
Zone Asia/Vladivostok	 8:47:44 -	LMT	1922 Nov 15
			 9:00	-	VLAT	1930 Jun 21 # Vladivostok Time
			10:00	Russia	VLA%sT	1991 Mar 31 2:00s
			 9:00	Russia	VLA%sST	1992 Jan 19 2:00s
			10:00	Russia	VLA%sT	2011 Mar 27 2:00s
			11:00	-	VLAT

# From Arthur David Olson (2012-05-09):
# Tomponskij and Ust'-Majskij switched from Vladivostok time to Yakutsk time
# in 2011.
#
# From Paul Eggert (2012-11-25):
# Shanks and Pottenger (2003) has Khandyga on Yakutsk time.
# Make a wild guess that it switched to Vladivostok time in 2004.
# This transition is no doubt wrong, but we have no better info.
#
Zone Asia/Khandyga	 9:02:13 -	LMT	1919 Dec 15
			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
			 9:00	Russia	YAK%sT	1991 Mar 31 2:00s
			 8:00	Russia	YAK%sT	1992 Jan 19 2:00s
			 9:00	Russia	YAK%sT	2004
			10:00	Russia	VLA%sT	2011 Mar 27 2:00s
			11:00	-	VLAT	2011 Sep 13 0:00s # Decree 725?
			10:00	-	YAKT

#
# Sakhalinskaya oblast'.
# The Zone name should be Yuzhno-Sakhalinsk, but that's too long.
Zone Asia/Sakhalin	 9:30:48 -	LMT	1905 Aug 23
			 9:00	-	CJT	1938
			 9:00	-	JST	1945 Aug 25
			11:00	Russia	SAK%sT	1991 Mar 31 2:00s # Sakhalin T.
			10:00	Russia	SAK%sT	1992 Jan 19 2:00s
			11:00	Russia	SAK%sT	1997 Mar lastSun 2:00s
			10:00	Russia	SAK%sT	2011 Mar 27 2:00s
			11:00	-	SAKT
#
# From Oscar van Vlijmen (2003-10-18): [This region consists of]
# Magadanskaya oblast', Respublika Sakha (Yakutiya).
# Probably also: Kuril Islands.

# From Oscar van Vlijmen (2009-11-29):
# The Sakha districts are: Abyjskij, Allaikhovskij, Verkhhhnekolymskij, Momskij,
# Nizhnekolymskij, ... Srednekolymskij.
Zone Asia/Magadan	10:03:12 -	LMT	1924 May  2
			10:00	-	MAGT	1930 Jun 21 # Magadan Time
			11:00	Russia	MAG%sT	1991 Mar 31 2:00s
			10:00	Russia	MAG%sT	1992 Jan 19 2:00s
			11:00	Russia	MAG%sT	2011 Mar 27 2:00s
			12:00	-	MAGT

# From Arthur David Olson (2012-05-09):
# Ojmyakonskij and the Kuril Islands switched from
# Magadan time to Vladivostok time in 2011.
Zone Asia/Ust-Nera	 9:32:54 -	LMT	1919 Dec 15
			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
			 9:00	Russia	YAKT	1981 Apr  1
			11:00	Russia	MAG%sT	1991 Mar 31 2:00s
			10:00	Russia	MAG%sT	1992 Jan 19 2:00s
			11:00	Russia	MAG%sT	2011 Mar 27 2:00s
			12:00	-	MAGT	2011 Sep 13 0:00s # Decree 725?
			11:00	-	VLAT

# From Oscar van Vlijmen (2001-08-25): [This region consists of]
# Kamchatskaya oblast', Koryakskij avtonomnyj okrug.
#
# The Zone name should be Asia/Petropavlovsk-Kamchatski, but that's too long.
Zone Asia/Kamchatka	10:34:36 -	LMT	1922 Nov 10
			11:00	-	PETT	1930 Jun 21 # P-K Time
			12:00	Russia	PET%sT	1991 Mar 31 2:00s
			11:00	Russia	PET%sT	1992 Jan 19 2:00s
			12:00	Russia	PET%sT	2010 Mar 28 2:00s
			11:00	Russia	PET%sT	2011 Mar 27 2:00s
			12:00	-	PETT
#
# Chukotskij avtonomnyj okrug
Zone Asia/Anadyr	11:49:56 -	LMT	1924 May  2
			12:00	-	ANAT	1930 Jun 21 # Anadyr Time
			13:00	Russia	ANA%sT	1982 Apr  1 0:00s
			12:00	Russia	ANA%sT	1991 Mar 31 2:00s
			11:00	Russia	ANA%sT	1992 Jan 19 2:00s
			12:00	Russia	ANA%sT	2010 Mar 28 2:00s
			11:00	Russia	ANA%sT	2011 Mar 27 2:00s
			12:00	-	ANAT

# Serbia
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Belgrade	1:22:00	-	LMT	1884
			1:00	-	CET	1941 Apr 18 23:00
			1:00	C-Eur	CE%sT	1945
			1:00	-	CET	1945 May 8 2:00s
			1:00	1:00	CEST	1945 Sep 16  2:00s
# Metod Kozelj reports that the legal date of
# transition to EU rules was 1982-11-27, for all of Yugoslavia at the time.
# Shanks & Pottenger don't give as much detail, so go with Kozelj.
			1:00	-	CET	1982 Nov 27
			1:00	EU	CE%sT
Link Europe/Belgrade Europe/Ljubljana	# Slovenia
Link Europe/Belgrade Europe/Podgorica	# Montenegro
Link Europe/Belgrade Europe/Sarajevo	# Bosnia and Herzegovina
Link Europe/Belgrade Europe/Skopje	# Macedonia
Link Europe/Belgrade Europe/Zagreb	# Croatia

# Slovakia
Link Europe/Prague Europe/Bratislava

# Slovenia
# see Serbia

# Spain
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# For 1917-1919 Whitman gives Apr Sat>=1 - Oct Sat>=1;
# go with Shanks & Pottenger.
Rule	Spain	1917	only	-	May	 5	23:00s	1:00	S
Rule	Spain	1917	1919	-	Oct	 6	23:00s	0	-
Rule	Spain	1918	only	-	Apr	15	23:00s	1:00	S
Rule	Spain	1919	only	-	Apr	 5	23:00s	1:00	S
# Whitman gives 1921 Feb 28 - Oct 14; go with Shanks & Pottenger.
Rule	Spain	1924	only	-	Apr	16	23:00s	1:00	S
# Whitman gives 1924 Oct 14; go with Shanks & Pottenger.
Rule	Spain	1924	only	-	Oct	 4	23:00s	0	-
Rule	Spain	1926	only	-	Apr	17	23:00s	1:00	S
# Whitman says no DST in 1929; go with Shanks & Pottenger.
Rule	Spain	1926	1929	-	Oct	Sat>=1	23:00s	0	-
Rule	Spain	1927	only	-	Apr	 9	23:00s	1:00	S
Rule	Spain	1928	only	-	Apr	14	23:00s	1:00	S
Rule	Spain	1929	only	-	Apr	20	23:00s	1:00	S
# Whitman gives 1937 Jun 16, 1938 Apr 16, 1940 Apr 13;
# go with Shanks & Pottenger.
Rule	Spain	1937	only	-	May	22	23:00s	1:00	S
Rule	Spain	1937	1939	-	Oct	Sat>=1	23:00s	0	-
Rule	Spain	1938	only	-	Mar	22	23:00s	1:00	S
Rule	Spain	1939	only	-	Apr	15	23:00s	1:00	S
Rule	Spain	1940	only	-	Mar	16	23:00s	1:00	S
# Whitman says no DST 1942-1945; go with Shanks & Pottenger.
Rule	Spain	1942	only	-	May	 2	22:00s	2:00	M # Midsummer
Rule	Spain	1942	only	-	Sep	 1	22:00s	1:00	S
Rule	Spain	1943	1946	-	Apr	Sat>=13	22:00s	2:00	M
Rule	Spain	1943	only	-	Oct	 3	22:00s	1:00	S
Rule	Spain	1944	only	-	Oct	10	22:00s	1:00	S
Rule	Spain	1945	only	-	Sep	30	 1:00	1:00	S
Rule	Spain	1946	only	-	Sep	30	 0:00	0	-
Rule	Spain	1949	only	-	Apr	30	23:00	1:00	S
Rule	Spain	1949	only	-	Sep	30	 1:00	0	-
Rule	Spain	1974	1975	-	Apr	Sat>=13	23:00	1:00	S
Rule	Spain	1974	1975	-	Oct	Sun>=1	 1:00	0	-
Rule	Spain	1976	only	-	Mar	27	23:00	1:00	S
Rule	Spain	1976	1977	-	Sep	lastSun	 1:00	0	-
Rule	Spain	1977	1978	-	Apr	 2	23:00	1:00	S
Rule	Spain	1978	only	-	Oct	 1	 1:00	0	-
# The following rules are copied from Morocco from 1967 through 1978.
Rule SpainAfrica 1967	only	-	Jun	 3	12:00	1:00	S
Rule SpainAfrica 1967	only	-	Oct	 1	 0:00	0	-
Rule SpainAfrica 1974	only	-	Jun	24	 0:00	1:00	S
Rule SpainAfrica 1974	only	-	Sep	 1	 0:00	0	-
Rule SpainAfrica 1976	1977	-	May	 1	 0:00	1:00	S
Rule SpainAfrica 1976	only	-	Aug	 1	 0:00	0	-
Rule SpainAfrica 1977	only	-	Sep	28	 0:00	0	-
Rule SpainAfrica 1978	only	-	Jun	 1	 0:00	1:00	S
Rule SpainAfrica 1978	only	-	Aug	 4	 0:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Madrid	-0:14:44 -	LMT	1901 Jan  1  0:00s
			 0:00	Spain	WE%sT	1946 Sep 30
			 1:00	Spain	CE%sT	1979
			 1:00	EU	CE%sT
Zone	Africa/Ceuta	-0:21:16 -	LMT	1901
			 0:00	-	WET	1918 May  6 23:00
			 0:00	1:00	WEST	1918 Oct  7 23:00
			 0:00	-	WET	1924
			 0:00	Spain	WE%sT	1929
			 0:00 SpainAfrica WE%sT 1984 Mar 16
			 1:00	-	CET	1986
			 1:00	EU	CE%sT
Zone	Atlantic/Canary	-1:01:36 -	LMT	1922 Mar # Las Palmas de Gran C.
			-1:00	-	CANT	1946 Sep 30 1:00 # Canaries Time
			 0:00	-	WET	1980 Apr  6 0:00s
			 0:00	1:00	WEST	1980 Sep 28 0:00s
			 0:00	EU	WE%sT
# IATA SSIM (1996-09) says the Canaries switch at 2:00u, not 1:00u.
# Ignore this for now, as the Canaries are part of the EU.

# Sweden

# From Ivan Nilsson (2001-04-13), superseding Shanks & Pottenger:
#
# The law "Svensk forfattningssamling 1878, no 14" about standard time in 1879:
# From the beginning of 1879 (that is 01-01 00:00) the time for all
# places in the country is "the mean solar time for the meridian at
# three degrees, or twelve minutes of time, to the west of the
# meridian of the Observatory of Stockholm".  The law is dated 1878-05-31.
#
# The observatory at that time had the meridian 18 degrees 03' 30"
# eastern longitude = 01:12:14 in time.  Less 12 minutes gives the
# national standard time as 01:00:14 ahead of GMT....
#
# About the beginning of CET in Sweden. The lawtext ("Svensk
# forfattningssamling 1899, no 44") states, that "from the beginning
# of 1900... ... the same as the mean solar time for the meridian at
# the distance of one hour of time from the meridian of the English
# observatory at Greenwich, or at 12 minutes 14 seconds to the west
# from the meridian of the Observatory of Stockholm". The law is dated
# 1899-06-16.  In short: At 1900-01-01 00:00:00 the new standard time
# in Sweden is 01:00:00 ahead of GMT.
#
# 1916: The lawtext ("Svensk forfattningssamling 1916, no 124") states
# that "1916-05-15 is considered to begin one hour earlier". It is
# pretty obvious that at 05-14 23:00 the clocks are set to 05-15 00:00....
# Further the law says, that "1916-09-30 is considered to end one hour later".
#
# The laws regulating [DST] are available on the site of the Swedish
# Parliament beginning with 1985 - the laws regulating 1980/1984 are
# not available on the site (to my knowledge they are only available
# in Swedish):  (type
# "sommartid" without the quotes in the field "Fritext" and then click
# the Sok-button).
#
# (2001-05-13):
#
# I have now found a newspaper stating that at 1916-10-01 01:00
# summertime the church-clocks etc were set back one hour to show
# 1916-10-01 00:00 standard time.  The article also reports that some
# people thought the switch to standard time would take place already
# at 1916-10-01 00:00 summer time, but they had to wait for another
# hour before the event took place.
#
# Source: The newspaper "Dagens Nyheter", 1916-10-01, page 7 upper left.

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Europe/Stockholm	1:12:12 -	LMT	1879 Jan  1
			1:00:14	-	SET	1900 Jan  1	# Swedish Time
			1:00	-	CET	1916 May 14 23:00
			1:00	1:00	CEST	1916 Oct  1 01:00
			1:00	-	CET	1980
			1:00	EU	CE%sT

# Switzerland
# From Howse:
# By the end of the 18th century clocks and watches became commonplace
# and their performance improved enormously.  Communities began to keep
# mean time in preference to apparent time -- Geneva from 1780 ....
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
# From Whitman (who writes ``Midnight?''):
# Rule	Swiss	1940	only	-	Nov	 2	0:00	1:00	S
# Rule	Swiss	1940	only	-	Dec	31	0:00	0	-
# From Shanks & Pottenger:
# Rule	Swiss	1941	1942	-	May	Sun>=1	2:00	1:00	S
# Rule	Swiss	1941	1942	-	Oct	Sun>=1	0:00	0	-

# From Alois Treindl (2008-12-17):
# I have researched the DST usage in Switzerland during the 1940ies.
#
# As I wrote in an earlier message, I suspected the current tzdata values
# to be wrong. This is now verified.
#
# I have found copies of the original ruling by the Swiss Federal
# government, in 'Eidgen[o]ssische Gesetzessammlung 1941 and 1942' (Swiss
# federal law collection)...
#
# DST began on Monday 5 May 1941, 1:00 am by shifting the clocks to 2:00 am
# DST ended on Monday 6 Oct 1941, 2:00 am by shifting the clocks to 1:00 am.
#
# DST began on Monday, 4 May 1942 at 01:00 am
# DST ended on Monday, 5 Oct 1942 at 02:00 am
#
# There was no DST in 1940, I have checked the law collection carefully.
# It is also indicated by the fact that the 1942 entry in the law
# collection points back to 1941 as a reference, but no reference to any
# other years are made.
#
# Newspaper articles I have read in the archives on 6 May 1941 reported
# about the introduction of DST (Sommerzeit in German) during the previous
# night as an absolute novelty, because this was the first time that such
# a thing had happened in Switzerland.
#
# I have also checked 1916, because one book source (Gabriel, Traite de
# l'heure dans le monde) claims that Switzerland had DST in 1916. This is
# false, no official document could be found. Probably Gabriel got misled
# by references to Germany, which introduced DST in 1916 for the first time.
#
# The tzdata rules for Switzerland must be changed to:
# Rule  Swiss   1941    1942    -       May     Mon>=1  1:00    1:00    S
# Rule  Swiss   1941    1942    -       Oct     Mon>=1  2:00    0       -
#
# The 1940 rules must be deleted.
#
# One further detail for Switzerland, which is probably out of scope for
# most users of tzdata:
# The zone file
# Zone    Europe/Zurich   0:34:08 -       LMT     1848 Sep 12
#                          0:29:44 -       BMT     1894 Jun #Bern Mean Time
#                          1:00    Swiss   CE%sT   1981
#                          1:00    EU      CE%sT
# describes all of Switzerland correctly, with the exception of
# the Cantone Geneve (Geneva, Genf). Between 1848 and 1894 Geneve did not
# follow Bern Mean Time but kept its own local mean time.
# To represent this, an extra zone would be needed.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Swiss	1941	1942	-	May	Mon>=1	1:00	1:00	S
Rule	Swiss	1941	1942	-	Oct	Mon>=1	2:00	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Zurich	0:34:08 -	LMT	1848 Sep 12
			0:29:44	-	BMT	1894 Jun # Bern Mean Time
			1:00	Swiss	CE%sT	1981
			1:00	EU	CE%sT

# Turkey

# From Amar Devegowda (2007-01-03):
# The time zone rules for Istanbul, Turkey have not been changed for years now.
# ... The latest rules are available at -
# http://www.timeanddate.com/worldclock/timezone.html?n=107
# From Steffen Thorsen (2007-01-03):
# I have been able to find press records back to 1996 which all say that
# DST started 01:00 local time and end at 02:00 local time.  I am not sure
# what happened before that.  One example for each year from 1996 to 2001:
# http://newspot.byegm.gov.tr/arsiv/1996/21/N4.htm
# http://www.byegm.gov.tr/YAYINLARIMIZ/CHR/ING97/03/97X03X25.TXT
# http://www.byegm.gov.tr/YAYINLARIMIZ/CHR/ING98/03/98X03X02.HTM
# http://www.byegm.gov.tr/YAYINLARIMIZ/CHR/ING99/10/99X10X26.HTM#%2016
# http://www.byegm.gov.tr/YAYINLARIMIZ/CHR/ING2000/03/00X03X06.HTM#%2021
# http://www.byegm.gov.tr/YAYINLARIMIZ/CHR/ING2001/03/23x03x01.HTM#%2027
# From Paul Eggert (2007-01-03):
# Prefer the above source to Shanks & Pottenger for time stamps after 1990.

# From Steffen Thorsen (2007-03-09):
# Starting 2007 though, it seems that they are adopting EU's 1:00 UTC
# start/end time, according to the following page (2007-03-07):
# http://www.ntvmsnbc.com/news/402029.asp
# The official document is located here - it is in Turkish...:
# http://rega.basbakanlik.gov.tr/eskiler/2007/03/20070307-7.htm
# I was able to locate the following seemingly official document
# (on a non-government server though) describing dates between 2002 and 2006:
# http://www.alomaliye.com/bkk_2002_3769.htm

# From Gökdeniz Karadağ (2011-03-10):
#
# According to the articles linked below, Turkey will change into summer
# time zone (GMT+3) on March 28, 2011 at 3:00 a.m. instead of March 27.
# This change is due to a nationwide exam on 27th.
#
# 
# http://www.worldbulletin.net/?aType=haber&ArticleID=70872
# 
# Turkish:
# 
# http://www.hurriyet.com.tr/ekonomi/17230464.asp?gid=373
# 

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	Turkey	1916	only	-	May	 1	0:00	1:00	S
Rule	Turkey	1916	only	-	Oct	 1	0:00	0	-
Rule	Turkey	1920	only	-	Mar	28	0:00	1:00	S
Rule	Turkey	1920	only	-	Oct	25	0:00	0	-
Rule	Turkey	1921	only	-	Apr	 3	0:00	1:00	S
Rule	Turkey	1921	only	-	Oct	 3	0:00	0	-
Rule	Turkey	1922	only	-	Mar	26	0:00	1:00	S
Rule	Turkey	1922	only	-	Oct	 8	0:00	0	-
# Whitman gives 1923 Apr 28 - Sep 16 and no DST in 1924-1925;
# go with Shanks & Pottenger.
Rule	Turkey	1924	only	-	May	13	0:00	1:00	S
Rule	Turkey	1924	1925	-	Oct	 1	0:00	0	-
Rule	Turkey	1925	only	-	May	 1	0:00	1:00	S
Rule	Turkey	1940	only	-	Jun	30	0:00	1:00	S
Rule	Turkey	1940	only	-	Oct	 5	0:00	0	-
Rule	Turkey	1940	only	-	Dec	 1	0:00	1:00	S
Rule	Turkey	1941	only	-	Sep	21	0:00	0	-
Rule	Turkey	1942	only	-	Apr	 1	0:00	1:00	S
# Whitman omits the next two transition and gives 1945 Oct 1;
# go with Shanks & Pottenger.
Rule	Turkey	1942	only	-	Nov	 1	0:00	0	-
Rule	Turkey	1945	only	-	Apr	 2	0:00	1:00	S
Rule	Turkey	1945	only	-	Oct	 8	0:00	0	-
Rule	Turkey	1946	only	-	Jun	 1	0:00	1:00	S
Rule	Turkey	1946	only	-	Oct	 1	0:00	0	-
Rule	Turkey	1947	1948	-	Apr	Sun>=16	0:00	1:00	S
Rule	Turkey	1947	1950	-	Oct	Sun>=2	0:00	0	-
Rule	Turkey	1949	only	-	Apr	10	0:00	1:00	S
Rule	Turkey	1950	only	-	Apr	19	0:00	1:00	S
Rule	Turkey	1951	only	-	Apr	22	0:00	1:00	S
Rule	Turkey	1951	only	-	Oct	 8	0:00	0	-
Rule	Turkey	1962	only	-	Jul	15	0:00	1:00	S
Rule	Turkey	1962	only	-	Oct	 8	0:00	0	-
Rule	Turkey	1964	only	-	May	15	0:00	1:00	S
Rule	Turkey	1964	only	-	Oct	 1	0:00	0	-
Rule	Turkey	1970	1972	-	May	Sun>=2	0:00	1:00	S
Rule	Turkey	1970	1972	-	Oct	Sun>=2	0:00	0	-
Rule	Turkey	1973	only	-	Jun	 3	1:00	1:00	S
Rule	Turkey	1973	only	-	Nov	 4	3:00	0	-
Rule	Turkey	1974	only	-	Mar	31	2:00	1:00	S
Rule	Turkey	1974	only	-	Nov	 3	5:00	0	-
Rule	Turkey	1975	only	-	Mar	30	0:00	1:00	S
Rule	Turkey	1975	1976	-	Oct	lastSun	0:00	0	-
Rule	Turkey	1976	only	-	Jun	 1	0:00	1:00	S
Rule	Turkey	1977	1978	-	Apr	Sun>=1	0:00	1:00	S
Rule	Turkey	1977	only	-	Oct	16	0:00	0	-
Rule	Turkey	1979	1980	-	Apr	Sun>=1	3:00	1:00	S
Rule	Turkey	1979	1982	-	Oct	Mon>=11	0:00	0	-
Rule	Turkey	1981	1982	-	Mar	lastSun	3:00	1:00	S
Rule	Turkey	1983	only	-	Jul	31	0:00	1:00	S
Rule	Turkey	1983	only	-	Oct	 2	0:00	0	-
Rule	Turkey	1985	only	-	Apr	20	0:00	1:00	S
Rule	Turkey	1985	only	-	Sep	28	0:00	0	-
Rule	Turkey	1986	1990	-	Mar	lastSun	2:00s	1:00	S
Rule	Turkey	1986	1990	-	Sep	lastSun	2:00s	0	-
Rule	Turkey	1991	2006	-	Mar	lastSun	1:00s	1:00	S
Rule	Turkey	1991	1995	-	Sep	lastSun	1:00s	0	-
Rule	Turkey	1996	2006	-	Oct	lastSun	1:00s	0	-
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone	Europe/Istanbul	1:55:52 -	LMT	1880
			1:56:56	-	IMT	1910 Oct # Istanbul Mean Time?
			2:00	Turkey	EE%sT	1978 Oct 15
			3:00	Turkey	TR%sT	1985 Apr 20 # Turkey Time
			2:00	Turkey	EE%sT	2007
			2:00	EU	EE%sT	2011 Mar 27 1:00u
			2:00	-	EET	2011 Mar 28 1:00u
			2:00	EU	EE%sT
Link	Europe/Istanbul	Asia/Istanbul	# Istanbul is in both continents.

# Ukraine
#
# From Igor Karpov, who works for the Ukrainian Ministry of Justice,
# via Garrett Wollman (2003-01-27):
# BTW, I've found the official document on this matter. It's government
# regulations number 509, May 13, 1996. In my poor translation it says:
# "Time in Ukraine is set to second timezone (Kiev time). Each last Sunday
# of March at 3am the time is changing to 4am and each last Sunday of
# October the time at 4am is changing to 3am"

# From Alexander Krivenyshev (2011-09-20):
# On September 20, 2011 the deputies of the Verkhovna Rada agreed to
# abolish the transfer clock to winter time.
#
# Bill number 8330 of MP from the Party of Regions Oleg Nadoshi got
# approval from 266 deputies.
#
# Ukraine abolishes transter back to the winter time (in Russian)
# 
# http://news.mail.ru/politics/6861560/
# 
#
# The Ukrainians will no longer change the clock (in Russian)
# 
# http://www.segodnya.ua/news/14290482.html
# 
#
# Deputies cancelled the winter time (in Russian)
# 
# http://www.pravda.com.ua/rus/news/2011/09/20/6600616/
# 
#
# From Philip Pizzey (2011-10-18):
# Today my Ukrainian colleagues have informed me that the
# Ukrainian parliament have decided that they will go to winter
# time this year after all.
#
# From Udo Schwedt (2011-10-18):
# As far as I understand, the recent change to the Ukrainian time zone
# (Europe/Kiev) to introduce permanent daylight saving time (similar
# to Russia) was reverted today:
#
# 
# http://portal.rada.gov.ua/rada/control/en/publish/article/info_left?art_id=287324&cat_id=105995
# 
#
# Also reported by Alexander Bokovoy (2011-10-18) who also noted:
# The law documents themselves are at
#
# 
# http://w1.c1.rada.gov.ua/pls/zweb_n/webproc4_1?id=&pf3511=41484
# 


# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
# Most of Ukraine since 1970 has been like Kiev.
# "Kyiv" is the transliteration of the Ukrainian name, but
# "Kiev" is more common in English.
Zone Europe/Kiev	2:02:04 -	LMT	1880
			2:02:04	-	KMT	1924 May  2 # Kiev Mean Time
			2:00	-	EET	1930 Jun 21
			3:00	-	MSK	1941 Sep 20
			1:00	C-Eur	CE%sT	1943 Nov  6
			3:00	Russia	MSK/MSD	1990
			3:00	-	MSK	1990 Jul  1 2:00
			2:00	-	EET	1992
			2:00	E-Eur	EE%sT	1995
			2:00	EU	EE%sT
# Ruthenia used CET 1990/1991.
# "Uzhhorod" is the transliteration of the Ukrainian name, but
# "Uzhgorod" is more common in English.
Zone Europe/Uzhgorod	1:29:12 -	LMT	1890 Oct
			1:00	-	CET	1940
			1:00	C-Eur	CE%sT	1944 Oct
			1:00	1:00	CEST	1944 Oct 26
			1:00	-	CET	1945 Jun 29
			3:00	Russia	MSK/MSD	1990
			3:00	-	MSK	1990 Jul  1 2:00
			1:00	-	CET	1991 Mar 31 3:00
			2:00	-	EET	1992
			2:00	E-Eur	EE%sT	1995
			2:00	EU	EE%sT
# Zaporozh'ye and eastern Lugansk oblasts observed DST 1990/1991.
# "Zaporizhia" is the transliteration of the Ukrainian name, but
# "Zaporozh'ye" is more common in English.  Use the common English
# spelling, except omit the apostrophe as it is not allowed in
# portable Posix file names.
Zone Europe/Zaporozhye	2:20:40 -	LMT	1880
			2:20	-	CUT	1924 May  2 # Central Ukraine T
			2:00	-	EET	1930 Jun 21
			3:00	-	MSK	1941 Aug 25
			1:00	C-Eur	CE%sT	1943 Oct 25
			3:00	Russia	MSK/MSD	1991 Mar 31 2:00
			2:00	E-Eur	EE%sT	1995
			2:00	EU	EE%sT
# Central Crimea used Moscow time 1994/1997.
Zone Europe/Simferopol	2:16:24 -	LMT	1880
			2:16	-	SMT	1924 May  2 # Simferopol Mean T
			2:00	-	EET	1930 Jun 21
			3:00	-	MSK	1941 Nov
			1:00	C-Eur	CE%sT	1944 Apr 13
			3:00	Russia	MSK/MSD	1990
			3:00	-	MSK	1990 Jul  1 2:00
			2:00	-	EET	1992
# From Paul Eggert (2006-03-22):
# The _Economist_ (1994-05-28, p 45) reports that central Crimea switched
# from Kiev to Moscow time sometime after the January 1994 elections.
# Shanks (1999) says ``date of change uncertain'', but implies that it happened
# sometime between the 1994 DST switches.  Shanks & Pottenger simply say
# 1994-09-25 03:00, but that can't be right.  For now, guess it
# changed in May.
			2:00	E-Eur	EE%sT	1994 May
# From IATA SSIM (1994/1997), which also says that Kerch is still like Kiev.
			3:00	E-Eur	MSK/MSD	1996 Mar 31 3:00s
			3:00	1:00	MSD	1996 Oct 27 3:00s
# IATA SSIM (1997-09) says Crimea switched to EET/EEST.
# Assume it happened in March by not changing the clocks.
			3:00	Russia	MSK/MSD	1997
			3:00	-	MSK	1997 Mar lastSun 1:00u
			2:00	EU	EE%sT

###############################################################################

# One source shows that Bulgaria, Cyprus, Finland, and Greece observe DST from
# the last Sunday in March to the last Sunday in September in 1986.
# The source shows Romania changing a day later than everybody else.
#
# According to Bernard Sieloff's source, Poland is in the MET time zone but
# uses the WE DST rules.  The Western USSR uses EET+1 and ME DST rules.
# Bernard Sieloff's source claims Romania switches on the same day, but at
# 00:00 standard time (i.e., 01:00 DST).  It also claims that Turkey
# switches on the same day, but switches on at 01:00 standard time
# and off at 00:00 standard time (i.e., 01:00 DST)

# ...
# Date: Wed, 28 Jan 87 16:56:27 -0100
# From: Tom Hofmann
# ...
#
# ...the European time rules are...standardized since 1981, when
# most European coun[tr]ies started DST.  Before that year, only
# a few countries (UK, France, Italy) had DST, each according
# to own national rules.  In 1981, however, DST started on
# 'Apr firstSun', and not on 'Mar lastSun' as in the following
# years...
# But also since 1981 there are some more national exceptions
# than listed in 'europe': Switzerland, for example, joined DST
# one year later, Denmark ended DST on 'Oct 1' instead of 'Sep
# lastSun' in 1981---I don't know how they handle now.
#
# Finally, DST ist always from 'Apr 1' to 'Oct 1' in the
# Soviet Union (as far as I know).
#
# Tom Hofmann, Scientific Computer Center, CIBA-GEIGY AG,
# 4002 Basle, Switzerland
# ...

# ...
# Date: Wed, 4 Feb 87 22:35:22 +0100
# From: Dik T. Winter
# ...
#
# The information from Tom Hofmann is (as far as I know) not entirely correct.
# After a request from chongo at amdahl I tried to retrieve all information
# about DST in Europe.  I was able to find all from about 1969.
#
# ...standardization on DST in Europe started in about 1977 with switches on
# first Sunday in April and last Sunday in September...
# In 1981 UK joined Europe insofar that
# the starting day for both shifted to last Sunday in March.  And from 1982
# the whole of Europe used DST, with switch dates April 1 and October 1 in
# the Sov[i]et Union.  In 1985 the SU reverted to standard Europe[a]n switch
# dates...
#
# It should also be remembered that time-zones are not constants; e.g.
# Portugal switched in 1976 from MET (or CET) to WET with DST...
# Note also that though there were rules for switch dates not
# all countries abided to these dates, and many individual deviations
# occurred, though not since 1982 I believe.  Another note: it is always
# assumed that DST is 1 hour ahead of normal time, this need not be the
# case; at least in the Netherlands there have been times when DST was 2 hours
# in advance of normal time.
#
# ...
# dik t. winter, cwi, amsterdam, nederland
# ...

# From Bob Devine (1988-01-28):
# ...
# Greece: Last Sunday in April to last Sunday in September (iffy on dates).
# Since 1978.  Change at midnight.
# ...
# Monaco: has same DST as France.
# ...
joda-time-2.3/src/main/java/org/joda/time/tz/src/antarctica0000644000175000017500000003332312137470245023146 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# From Paul Eggert (1999-11-15):
# To keep things manageable, we list only locations occupied year-round; see
# 
# COMNAP - Stations and Bases
# 
# and
# 
# Summary of the Peri-Antarctic Islands (1998-07-23)
# 
# for information.
# Unless otherwise specified, we have no time zone information.
#
# Except for the French entries,
# I made up all time zone abbreviations mentioned here; corrections welcome!
# FORMAT is `zzz' and GMTOFF is 0 for locations while uninhabited.

# These rules are stolen from the `southamerica' file.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	ArgAQ	1964	1966	-	Mar	 1	0:00	0	-
Rule	ArgAQ	1964	1966	-	Oct	15	0:00	1:00	S
Rule	ArgAQ	1967	only	-	Apr	 2	0:00	0	-
Rule	ArgAQ	1967	1968	-	Oct	Sun>=1	0:00	1:00	S
Rule	ArgAQ	1968	1969	-	Apr	Sun>=1	0:00	0	-
Rule	ArgAQ	1974	only	-	Jan	23	0:00	1:00	S
Rule	ArgAQ	1974	only	-	May	 1	0:00	0	-
Rule	ChileAQ	1972	1986	-	Mar	Sun>=9	3:00u	0	-
Rule	ChileAQ	1974	1987	-	Oct	Sun>=9	4:00u	1:00	S
Rule	ChileAQ	1987	only	-	Apr	12	3:00u	0	-
Rule	ChileAQ	1988	1989	-	Mar	Sun>=9	3:00u	0	-
Rule	ChileAQ	1988	only	-	Oct	Sun>=1	4:00u	1:00	S
Rule	ChileAQ	1989	only	-	Oct	Sun>=9	4:00u	1:00	S
Rule	ChileAQ	1990	only	-	Mar	18	3:00u	0	-
Rule	ChileAQ	1990	only	-	Sep	16	4:00u	1:00	S
Rule	ChileAQ	1991	1996	-	Mar	Sun>=9	3:00u	0	-
Rule	ChileAQ	1991	1997	-	Oct	Sun>=9	4:00u	1:00	S
Rule	ChileAQ	1997	only	-	Mar	30	3:00u	0	-
Rule	ChileAQ	1998	only	-	Mar	Sun>=9	3:00u	0	-
Rule	ChileAQ	1998	only	-	Sep	27	4:00u	1:00	S
Rule	ChileAQ	1999	only	-	Apr	 4	3:00u	0	-
Rule	ChileAQ	1999	2010	-	Oct	Sun>=9	4:00u	1:00	S
Rule	ChileAQ	2000	2007	-	Mar	Sun>=9	3:00u	0	-
# N.B.: the end of March 29 in Chile is March 30 in Universal time,
# which is used below in specifying the transition.
Rule	ChileAQ	2008	only	-	Mar	30	3:00u	0	-
Rule	ChileAQ	2009	only	-	Mar	Sun>=9	3:00u	0	-
Rule	ChileAQ	2010	only	-	Apr	Sun>=1	3:00u	0	-
Rule	ChileAQ	2011	only	-	May	Sun>=2	3:00u	0	-
Rule	ChileAQ	2011	only	-	Aug	Sun>=16	4:00u	1:00	S
Rule	ChileAQ	2012	max	-	Apr	Sun>=23	3:00u	0	-
Rule	ChileAQ	2012	max	-	Sep	Sun>=2	4:00u	1:00	S

# Argentina - year-round bases
# Belgrano II, Confin Coast, -770227-0343737, since 1972-02-05
# Esperanza, San Martin Land, -6323-05659, since 1952-12-17
# Jubany, Potter Peninsula, King George Island, -6414-0602320, since 1982-01
# Marambio, Seymour I, -6414-05637, since 1969-10-29
# Orcadas, Laurie I, -6016-04444, since 1904-02-22
# San Martin, Debenham I, -6807-06708, since 1951-03-21
#	(except 1960-03 / 1976-03-21)

# Australia - territories
# Heard Island, McDonald Islands (uninhabited)
#	previously sealers and scientific personnel wintered
#	
#	Margaret Turner reports
#	 (1999-09-30) that they're UTC+5, with no DST;
#	presumably this is when they have visitors.
#
# year-round bases
# Casey, Bailey Peninsula, -6617+11032, since 1969
# Davis, Vestfold Hills, -6835+07759, since 1957-01-13
#	(except 1964-11 - 1969-02)
# Mawson, Holme Bay, -6736+06253, since 1954-02-13

# From Steffen Thorsen (2009-03-11):
# Three Australian stations in Antarctica have changed their time zone:
# Casey moved from UTC+8 to UTC+11
# Davis moved from UTC+7 to UTC+5
# Mawson moved from UTC+6 to UTC+5
# The changes occurred on 2009-10-18 at 02:00 (local times).
#
# Government source: (Australian Antarctic Division)
# 
# http://www.aad.gov.au/default.asp?casid=37079
# 
#
# We have more background information here:
# 
# http://www.timeanddate.com/news/time/antarctica-new-times.html
# 

# From Steffen Thorsen (2010-03-10):
# We got these changes from the Australian Antarctic Division: ...
#
# - Casey station reverted to its normal time of UTC+8 on 5 March 2010.
# The change to UTC+11 is being considered as a regular summer thing but
# has not been decided yet.
#
# - Davis station will revert to its normal time of UTC+7 at 10 March 2010
# 20:00 UTC.
#
# - Mawson station stays on UTC+5.
#
# Background:
# 
# http://www.timeanddate.com/news/time/antartica-time-changes-2010.html
# 

# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Antarctica/Casey	0	-	zzz	1969
			8:00	-	WST	2009 Oct 18 2:00
						# Western (Aus) Standard Time
			11:00	-	CAST	2010 Mar 5 2:00
						# Casey Time
			8:00	-	WST	2011 Oct 28 2:00
			11:00	-	CAST	2012 Feb 21 17:00u
			8:00	-	WST
Zone Antarctica/Davis	0	-	zzz	1957 Jan 13
			7:00	-	DAVT	1964 Nov # Davis Time
			0	-	zzz	1969 Feb
			7:00	-	DAVT	2009 Oct 18 2:00
			5:00	-	DAVT	2010 Mar 10 20:00u
			7:00	-	DAVT	2011 Oct 28 2:00
			5:00	-	DAVT	2012 Feb 21 20:00u
			7:00	-	DAVT
Zone Antarctica/Mawson	0	-	zzz	1954 Feb 13
			6:00	-	MAWT	2009 Oct 18 2:00
						# Mawson Time
			5:00	-	MAWT
# References:
# 
# Casey Weather (1998-02-26)
# 
# 
# Davis Station, Antarctica (1998-02-26)
# 
# 
# Mawson Station, Antarctica (1998-02-25)
# 

# Brazil - year-round base
# Comandante Ferraz, King George Island, -6205+05824, since 1983/4

# Chile - year-round bases and towns
# Escudero, South Shetland Is, -621157-0585735, since 1994
# Presidente Eduadro Frei, King George Island, -6214-05848, since 1969-03-07
# General Bernardo O'Higgins, Antarctic Peninsula, -6319-05704, since 1948-02
# Capitan Arturo Prat, -6230-05941
# Villa Las Estrellas (a town), around the Frei base, since 1984-04-09
# These locations have always used Santiago time; use TZ='America/Santiago'.

# China - year-round bases
# Great Wall, King George Island, -6213-05858, since 1985-02-20
# Zhongshan, Larsemann Hills, Prydz Bay, -6922+07623, since 1989-02-26

# France - year-round bases
#
# From Antoine Leca (1997-01-20):
# Time data are from Nicole Pailleau at the IFRTP
# (French Institute for Polar Research and Technology).
# She confirms that French Southern Territories and Terre Adelie bases
# don't observe daylight saving time, even if Terre Adelie supplies came
# from Tasmania.
#
# French Southern Territories with year-round inhabitants
#
# Martin-de-Vivies Base, Amsterdam Island, -374105+0773155, since 1950
# Alfred-Faure Base, Crozet Islands, -462551+0515152, since 1964
# Port-aux-Francais, Kerguelen Islands, -492110+0701303, since 1951;
#	whaling & sealing station operated 1908/1914, 1920/1929, and 1951/1956
#
# St Paul Island - near Amsterdam, uninhabited
#	fishing stations operated variously 1819/1931
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Indian/Kerguelen	0	-	zzz	1950	# Port-aux-Francais
			5:00	-	TFT	# ISO code TF Time
#
# year-round base in the main continent
# Dumont-d'Urville, Ile des Petrels, -6640+14001, since 1956-11
#
# Another base at Port-Martin, 50km east, began operation in 1947.
# It was destroyed by fire on 1952-01-14.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Antarctica/DumontDUrville 0 -	zzz	1947
			10:00	-	PMT	1952 Jan 14 # Port-Martin Time
			0	-	zzz	1956 Nov
			10:00	-	DDUT	# Dumont-d'Urville Time
# Reference:
# 
# Dumont d'Urville Station (2005-12-05)
# 

# Germany - year-round base
# Georg von Neumayer, -7039-00815

# India - year-round base
# Dakshin Gangotri, -7005+01200

# Japan - year-round bases
# Dome Fuji, -7719+03942
# Syowa, -690022+0393524
#
# From Hideyuki Suzuki (1999-02-06):
# In all Japanese stations, +0300 is used as the standard time.
#
# Syowa station, which is the first antarctic station of Japan,
# was established on 1957-01-29.  Since Syowa station is still the main
# station of Japan, it's appropriate for the principal location.
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Antarctica/Syowa	0	-	zzz	1957 Jan 29
			3:00	-	SYOT	# Syowa Time
# See:
# 
# NIPR Antarctic Research Activities (1999-08-17)
# 

# S Korea - year-round base
# King Sejong, King George Island, -6213-05847, since 1988

# New Zealand - claims
# Balleny Islands (never inhabited)
# Scott Island (never inhabited)
#
# year-round base
# Scott, Ross Island, since 1957-01, is like Antarctica/McMurdo.
#
# These rules for New Zealand are stolen from the `australasia' file.
# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
Rule	NZAQ	1974	only	-	Nov	 3	2:00s	1:00	D
Rule	NZAQ	1975	1988	-	Oct	lastSun	2:00s	1:00	D
Rule	NZAQ	1989	only	-	Oct	 8	2:00s	1:00	D
Rule	NZAQ	1990	2006	-	Oct	Sun>=1	2:00s	1:00	D
Rule	NZAQ	1975	only	-	Feb	23	2:00s	0	S
Rule	NZAQ	1976	1989	-	Mar	Sun>=1	2:00s	0	S
Rule	NZAQ	1990	2007	-	Mar	Sun>=15	2:00s	0	S
Rule	NZAQ	2007	max	-	Sep	lastSun	2:00s	1:00	D
Rule	NZAQ	2008	max	-	Apr	Sun>=1	2:00s	0	S

# Norway - territories
# Bouvet (never inhabited)
#
# claims
# Peter I Island (never inhabited)

# Poland - year-round base
# Arctowski, King George Island, -620945-0582745, since 1977

# Russia - year-round bases
# Bellingshausen, King George Island, -621159-0585337, since 1968-02-22
# Mirny, Davis coast, -6633+09301, since 1956-02
# Molodezhnaya, Alasheyev Bay, -6740+04551,
#	year-round from 1962-02 to 1999-07-01
# Novolazarevskaya, Queen Maud Land, -7046+01150,
#	year-round from 1960/61 to 1992

# Vostok, since 1957-12-16, temporarily closed 1994-02/1994-11
# 
# From Craig Mundell (1994-12-15):
# Vostok, which is one of the Russian stations, is set on the same
# time as Moscow, Russia.
#
# From Lee Hotz (2001-03-08):
# I queried the folks at Columbia who spent the summer at Vostok and this is
# what they had to say about time there:
# ``in the US Camp (East Camp) we have been on New Zealand (McMurdo)
# time, which is 12 hours ahead of GMT. The Russian Station Vostok was
# 6 hours behind that (although only 2 miles away, i.e. 6 hours ahead
# of GMT). This is a time zone I think two hours east of Moscow. The
# natural time zone is in between the two: 8 hours ahead of GMT.''
#
# From Paul Eggert (2001-05-04):
# This seems to be hopelessly confusing, so I asked Lee Hotz about it
# in person.  He said that some Antartic locations set their local
# time so that noon is the warmest part of the day, and that this
# changes during the year and does not necessarily correspond to mean
# solar noon.  So the Vostok time might have been whatever the clocks
# happened to be during their visit.  So we still don't really know what time
# it is at Vostok.  But we'll guess UTC+6.
#
Zone Antarctica/Vostok	0	-	zzz	1957 Dec 16
			6:00	-	VOST	# Vostok time

# S Africa - year-round bases
# Marion Island, -4653+03752
# Sanae, -7141-00250

# UK
#
# British Antarctic Territories (BAT) claims
# South Orkney Islands
#	scientific station from 1903
#	whaling station at Signy I 1920/1926
# South Shetland Islands
#
# year-round bases
# Bird Island, South Georgia, -5400-03803, since 1983
# Deception Island, -6259-06034, whaling station 1912/1931,
#	scientific station 1943/1967,
#	previously sealers and a scientific expedition wintered by accident,
#	and a garrison was deployed briefly
# Halley, Coates Land, -7535-02604, since 1956-01-06
#	Halley is on a moving ice shelf and is periodically relocated
#	so that it is never more than 10km from its nominal location.
# Rothera, Adelaide Island, -6734-6808, since 1976-12-01
#
# From Paul Eggert (2002-10-22)
#  says Rothera is -03 all year.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Antarctica/Rothera	0	-	zzz	1976 Dec  1
			-3:00	-	ROTT	# Rothera time

# Uruguay - year round base
# Artigas, King George Island, -621104-0585107

# USA - year-round bases
#
# Palmer, Anvers Island, since 1965 (moved 2 miles in 1968)
#
# From Ethan Dicks (1996-10-06):
# It keeps the same time as Punta Arenas, Chile, because, just like us
# and the South Pole, that's the other end of their supply line....
# I verified with someone who was there that since 1980,
# Palmer has followed Chile.  Prior to that, before the Falklands War,
# Palmer used to be supplied from Argentina.
#
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Antarctica/Palmer	0	-	zzz	1965
			-4:00	ArgAQ	AR%sT	1969 Oct 5
			-3:00	ArgAQ	AR%sT	1982 May
			-4:00	ChileAQ	CL%sT
#
#
# McMurdo, Ross Island, since 1955-12
# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
Zone Antarctica/McMurdo	0	-	zzz	1956
			12:00	NZAQ	NZ%sT
#
# Amundsen-Scott, South Pole, continuously occupied since 1956-11-20
#
# From Paul Eggert (1996-09-03):
# Normally it wouldn't have a separate entry, since it's like the
# larger Antarctica/McMurdo since 1970, but it's too famous to omit.
#
# From Chris Carrier (1996-06-27):
# Siple, the first commander of the South Pole station,
# stated that he would have liked to have kept GMT at the station,
# but that he found it more convenient to keep GMT+12
# as supplies for the station were coming from McMurdo Sound,
# which was on GMT+12 because New Zealand was on GMT+12 all year
# at that time (1957).  (Source: Siple's book 90 degrees SOUTH.)
#
# From Susan Smith
# http://www.cybertours.com/whs/pole10.html
# (1995-11-13 16:24:56 +1300, no longer available):
# We use the same time as McMurdo does.
# And they use the same time as Christchurch, NZ does....
# One last quirk about South Pole time.
# All the electric clocks are usually wrong.
# Something about the generators running at 60.1hertz or something
# makes all of the clocks run fast.  So every couple of days,
# we have to go around and set them back 5 minutes or so.
# Maybe if we let them run fast all of the time, we'd get to leave here sooner!!
#
Link	Antarctica/McMurdo	Antarctica/South_Pole
joda-time-2.3/src/main/java/org/joda/time/tz/src/pacificnew0000644000175000017500000000224612137470246023146 0ustar  ebourgebourg# 
# This file is in the public domain, so clarified as of
# 2009-05-17 by Arthur David Olson.

# From Arthur David Olson (1989-04-05):
# On 1989-04-05, the U. S. House of Representatives passed (238-154) a bill
# establishing "Pacific Presidential Election Time"; it was not acted on
# by the Senate or signed into law by the President.
# You might want to change the "PE" (Presidential Election) below to
# "Q" (Quadrennial) to maintain three-character zone abbreviations.
# If you're really conservative, you might want to change it to "D".
# Avoid "L" (Leap Year), which won't be true in 2100.

# If Presidential Election Time is ever established, replace "XXXX" below
# with the year the law takes effect and uncomment the "##" lines.

# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
## Rule	Twilite	XXXX	max	-	Apr	Sun>=1	2:00	1:00	D
## Rule	Twilite	XXXX	max	uspres	Oct	lastSun	2:00	1:00	PE
## Rule	Twilite	XXXX	max	uspres	Nov	Sun>=7	2:00	0	S
## Rule	Twilite	XXXX	max	nonpres	Oct	lastSun	2:00	0	S

# Zone	NAME			GMTOFF	RULES/SAVE	FORMAT	[UNTIL]
## Zone	America/Los_Angeles-PET	-8:00	US		P%sT	XXXX
##				-8:00	Twilite		P%sT

# For now...
Link	America/Los_Angeles	US/Pacific-New	##
joda-time-2.3/src/main/java/org/joda/time/tz/DateTimeZoneBuilder.java0000644000175000017500000017652212203435210025021 0ustar  ebourgebourg/*
 *  Copyright 2001-2013 Stephen Colebourne
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.joda.time.tz;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;

import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.chrono.ISOChronology;

/**
 * DateTimeZoneBuilder allows complex DateTimeZones to be constructed. Since
 * creating a new DateTimeZone this way is a relatively expensive operation,
 * built zones can be written to a file. Reading back the encoded data is a
 * quick operation.
 * 

* DateTimeZoneBuilder itself is mutable and not thread-safe, but the * DateTimeZone objects that it builds are thread-safe and immutable. *

* It is intended that {@link ZoneInfoCompiler} be used to read time zone data * files, indirectly calling DateTimeZoneBuilder. The following complex * example defines the America/Los_Angeles time zone, with all historical * transitions: * *

 * DateTimeZone America_Los_Angeles = new DateTimeZoneBuilder()
 *     .addCutover(-2147483648, 'w', 1, 1, 0, false, 0)
 *     .setStandardOffset(-28378000)
 *     .setFixedSavings("LMT", 0)
 *     .addCutover(1883, 'w', 11, 18, 0, false, 43200000)
 *     .setStandardOffset(-28800000)
 *     .addRecurringSavings("PDT", 3600000, 1918, 1919, 'w',  3, -1, 7, false, 7200000)
 *     .addRecurringSavings("PST",       0, 1918, 1919, 'w', 10, -1, 7, false, 7200000)
 *     .addRecurringSavings("PWT", 3600000, 1942, 1942, 'w',  2,  9, 0, false, 7200000)
 *     .addRecurringSavings("PPT", 3600000, 1945, 1945, 'u',  8, 14, 0, false, 82800000)
 *     .addRecurringSavings("PST",       0, 1945, 1945, 'w',  9, 30, 0, false, 7200000)
 *     .addRecurringSavings("PDT", 3600000, 1948, 1948, 'w',  3, 14, 0, false, 7200000)
 *     .addRecurringSavings("PST",       0, 1949, 1949, 'w',  1,  1, 0, false, 7200000)
 *     .addRecurringSavings("PDT", 3600000, 1950, 1966, 'w',  4, -1, 7, false, 7200000)
 *     .addRecurringSavings("PST",       0, 1950, 1961, 'w',  9, -1, 7, false, 7200000)
 *     .addRecurringSavings("PST",       0, 1962, 1966, 'w', 10, -1, 7, false, 7200000)
 *     .addRecurringSavings("PST",       0, 1967, 2147483647, 'w', 10, -1, 7, false, 7200000)
 *     .addRecurringSavings("PDT", 3600000, 1967, 1973, 'w', 4, -1,  7, false, 7200000)
 *     .addRecurringSavings("PDT", 3600000, 1974, 1974, 'w', 1,  6,  0, false, 7200000)
 *     .addRecurringSavings("PDT", 3600000, 1975, 1975, 'w', 2, 23,  0, false, 7200000)
 *     .addRecurringSavings("PDT", 3600000, 1976, 1986, 'w', 4, -1,  7, false, 7200000)
 *     .addRecurringSavings("PDT", 3600000, 1987, 2147483647, 'w', 4, 1, 7, true, 7200000)
 *     .toDateTimeZone("America/Los_Angeles", true);
 * 
* * @author Brian S O'Neill * @see ZoneInfoCompiler * @see ZoneInfoProvider * @since 1.0 */ public class DateTimeZoneBuilder { /** * Decodes a built DateTimeZone from the given stream, as encoded by * writeTo. * * @param in input stream to read encoded DateTimeZone from. * @param id time zone id to assign */ public static DateTimeZone readFrom(InputStream in, String id) throws IOException { if (in instanceof DataInput) { return readFrom((DataInput)in, id); } else { return readFrom((DataInput)new DataInputStream(in), id); } } /** * Decodes a built DateTimeZone from the given stream, as encoded by * writeTo. * * @param in input stream to read encoded DateTimeZone from. * @param id time zone id to assign */ public static DateTimeZone readFrom(DataInput in, String id) throws IOException { switch (in.readUnsignedByte()) { case 'F': DateTimeZone fixed = new FixedDateTimeZone (id, in.readUTF(), (int)readMillis(in), (int)readMillis(in)); if (fixed.equals(DateTimeZone.UTC)) { fixed = DateTimeZone.UTC; } return fixed; case 'C': return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id)); case 'P': return PrecalculatedZone.readFrom(in, id); default: throw new IOException("Invalid encoding"); } } /** * Millisecond encoding formats: * * upper two bits units field length approximate range * --------------------------------------------------------------- * 00 30 minutes 1 byte +/- 16 hours * 01 minutes 4 bytes +/- 1020 years * 10 seconds 5 bytes +/- 4355 years * 11 millis 9 bytes +/- 292,000,000 years * * Remaining bits in field form signed offset from 1970-01-01T00:00:00Z. */ static void writeMillis(DataOutput out, long millis) throws IOException { if (millis % (30 * 60000L) == 0) { // Try to write in 30 minute units. long units = millis / (30 * 60000L); if (((units << (64 - 6)) >> (64 - 6)) == units) { // Form 00 (6 bits effective precision) out.writeByte((int)(units & 0x3f)); return; } } if (millis % 60000L == 0) { // Try to write minutes. long minutes = millis / 60000L; if (((minutes << (64 - 30)) >> (64 - 30)) == minutes) { // Form 01 (30 bits effective precision) out.writeInt(0x40000000 | (int)(minutes & 0x3fffffff)); return; } } if (millis % 1000L == 0) { // Try to write seconds. long seconds = millis / 1000L; if (((seconds << (64 - 38)) >> (64 - 38)) == seconds) { // Form 10 (38 bits effective precision) out.writeByte(0x80 | (int)((seconds >> 32) & 0x3f)); out.writeInt((int)(seconds & 0xffffffff)); return; } } // Write milliseconds either because the additional precision is // required or the minutes didn't fit in the field. // Form 11 (64 bits effective precision, but write as if 70 bits) out.writeByte(millis < 0 ? 0xff : 0xc0); out.writeLong(millis); } /** * Reads encoding generated by writeMillis. */ static long readMillis(DataInput in) throws IOException { int v = in.readUnsignedByte(); switch (v >> 6) { case 0: default: // Form 00 (6 bits effective precision) v = (v << (32 - 6)) >> (32 - 6); return v * (30 * 60000L); case 1: // Form 01 (30 bits effective precision) v = (v << (32 - 6)) >> (32 - 30); v |= (in.readUnsignedByte()) << 16; v |= (in.readUnsignedByte()) << 8; v |= (in.readUnsignedByte()); return v * 60000L; case 2: // Form 10 (38 bits effective precision) long w = (((long)v) << (64 - 6)) >> (64 - 38); w |= (in.readUnsignedByte()) << 24; w |= (in.readUnsignedByte()) << 16; w |= (in.readUnsignedByte()) << 8; w |= (in.readUnsignedByte()); return w * 1000L; case 3: // Form 11 (64 bits effective precision) return in.readLong(); } } private static DateTimeZone buildFixedZone(String id, String nameKey, int wallOffset, int standardOffset) { if ("UTC".equals(id) && id.equals(nameKey) && wallOffset == 0 && standardOffset == 0) { return DateTimeZone.UTC; } return new FixedDateTimeZone(id, nameKey, wallOffset, standardOffset); } // List of RuleSets. private final ArrayList iRuleSets; public DateTimeZoneBuilder() { iRuleSets = new ArrayList(10); } /** * Adds a cutover for added rules. The standard offset at the cutover * defaults to 0. Call setStandardOffset afterwards to change it. * * @param year the year of cutover * @param mode 'u' - cutover is measured against UTC, 'w' - against wall * offset, 's' - against standard offset * @param monthOfYear the month from 1 (January) to 12 (December) * @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth). * For example, if -1, set to last day of month * @param dayOfWeek from 1 (Monday) to 7 (Sunday), if 0 then ignore * @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to * dayOfWeek when true, retreat when false. * @param millisOfDay additional precision for specifying time of day of cutover */ public DateTimeZoneBuilder addCutover(int year, char mode, int monthOfYear, int dayOfMonth, int dayOfWeek, boolean advanceDayOfWeek, int millisOfDay) { if (iRuleSets.size() > 0) { OfYear ofYear = new OfYear (mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay); RuleSet lastRuleSet = iRuleSets.get(iRuleSets.size() - 1); lastRuleSet.setUpperLimit(year, ofYear); } iRuleSets.add(new RuleSet()); return this; } /** * Sets the standard offset to use for newly added rules until the next * cutover is added. * @param standardOffset the standard offset in millis */ public DateTimeZoneBuilder setStandardOffset(int standardOffset) { getLastRuleSet().setStandardOffset(standardOffset); return this; } /** * Set a fixed savings rule at the cutover. */ public DateTimeZoneBuilder setFixedSavings(String nameKey, int saveMillis) { getLastRuleSet().setFixedSavings(nameKey, saveMillis); return this; } /** * Add a recurring daylight saving time rule. * * @param nameKey the name key of new rule * @param saveMillis the milliseconds to add to standard offset * @param fromYear the first year that rule is in effect, MIN_VALUE indicates * beginning of time * @param toYear the last year (inclusive) that rule is in effect, MAX_VALUE * indicates end of time * @param mode 'u' - transitions are calculated against UTC, 'w' - * transitions are calculated against wall offset, 's' - transitions are * calculated against standard offset * @param monthOfYear the month from 1 (January) to 12 (December) * @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth). * For example, if -1, set to last day of month * @param dayOfWeek from 1 (Monday) to 7 (Sunday), if 0 then ignore * @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to * dayOfWeek when true, retreat when false. * @param millisOfDay additional precision for specifying time of day of transitions */ public DateTimeZoneBuilder addRecurringSavings(String nameKey, int saveMillis, int fromYear, int toYear, char mode, int monthOfYear, int dayOfMonth, int dayOfWeek, boolean advanceDayOfWeek, int millisOfDay) { if (fromYear <= toYear) { OfYear ofYear = new OfYear (mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay); Recurrence recurrence = new Recurrence(ofYear, nameKey, saveMillis); Rule rule = new Rule(recurrence, fromYear, toYear); getLastRuleSet().addRule(rule); } return this; } private RuleSet getLastRuleSet() { if (iRuleSets.size() == 0) { addCutover(Integer.MIN_VALUE, 'w', 1, 1, 0, false, 0); } return iRuleSets.get(iRuleSets.size() - 1); } /** * Processes all the rules and builds a DateTimeZone. * * @param id time zone id to assign * @param outputID true if the zone id should be output */ public DateTimeZone toDateTimeZone(String id, boolean outputID) { if (id == null) { throw new IllegalArgumentException(); } // Discover where all the transitions occur and store the results in // these lists. ArrayList transitions = new ArrayList(); // Tail zone picks up remaining transitions in the form of an endless // DST cycle. DSTZone tailZone = null; long millis = Long.MIN_VALUE; int saveMillis = 0; int ruleSetCount = iRuleSets.size(); for (int i=0; i transitions, Transition tr) { int size = transitions.size(); if (size == 0) { transitions.add(tr); return true; } Transition last = transitions.get(size - 1); if (!tr.isTransitionFrom(last)) { return false; } // If local time of new transition is same as last local time, just // replace last transition with new one. int offsetForLast = 0; if (size >= 2) { offsetForLast = transitions.get(size - 2).getWallOffset(); } int offsetForNew = last.getWallOffset(); long lastLocal = last.getMillis() + offsetForLast; long newLocal = tr.getMillis() + offsetForNew; if (newLocal != lastLocal) { transitions.add(tr); return true; } transitions.remove(size - 1); return addTransition(transitions, tr); } /** * Encodes a built DateTimeZone to the given stream. Call readFrom to * decode the data into a DateTimeZone object. * * @param out the output stream to receive the encoded DateTimeZone * @since 1.5 (parameter added) */ public void writeTo(String zoneID, OutputStream out) throws IOException { if (out instanceof DataOutput) { writeTo(zoneID, (DataOutput)out); } else { writeTo(zoneID, (DataOutput)new DataOutputStream(out)); } } /** * Encodes a built DateTimeZone to the given stream. Call readFrom to * decode the data into a DateTimeZone object. * * @param out the output stream to receive the encoded DateTimeZone * @since 1.5 (parameter added) */ public void writeTo(String zoneID, DataOutput out) throws IOException { // pass false so zone id is not written out DateTimeZone zone = toDateTimeZone(zoneID, false); if (zone instanceof FixedDateTimeZone) { out.writeByte('F'); // 'F' for fixed out.writeUTF(zone.getNameKey(0)); writeMillis(out, zone.getOffset(0)); writeMillis(out, zone.getStandardOffset(0)); } else { if (zone instanceof CachedDateTimeZone) { out.writeByte('C'); // 'C' for cached, precalculated zone = ((CachedDateTimeZone)zone).getUncachedZone(); } else { out.writeByte('P'); // 'P' for precalculated, uncached } ((PrecalculatedZone)zone).writeTo(out); } } /** * Supports setting fields of year and moving between transitions. */ private static final class OfYear { static OfYear readFrom(DataInput in) throws IOException { return new OfYear((char)in.readUnsignedByte(), (int)in.readUnsignedByte(), (int)in.readByte(), (int)in.readUnsignedByte(), in.readBoolean(), (int)readMillis(in)); } // Is 'u', 'w', or 's'. final char iMode; final int iMonthOfYear; final int iDayOfMonth; final int iDayOfWeek; final boolean iAdvance; final int iMillisOfDay; OfYear(char mode, int monthOfYear, int dayOfMonth, int dayOfWeek, boolean advanceDayOfWeek, int millisOfDay) { if (mode != 'u' && mode != 'w' && mode != 's') { throw new IllegalArgumentException("Unknown mode: " + mode); } iMode = mode; iMonthOfYear = monthOfYear; iDayOfMonth = dayOfMonth; iDayOfWeek = dayOfWeek; iAdvance = advanceDayOfWeek; iMillisOfDay = millisOfDay; } /** * @param standardOffset standard offset just before instant */ public long setInstant(int year, int standardOffset, int saveMillis) { int offset; if (iMode == 'w') { offset = standardOffset + saveMillis; } else if (iMode == 's') { offset = standardOffset; } else { offset = 0; } Chronology chrono = ISOChronology.getInstanceUTC(); long millis = chrono.year().set(0, year); millis = chrono.monthOfYear().set(millis, iMonthOfYear); millis = chrono.millisOfDay().set(millis, iMillisOfDay); millis = setDayOfMonth(chrono, millis); if (iDayOfWeek != 0) { millis = setDayOfWeek(chrono, millis); } // Convert from local time to UTC. return millis - offset; } /** * @param standardOffset standard offset just before next recurrence */ public long next(long instant, int standardOffset, int saveMillis) { int offset; if (iMode == 'w') { offset = standardOffset + saveMillis; } else if (iMode == 's') { offset = standardOffset; } else { offset = 0; } // Convert from UTC to local time. instant += offset; Chronology chrono = ISOChronology.getInstanceUTC(); long next = chrono.monthOfYear().set(instant, iMonthOfYear); // Be lenient with millisOfDay. next = chrono.millisOfDay().set(next, 0); next = chrono.millisOfDay().add(next, iMillisOfDay); next = setDayOfMonthNext(chrono, next); if (iDayOfWeek == 0) { if (next <= instant) { next = chrono.year().add(next, 1); next = setDayOfMonthNext(chrono, next); } } else { next = setDayOfWeek(chrono, next); if (next <= instant) { next = chrono.year().add(next, 1); next = chrono.monthOfYear().set(next, iMonthOfYear); next = setDayOfMonthNext(chrono, next); next = setDayOfWeek(chrono, next); } } // Convert from local time to UTC. return next - offset; } /** * @param standardOffset standard offset just before previous recurrence */ public long previous(long instant, int standardOffset, int saveMillis) { int offset; if (iMode == 'w') { offset = standardOffset + saveMillis; } else if (iMode == 's') { offset = standardOffset; } else { offset = 0; } // Convert from UTC to local time. instant += offset; Chronology chrono = ISOChronology.getInstanceUTC(); long prev = chrono.monthOfYear().set(instant, iMonthOfYear); // Be lenient with millisOfDay. prev = chrono.millisOfDay().set(prev, 0); prev = chrono.millisOfDay().add(prev, iMillisOfDay); prev = setDayOfMonthPrevious(chrono, prev); if (iDayOfWeek == 0) { if (prev >= instant) { prev = chrono.year().add(prev, -1); prev = setDayOfMonthPrevious(chrono, prev); } } else { prev = setDayOfWeek(chrono, prev); if (prev >= instant) { prev = chrono.year().add(prev, -1); prev = chrono.monthOfYear().set(prev, iMonthOfYear); prev = setDayOfMonthPrevious(chrono, prev); prev = setDayOfWeek(chrono, prev); } } // Convert from local time to UTC. return prev - offset; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof OfYear) { OfYear other = (OfYear)obj; return iMode == other.iMode && iMonthOfYear == other.iMonthOfYear && iDayOfMonth == other.iDayOfMonth && iDayOfWeek == other.iDayOfWeek && iAdvance == other.iAdvance && iMillisOfDay == other.iMillisOfDay; } return false; } /* public String toString() { return "[OfYear]\n" + "Mode: " + iMode + '\n' + "MonthOfYear: " + iMonthOfYear + '\n' + "DayOfMonth: " + iDayOfMonth + '\n' + "DayOfWeek: " + iDayOfWeek + '\n' + "AdvanceDayOfWeek: " + iAdvance + '\n' + "MillisOfDay: " + iMillisOfDay + '\n'; } */ public void writeTo(DataOutput out) throws IOException { out.writeByte(iMode); out.writeByte(iMonthOfYear); out.writeByte(iDayOfMonth); out.writeByte(iDayOfWeek); out.writeBoolean(iAdvance); writeMillis(out, iMillisOfDay); } /** * If month-day is 02-29 and year isn't leap, advances to next leap year. */ private long setDayOfMonthNext(Chronology chrono, long next) { try { next = setDayOfMonth(chrono, next); } catch (IllegalArgumentException e) { if (iMonthOfYear == 2 && iDayOfMonth == 29) { while (chrono.year().isLeap(next) == false) { next = chrono.year().add(next, 1); } next = setDayOfMonth(chrono, next); } else { throw e; } } return next; } /** * If month-day is 02-29 and year isn't leap, retreats to previous leap year. */ private long setDayOfMonthPrevious(Chronology chrono, long prev) { try { prev = setDayOfMonth(chrono, prev); } catch (IllegalArgumentException e) { if (iMonthOfYear == 2 && iDayOfMonth == 29) { while (chrono.year().isLeap(prev) == false) { prev = chrono.year().add(prev, -1); } prev = setDayOfMonth(chrono, prev); } else { throw e; } } return prev; } private long setDayOfMonth(Chronology chrono, long instant) { if (iDayOfMonth >= 0) { instant = chrono.dayOfMonth().set(instant, iDayOfMonth); } else { instant = chrono.dayOfMonth().set(instant, 1); instant = chrono.monthOfYear().add(instant, 1); instant = chrono.dayOfMonth().add(instant, iDayOfMonth); } return instant; } private long setDayOfWeek(Chronology chrono, long instant) { int dayOfWeek = chrono.dayOfWeek().get(instant); int daysToAdd = iDayOfWeek - dayOfWeek; if (daysToAdd != 0) { if (iAdvance) { if (daysToAdd < 0) { daysToAdd += 7; } } else { if (daysToAdd > 0) { daysToAdd -= 7; } } instant = chrono.dayOfWeek().add(instant, daysToAdd); } return instant; } } /** * Extends OfYear with a nameKey and savings. */ private static final class Recurrence { static Recurrence readFrom(DataInput in) throws IOException { return new Recurrence(OfYear.readFrom(in), in.readUTF(), (int)readMillis(in)); } final OfYear iOfYear; final String iNameKey; final int iSaveMillis; Recurrence(OfYear ofYear, String nameKey, int saveMillis) { iOfYear = ofYear; iNameKey = nameKey; iSaveMillis = saveMillis; } public OfYear getOfYear() { return iOfYear; } /** * @param standardOffset standard offset just before next recurrence */ public long next(long instant, int standardOffset, int saveMillis) { return iOfYear.next(instant, standardOffset, saveMillis); } /** * @param standardOffset standard offset just before previous recurrence */ public long previous(long instant, int standardOffset, int saveMillis) { return iOfYear.previous(instant, standardOffset, saveMillis); } public String getNameKey() { return iNameKey; } public int getSaveMillis() { return iSaveMillis; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Recurrence) { Recurrence other = (Recurrence)obj; return iSaveMillis == other.iSaveMillis && iNameKey.equals(other.iNameKey) && iOfYear.equals(other.iOfYear); } return false; } public void writeTo(DataOutput out) throws IOException { iOfYear.writeTo(out); out.writeUTF(iNameKey); writeMillis(out, iSaveMillis); } Recurrence rename(String nameKey) { return new Recurrence(iOfYear, nameKey, iSaveMillis); } Recurrence renameAppend(String appendNameKey) { return rename((iNameKey + appendNameKey).intern()); } } /** * Extends Recurrence with inclusive year limits. */ private static final class Rule { final Recurrence iRecurrence; final int iFromYear; // inclusive final int iToYear; // inclusive Rule(Recurrence recurrence, int fromYear, int toYear) { iRecurrence = recurrence; iFromYear = fromYear; iToYear = toYear; } @SuppressWarnings("unused") public int getFromYear() { return iFromYear; } public int getToYear() { return iToYear; } @SuppressWarnings("unused") public OfYear getOfYear() { return iRecurrence.getOfYear(); } public String getNameKey() { return iRecurrence.getNameKey(); } public int getSaveMillis() { return iRecurrence.getSaveMillis(); } public long next(final long instant, int standardOffset, int saveMillis) { Chronology chrono = ISOChronology.getInstanceUTC(); final int wallOffset = standardOffset + saveMillis; long testInstant = instant; int year; if (instant == Long.MIN_VALUE) { year = Integer.MIN_VALUE; } else { year = chrono.year().get(instant + wallOffset); } if (year < iFromYear) { // First advance instant to start of from year. testInstant = chrono.year().set(0, iFromYear) - wallOffset; // Back off one millisecond to account for next recurrence // being exactly at the beginning of the year. testInstant -= 1; } long next = iRecurrence.next(testInstant, standardOffset, saveMillis); if (next > instant) { year = chrono.year().get(next + wallOffset); if (year > iToYear) { // Out of range, return original value. next = instant; } } return next; } } private static final class Transition { private final long iMillis; private final String iNameKey; private final int iWallOffset; private final int iStandardOffset; Transition(long millis, Transition tr) { iMillis = millis; iNameKey = tr.iNameKey; iWallOffset = tr.iWallOffset; iStandardOffset = tr.iStandardOffset; } Transition(long millis, Rule rule, int standardOffset) { iMillis = millis; iNameKey = rule.getNameKey(); iWallOffset = standardOffset + rule.getSaveMillis(); iStandardOffset = standardOffset; } Transition(long millis, String nameKey, int wallOffset, int standardOffset) { iMillis = millis; iNameKey = nameKey; iWallOffset = wallOffset; iStandardOffset = standardOffset; } public long getMillis() { return iMillis; } public String getNameKey() { return iNameKey; } public int getWallOffset() { return iWallOffset; } public int getStandardOffset() { return iStandardOffset; } public int getSaveMillis() { return iWallOffset - iStandardOffset; } /** * There must be a change in the millis, wall offsets or name keys. */ public boolean isTransitionFrom(Transition other) { if (other == null) { return true; } return iMillis > other.iMillis && (iWallOffset != other.iWallOffset || //iStandardOffset != other.iStandardOffset || !(iNameKey.equals(other.iNameKey))); } } private static final class RuleSet { private static final int YEAR_LIMIT; static { // Don't pre-calculate more than 100 years into the future. Almost // all zones will stop pre-calculating far sooner anyhow. Either a // simple DST cycle is detected or the last rule is a fixed // offset. If a zone has a fixed offset set more than 100 years // into the future, then it won't be observed. long now = DateTimeUtils.currentTimeMillis(); YEAR_LIMIT = ISOChronology.getInstanceUTC().year().get(now) + 100; } private int iStandardOffset; private ArrayList iRules; // Optional. private String iInitialNameKey; private int iInitialSaveMillis; // Upper limit is exclusive. private int iUpperYear; private OfYear iUpperOfYear; RuleSet() { iRules = new ArrayList(10); iUpperYear = Integer.MAX_VALUE; } /** * Copy constructor. */ RuleSet(RuleSet rs) { iStandardOffset = rs.iStandardOffset; iRules = new ArrayList(rs.iRules); iInitialNameKey = rs.iInitialNameKey; iInitialSaveMillis = rs.iInitialSaveMillis; iUpperYear = rs.iUpperYear; iUpperOfYear = rs.iUpperOfYear; } @SuppressWarnings("unused") public int getStandardOffset() { return iStandardOffset; } public void setStandardOffset(int standardOffset) { iStandardOffset = standardOffset; } public void setFixedSavings(String nameKey, int saveMillis) { iInitialNameKey = nameKey; iInitialSaveMillis = saveMillis; } public void addRule(Rule rule) { if (!iRules.contains(rule)) { iRules.add(rule); } } public void setUpperLimit(int year, OfYear ofYear) { iUpperYear = year; iUpperOfYear = ofYear; } /** * Returns a transition at firstMillis with the first name key and * offsets for this rule set. This method may return null. * * @param firstMillis millis of first transition */ public Transition firstTransition(final long firstMillis) { if (iInitialNameKey != null) { // Initial zone info explicitly set, so don't search the rules. return new Transition(firstMillis, iInitialNameKey, iStandardOffset + iInitialSaveMillis, iStandardOffset); } // Make a copy before we destroy the rules. ArrayList copy = new ArrayList(iRules); // Iterate through all the transitions until firstMillis is // reached. Use the name key and savings for whatever rule reaches // the limit. long millis = Long.MIN_VALUE; int saveMillis = 0; Transition first = null; Transition next; while ((next = nextTransition(millis, saveMillis)) != null) { millis = next.getMillis(); if (millis == firstMillis) { first = new Transition(firstMillis, next); break; } if (millis > firstMillis) { if (first == null) { // Find first rule without savings. This way a more // accurate nameKey is found even though no rule // extends to the RuleSet's lower limit. for (Rule rule : copy) { if (rule.getSaveMillis() == 0) { first = new Transition(firstMillis, rule, iStandardOffset); break; } } } if (first == null) { // Found no rule without savings. Create a transition // with no savings anyhow, and use the best available // name key. first = new Transition(firstMillis, next.getNameKey(), iStandardOffset, iStandardOffset); } break; } // Set first to the best transition found so far, but next // iteration may find something closer to lower limit. first = new Transition(firstMillis, next); saveMillis = next.getSaveMillis(); } iRules = copy; return first; } /** * Returns null if RuleSet is exhausted or upper limit reached. Calling * this method will throw away rules as they each become * exhausted. Copy the RuleSet before using it to compute transitions. * * Returned transition may be a duplicate from previous * transition. Caller must call isTransitionFrom to filter out * duplicates. * * @param saveMillis savings before next transition */ public Transition nextTransition(final long instant, final int saveMillis) { Chronology chrono = ISOChronology.getInstanceUTC(); // Find next matching rule. Rule nextRule = null; long nextMillis = Long.MAX_VALUE; Iterator it = iRules.iterator(); while (it.hasNext()) { Rule rule = it.next(); long next = rule.next(instant, iStandardOffset, saveMillis); if (next <= instant) { it.remove(); continue; } // Even if next is same as previous next, choose the rule // in order for more recently added rules to override. if (next <= nextMillis) { // Found a better match. nextRule = rule; nextMillis = next; } } if (nextRule == null) { return null; } // Stop precalculating if year reaches some arbitrary limit. if (chrono.year().get(nextMillis) >= YEAR_LIMIT) { return null; } // Check if upper limit reached or passed. if (iUpperYear < Integer.MAX_VALUE) { long upperMillis = iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis); if (nextMillis >= upperMillis) { // At or after upper limit. return null; } } return new Transition(nextMillis, nextRule, iStandardOffset); } /** * @param saveMillis savings before upper limit */ public long getUpperLimit(int saveMillis) { if (iUpperYear == Integer.MAX_VALUE) { return Long.MAX_VALUE; } return iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis); } /** * Returns null if none can be built. */ public DSTZone buildTailZone(String id) { if (iRules.size() == 2) { Rule startRule = iRules.get(0); Rule endRule = iRules.get(1); if (startRule.getToYear() == Integer.MAX_VALUE && endRule.getToYear() == Integer.MAX_VALUE) { // With exactly two infinitely recurring rules left, a // simple DSTZone can be formed. // The order of rules can come in any order, and it doesn't // really matter which rule was chosen the 'start' and // which is chosen the 'end'. DSTZone works properly either // way. return new DSTZone(id, iStandardOffset, startRule.iRecurrence, endRule.iRecurrence); } } return null; } } private static final class DSTZone extends DateTimeZone { private static final long serialVersionUID = 6941492635554961361L; static DSTZone readFrom(DataInput in, String id) throws IOException { return new DSTZone(id, (int)readMillis(in), Recurrence.readFrom(in), Recurrence.readFrom(in)); } final int iStandardOffset; final Recurrence iStartRecurrence; final Recurrence iEndRecurrence; DSTZone(String id, int standardOffset, Recurrence startRecurrence, Recurrence endRecurrence) { super(id); iStandardOffset = standardOffset; iStartRecurrence = startRecurrence; iEndRecurrence = endRecurrence; } public String getNameKey(long instant) { return findMatchingRecurrence(instant).getNameKey(); } public int getOffset(long instant) { return iStandardOffset + findMatchingRecurrence(instant).getSaveMillis(); } public int getStandardOffset(long instant) { return iStandardOffset; } public boolean isFixed() { return false; } public long nextTransition(long instant) { int standardOffset = iStandardOffset; Recurrence startRecurrence = iStartRecurrence; Recurrence endRecurrence = iEndRecurrence; long start, end; try { start = startRecurrence.next (instant, standardOffset, endRecurrence.getSaveMillis()); if (instant > 0 && start < 0) { // Overflowed. start = instant; } } catch (IllegalArgumentException e) { // Overflowed. start = instant; } catch (ArithmeticException e) { // Overflowed. start = instant; } try { end = endRecurrence.next (instant, standardOffset, startRecurrence.getSaveMillis()); if (instant > 0 && end < 0) { // Overflowed. end = instant; } } catch (IllegalArgumentException e) { // Overflowed. end = instant; } catch (ArithmeticException e) { // Overflowed. end = instant; } return (start > end) ? end : start; } public long previousTransition(long instant) { // Increment in order to handle the case where instant is exactly at // a transition. instant++; int standardOffset = iStandardOffset; Recurrence startRecurrence = iStartRecurrence; Recurrence endRecurrence = iEndRecurrence; long start, end; try { start = startRecurrence.previous (instant, standardOffset, endRecurrence.getSaveMillis()); if (instant < 0 && start > 0) { // Overflowed. start = instant; } } catch (IllegalArgumentException e) { // Overflowed. start = instant; } catch (ArithmeticException e) { // Overflowed. start = instant; } try { end = endRecurrence.previous (instant, standardOffset, startRecurrence.getSaveMillis()); if (instant < 0 && end > 0) { // Overflowed. end = instant; } } catch (IllegalArgumentException e) { // Overflowed. end = instant; } catch (ArithmeticException e) { // Overflowed. end = instant; } return ((start > end) ? start : end) - 1; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DSTZone) { DSTZone other = (DSTZone)obj; return getID().equals(other.getID()) && iStandardOffset == other.iStandardOffset && iStartRecurrence.equals(other.iStartRecurrence) && iEndRecurrence.equals(other.iEndRecurrence); } return false; } public void writeTo(DataOutput out) throws IOException { writeMillis(out, iStandardOffset); iStartRecurrence.writeTo(out); iEndRecurrence.writeTo(out); } private Recurrence findMatchingRecurrence(long instant) { int standardOffset = iStandardOffset; Recurrence startRecurrence = iStartRecurrence; Recurrence endRecurrence = iEndRecurrence; long start, end; try { start = startRecurrence.next (instant, standardOffset, endRecurrence.getSaveMillis()); } catch (IllegalArgumentException e) { // Overflowed. start = instant; } catch (ArithmeticException e) { // Overflowed. start = instant; } try { end = endRecurrence.next (instant, standardOffset, startRecurrence.getSaveMillis()); } catch (IllegalArgumentException e) { // Overflowed. end = instant; } catch (ArithmeticException e) { // Overflowed. end = instant; } return (start > end) ? startRecurrence : endRecurrence; } } private static final class PrecalculatedZone extends DateTimeZone { private static final long serialVersionUID = 7811976468055766265L; static PrecalculatedZone readFrom(DataInput in, String id) throws IOException { // Read string pool. int poolSize = in.readUnsignedShort(); String[] pool = new String[poolSize]; for (int i=0; i transitions, DSTZone tailZone) { int size = transitions.size(); if (size == 0) { throw new IllegalArgumentException(); } long[] trans = new long[size]; int[] wallOffsets = new int[size]; int[] standardOffsets = new int[size]; String[] nameKeys = new String[size]; Transition last = null; for (int i=0; i 4 && p.getMonths() < 8 && curNameKey.equals(zoneNameData[2]) && curNameKey.equals(zoneNameData[4])) { if (ZoneInfoCompiler.verbose()) { System.out.println("Fixing duplicate name key - " + nextNameKey); System.out.println(" - " + new DateTime(trans[i], chrono) + " - " + new DateTime(trans[i + 1], chrono)); } if (curOffset > nextOffset) { nameKeys[i] = (curNameKey + "-Summer").intern(); } else if (curOffset < nextOffset) { nameKeys[i + 1] = (nextNameKey + "-Summer").intern(); i++; } } } if (tailZone != null) { if (tailZone.iStartRecurrence.getNameKey() .equals(tailZone.iEndRecurrence.getNameKey())) { if (ZoneInfoCompiler.verbose()) { System.out.println("Fixing duplicate recurrent name key - " + tailZone.iStartRecurrence.getNameKey()); } if (tailZone.iStartRecurrence.getSaveMillis() > 0) { tailZone = new DSTZone( tailZone.getID(), tailZone.iStandardOffset, tailZone.iStartRecurrence.renameAppend("-Summer"), tailZone.iEndRecurrence); } else { tailZone = new DSTZone( tailZone.getID(), tailZone.iStandardOffset, tailZone.iStartRecurrence, tailZone.iEndRecurrence.renameAppend("-Summer")); } } } return new PrecalculatedZone ((outputID ? id : ""), trans, wallOffsets, standardOffsets, nameKeys, tailZone); } // All array fields have the same length. private final long[] iTransitions; private final int[] iWallOffsets; private final int[] iStandardOffsets; private final String[] iNameKeys; private final DSTZone iTailZone; /** * Constructor used ONLY for valid input, loaded via static methods. */ private PrecalculatedZone(String id, long[] transitions, int[] wallOffsets, int[] standardOffsets, String[] nameKeys, DSTZone tailZone) { super(id); iTransitions = transitions; iWallOffsets = wallOffsets; iStandardOffsets = standardOffsets; iNameKeys = nameKeys; iTailZone = tailZone; } public String getNameKey(long instant) { long[] transitions = iTransitions; int i = Arrays.binarySearch(transitions, instant); if (i >= 0) { return iNameKeys[i]; } i = ~i; if (i < transitions.length) { if (i > 0) { return iNameKeys[i - 1]; } return "UTC"; } if (iTailZone == null) { return iNameKeys[i - 1]; } return iTailZone.getNameKey(instant); } public int getOffset(long instant) { long[] transitions = iTransitions; int i = Arrays.binarySearch(transitions, instant); if (i >= 0) { return iWallOffsets[i]; } i = ~i; if (i < transitions.length) { if (i > 0) { return iWallOffsets[i - 1]; } return 0; } if (iTailZone == null) { return iWallOffsets[i - 1]; } return iTailZone.getOffset(instant); } public int getStandardOffset(long instant) { long[] transitions = iTransitions; int i = Arrays.binarySearch(transitions, instant); if (i >= 0) { return iStandardOffsets[i]; } i = ~i; if (i < transitions.length) { if (i > 0) { return iStandardOffsets[i - 1]; } return 0; } if (iTailZone == null) { return iStandardOffsets[i - 1]; } return iTailZone.getStandardOffset(instant); } public boolean isFixed() { return false; } public long nextTransition(long instant) { long[] transitions = iTransitions; int i = Arrays.binarySearch(transitions, instant); i = (i >= 0) ? (i + 1) : ~i; if (i < transitions.length) { return transitions[i]; } if (iTailZone == null) { return instant; } long end = transitions[transitions.length - 1]; if (instant < end) { instant = end; } return iTailZone.nextTransition(instant); } public long previousTransition(long instant) { long[] transitions = iTransitions; int i = Arrays.binarySearch(transitions, instant); if (i >= 0) { if (instant > Long.MIN_VALUE) { return instant - 1; } return instant; } i = ~i; if (i < transitions.length) { if (i > 0) { long prev = transitions[i - 1]; if (prev > Long.MIN_VALUE) { return prev - 1; } } return instant; } if (iTailZone != null) { long prev = iTailZone.previousTransition(instant); if (prev < instant) { return prev; } } long prev = transitions[i - 1]; if (prev > Long.MIN_VALUE) { return prev - 1; } return instant; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof PrecalculatedZone) { PrecalculatedZone other = (PrecalculatedZone)obj; return getID().equals(other.getID()) && Arrays.equals(iTransitions, other.iTransitions) && Arrays.equals(iNameKeys, other.iNameKeys) && Arrays.equals(iWallOffsets, other.iWallOffsets) && Arrays.equals(iStandardOffsets, other.iStandardOffsets) && ((iTailZone == null) ? (null == other.iTailZone) : (iTailZone.equals(other.iTailZone))); } return false; } public void writeTo(DataOutput out) throws IOException { int size = iTransitions.length; // Create unique string pool. Set poolSet = new HashSet(); for (int i=0; i 65535) { throw new UnsupportedOperationException("String pool is too large"); } String[] pool = new String[poolSize]; Iterator it = poolSet.iterator(); for (int i=0; it.hasNext(); i++) { pool[i] = it.next(); } // Write out the pool. out.writeShort(poolSize); for (int i=0; i 0) { double avg = distances / count; avg /= 24 * 60 * 60 * 1000; if (avg >= 25) { // Only bother caching if average distance between // transitions is at least 25 days. Why 25? // CachedDateTimeZone is more efficient if the distance // between transitions is large. With an average of 25, it // will on average perform about 2 tests per cache // hit. (49.7 / 25) is approximately 2. return true; } } return false; } } } joda-time-2.3/src/main/java/org/joda/time/tz/FixedDateTimeZone.java0000644000175000017500000000611511721223530024464 0ustar ebourgebourg/* * Copyright 2001-2005 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import org.joda.time.DateTimeZone; /** * Basic DateTimeZone implementation that has a fixed name key and offsets. *

* FixedDateTimeZone is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public final class FixedDateTimeZone extends DateTimeZone { private static final long serialVersionUID = -3513011772763289092L; private final String iNameKey; private final int iWallOffset; private final int iStandardOffset; public FixedDateTimeZone(String id, String nameKey, int wallOffset, int standardOffset) { super(id); iNameKey = nameKey; iWallOffset = wallOffset; iStandardOffset = standardOffset; } public String getNameKey(long instant) { return iNameKey; } public int getOffset(long instant) { return iWallOffset; } public int getStandardOffset(long instant) { return iStandardOffset; } public int getOffsetFromLocal(long instantLocal) { return iWallOffset; } public boolean isFixed() { return true; } public long nextTransition(long instant) { return instant; } public long previousTransition(long instant) { return instant; } /** * Override to return the correct timzone instance. * @since 1.5 */ public java.util.TimeZone toTimeZone() { String id = getID(); if (id.length() == 6 && (id.startsWith("+") || id.startsWith("-"))) { // standard format offset [+-]hh:mm // our ID is without any prefix, so we need to add the GMT back return java.util.TimeZone.getTimeZone("GMT" + getID()); } // unusual offset, so setup a SimpleTimeZone as best we can return new java.util.SimpleTimeZone(iWallOffset, getID()); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof FixedDateTimeZone) { FixedDateTimeZone other = (FixedDateTimeZone) obj; return getID().equals(other.getID()) && iStandardOffset == other.iStandardOffset && iWallOffset == other.iWallOffset; } return false; } public int hashCode() { return getID().hashCode() + 37 * iStandardOffset + 31 * iWallOffset; } } joda-time-2.3/src/main/java/org/joda/time/tz/ZoneInfoCompiler.java0000644000175000017500000007345612203434112024406 0ustar ebourgebourg/* * Copyright 2001-2013 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Map.Entry; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.MutableDateTime; import org.joda.time.chrono.ISOChronology; import org.joda.time.chrono.LenientChronology; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Compiles Olson ZoneInfo database files into binary files for each time zone * in the database. {@link DateTimeZoneBuilder} is used to construct and encode * compiled data files. {@link ZoneInfoProvider} loads the encoded files and * converts them back into {@link DateTimeZone} objects. *

* Although this tool is similar to zic, the binary formats are not * compatible. The latest Olson database files may be obtained * here. *

* ZoneInfoCompiler is mutable and not thread-safe, although the main method * may be safely invoked by multiple threads. * * @author Brian S O'Neill * @since 1.0 */ public class ZoneInfoCompiler { static DateTimeOfYear cStartOfYear; static Chronology cLenientISO; static ThreadLocal cVerbose = new ThreadLocal() { protected Boolean initialValue() { return Boolean.FALSE; } }; /** * Gets a flag indicating that verbose logging is required. * @return true to log verbosely */ public static boolean verbose() { return cVerbose.get(); } //----------------------------------------------------------------------- /** * Launches the ZoneInfoCompiler tool. * *

     * Usage: java org.joda.time.tz.ZoneInfoCompiler <options> <source files>
     * where possible options include:
     *   -src <directory>    Specify where to read source files
     *   -dst <directory>    Specify where to write generated files
     *   -verbose            Output verbosely (default false)
     * 
*/ public static void main(String[] args) throws Exception { if (args.length == 0) { printUsage(); return; } File inputDir = null; File outputDir = null; boolean verbose = false; int i; for (i=0; i= args.length) { printUsage(); return; } File[] sources = new File[args.length - i]; for (int j=0; i "); System.out.println("where possible options include:"); System.out.println(" -src Specify where to read source files"); System.out.println(" -dst Specify where to write generated files"); System.out.println(" -verbose Output verbosely (default false)"); } static DateTimeOfYear getStartOfYear() { if (cStartOfYear == null) { cStartOfYear = new DateTimeOfYear(); } return cStartOfYear; } static Chronology getLenientISOChronology() { if (cLenientISO == null) { cLenientISO = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); } return cLenientISO; } /** * @param zimap maps string ids to DateTimeZone objects. */ static void writeZoneInfoMap(DataOutputStream dout, Map zimap) throws IOException { // Build the string pool. Map idToIndex = new HashMap(zimap.size()); TreeMap indexToId = new TreeMap(); short count = 0; for (Entry entry : zimap.entrySet()) { String id = (String)entry.getKey(); if (!idToIndex.containsKey(id)) { Short index = Short.valueOf(count); idToIndex.put(id, index); indexToId.put(index, id); if (++count == 0) { throw new InternalError("Too many time zone ids"); } } id = ((DateTimeZone)entry.getValue()).getID(); if (!idToIndex.containsKey(id)) { Short index = Short.valueOf(count); idToIndex.put(id, index); indexToId.put(index, id); if (++count == 0) { throw new InternalError("Too many time zone ids"); } } } // Write the string pool, ordered by index. dout.writeShort(indexToId.size()); for (String id : indexToId.values()) { dout.writeUTF(id); } // Write the mappings. dout.writeShort(zimap.size()); for (Entry entry : zimap.entrySet()) { String id = entry.getKey(); dout.writeShort(idToIndex.get(id).shortValue()); id = entry.getValue().getID(); dout.writeShort(idToIndex.get(id).shortValue()); } } static int parseYear(String str, int def) { str = str.toLowerCase(); if (str.equals("minimum") || str.equals("min")) { return Integer.MIN_VALUE; } else if (str.equals("maximum") || str.equals("max")) { return Integer.MAX_VALUE; } else if (str.equals("only")) { return def; } return Integer.parseInt(str); } static int parseMonth(String str) { DateTimeField field = ISOChronology.getInstanceUTC().monthOfYear(); return field.get(field.set(0, str, Locale.ENGLISH)); } static int parseDayOfWeek(String str) { DateTimeField field = ISOChronology.getInstanceUTC().dayOfWeek(); return field.get(field.set(0, str, Locale.ENGLISH)); } static String parseOptional(String str) { return (str.equals("-")) ? null : str; } static int parseTime(String str) { DateTimeFormatter p = ISODateTimeFormat.hourMinuteSecondFraction(); MutableDateTime mdt = new MutableDateTime(0, getLenientISOChronology()); int pos = 0; if (str.startsWith("-")) { pos = 1; } int newPos = p.parseInto(mdt, str, pos); if (newPos == ~pos) { throw new IllegalArgumentException(str); } int millis = (int)mdt.getMillis(); if (pos == 1) { millis = -millis; } return millis; } static char parseZoneChar(char c) { switch (c) { case 's': case 'S': // Standard time return 's'; case 'u': case 'U': case 'g': case 'G': case 'z': case 'Z': // UTC return 'u'; case 'w': case 'W': default: // Wall time return 'w'; } } /** * @return false if error. */ static boolean test(String id, DateTimeZone tz) { if (!id.equals(tz.getID())) { return true; } // Test to ensure that reported transitions are not duplicated. long millis = ISOChronology.getInstanceUTC().year().set(0, 1850); long end = ISOChronology.getInstanceUTC().year().set(0, 2050); int offset = tz.getOffset(millis); String key = tz.getNameKey(millis); List transitions = new ArrayList(); while (true) { long next = tz.nextTransition(millis); if (next == millis || next > end) { break; } millis = next; int nextOffset = tz.getOffset(millis); String nextKey = tz.getNameKey(millis); if (offset == nextOffset && key.equals(nextKey)) { System.out.println("*d* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC())); return false; } if (nextKey == null || (nextKey.length() < 3 && !"??".equals(nextKey))) { System.out.println("*s* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC()) + ", nameKey=" + nextKey); return false; } transitions.add(Long.valueOf(millis)); offset = nextOffset; key = nextKey; } // Now verify that reverse transitions match up. millis = ISOChronology.getInstanceUTC().year().set(0, 2050); end = ISOChronology.getInstanceUTC().year().set(0, 1850); for (int i=transitions.size(); --i>= 0; ) { long prev = tz.previousTransition(millis); if (prev == millis || prev < end) { break; } millis = prev; long trans = transitions.get(i).longValue(); if (trans - 1 != millis) { System.out.println("*r* Error in " + tz.getID() + " " + new DateTime(millis, ISOChronology.getInstanceUTC()) + " != " + new DateTime(trans - 1, ISOChronology.getInstanceUTC())); return false; } } return true; } // Maps names to RuleSets. private Map iRuleSets; // List of Zone objects. private List iZones; // List String pairs to link. private List iLinks; public ZoneInfoCompiler() { iRuleSets = new HashMap(); iZones = new ArrayList(); iLinks = new ArrayList(); } /** * Returns a map of ids to DateTimeZones. * * @param outputDir optional directory to write compiled data files to * @param sources optional list of source files to parse */ public Map compile(File outputDir, File[] sources) throws IOException { if (sources != null) { for (int i=0; i map = new TreeMap(); System.out.println("Writing zoneinfo files"); for (int i=0; i 0) { System.out.println("Cannot find time zone '" + id + "' to link alias '" + alias + "' to"); } } else { map.put(alias, tz); } } } if (outputDir != null) { System.out.println("Writing ZoneInfoMap"); File file = new File(outputDir, "ZoneInfoMap"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(file); DataOutputStream dout = new DataOutputStream(out); try { // Sort and filter out any duplicates that match case. Map zimap = new TreeMap(String.CASE_INSENSITIVE_ORDER); zimap.putAll(map); writeZoneInfoMap(dout, zimap); } finally { dout.close(); } } return map; } public void parseDataFile(BufferedReader in) throws IOException { Zone zone = null; String line; while ((line = in.readLine()) != null) { String trimmed = line.trim(); if (trimmed.length() == 0 || trimmed.charAt(0) == '#') { continue; } int index = line.indexOf('#'); if (index >= 0) { line = line.substring(0, index); } //System.out.println(line); StringTokenizer st = new StringTokenizer(line, " \t"); if (Character.isWhitespace(line.charAt(0)) && st.hasMoreTokens()) { if (zone != null) { // Zone continuation zone.chain(st); } continue; } else { if (zone != null) { iZones.add(zone); } zone = null; } if (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equalsIgnoreCase("Rule")) { Rule r = new Rule(st); RuleSet rs = iRuleSets.get(r.iName); if (rs == null) { rs = new RuleSet(r); iRuleSets.put(r.iName, rs); } else { rs.addRule(r); } } else if (token.equalsIgnoreCase("Zone")) { zone = new Zone(st); } else if (token.equalsIgnoreCase("Link")) { iLinks.add(st.nextToken()); iLinks.add(st.nextToken()); } else { System.out.println("Unknown line: " + line); } } } if (zone != null) { iZones.add(zone); } } static class DateTimeOfYear { public final int iMonthOfYear; public final int iDayOfMonth; public final int iDayOfWeek; public final boolean iAdvanceDayOfWeek; public final int iMillisOfDay; public final char iZoneChar; DateTimeOfYear() { iMonthOfYear = 1; iDayOfMonth = 1; iDayOfWeek = 0; iAdvanceDayOfWeek = false; iMillisOfDay = 0; iZoneChar = 'w'; } DateTimeOfYear(StringTokenizer st) { int month = 1; int day = 1; int dayOfWeek = 0; int millis = 0; boolean advance = false; char zoneChar = 'w'; if (st.hasMoreTokens()) { month = parseMonth(st.nextToken()); if (st.hasMoreTokens()) { String str = st.nextToken(); if (str.startsWith("last")) { day = -1; dayOfWeek = parseDayOfWeek(str.substring(4)); advance = false; } else { try { day = Integer.parseInt(str); dayOfWeek = 0; advance = false; } catch (NumberFormatException e) { int index = str.indexOf(">="); if (index > 0) { day = Integer.parseInt(str.substring(index + 2)); dayOfWeek = parseDayOfWeek(str.substring(0, index)); advance = true; } else { index = str.indexOf("<="); if (index > 0) { day = Integer.parseInt(str.substring(index + 2)); dayOfWeek = parseDayOfWeek(str.substring(0, index)); advance = false; } else { throw new IllegalArgumentException(str); } } } } if (st.hasMoreTokens()) { str = st.nextToken(); zoneChar = parseZoneChar(str.charAt(str.length() - 1)); if (str.equals("24:00")) { LocalDate date = (day == -1 ? new LocalDate(2001, month, 1).plusMonths(1) : new LocalDate(2001, month, day).plusDays(1)); advance = (day != -1); month = date.getMonthOfYear(); day = date.getDayOfMonth(); dayOfWeek = ((dayOfWeek - 1 + 1) % 7) + 1; } else { millis = parseTime(str); } } } } iMonthOfYear = month; iDayOfMonth = day; iDayOfWeek = dayOfWeek; iAdvanceDayOfWeek = advance; iMillisOfDay = millis; iZoneChar = zoneChar; } /** * Adds a recurring savings rule to the builder. */ public void addRecurring(DateTimeZoneBuilder builder, String nameKey, int saveMillis, int fromYear, int toYear) { builder.addRecurringSavings(nameKey, saveMillis, fromYear, toYear, iZoneChar, iMonthOfYear, iDayOfMonth, iDayOfWeek, iAdvanceDayOfWeek, iMillisOfDay); } /** * Adds a cutover to the builder. */ public void addCutover(DateTimeZoneBuilder builder, int year) { builder.addCutover(year, iZoneChar, iMonthOfYear, iDayOfMonth, iDayOfWeek, iAdvanceDayOfWeek, iMillisOfDay); } public String toString() { return "MonthOfYear: " + iMonthOfYear + "\n" + "DayOfMonth: " + iDayOfMonth + "\n" + "DayOfWeek: " + iDayOfWeek + "\n" + "AdvanceDayOfWeek: " + iAdvanceDayOfWeek + "\n" + "MillisOfDay: " + iMillisOfDay + "\n" + "ZoneChar: " + iZoneChar + "\n"; } } private static class Rule { public final String iName; public final int iFromYear; public final int iToYear; public final String iType; public final DateTimeOfYear iDateTimeOfYear; public final int iSaveMillis; public final String iLetterS; Rule(StringTokenizer st) { iName = st.nextToken().intern(); iFromYear = parseYear(st.nextToken(), 0); iToYear = parseYear(st.nextToken(), iFromYear); if (iToYear < iFromYear) { throw new IllegalArgumentException(); } iType = parseOptional(st.nextToken()); iDateTimeOfYear = new DateTimeOfYear(st); iSaveMillis = parseTime(st.nextToken()); iLetterS = parseOptional(st.nextToken()); } /** * Adds a recurring savings rule to the builder. */ public void addRecurring(DateTimeZoneBuilder builder, String nameFormat) { String nameKey = formatName(nameFormat); iDateTimeOfYear.addRecurring (builder, nameKey, iSaveMillis, iFromYear, iToYear); } private String formatName(String nameFormat) { int index = nameFormat.indexOf('/'); if (index > 0) { if (iSaveMillis == 0) { // Extract standard name. return nameFormat.substring(0, index).intern(); } else { return nameFormat.substring(index + 1).intern(); } } index = nameFormat.indexOf("%s"); if (index < 0) { return nameFormat; } String left = nameFormat.substring(0, index); String right = nameFormat.substring(index + 2); String name; if (iLetterS == null) { name = left.concat(right); } else { name = left + iLetterS + right; } return name.intern(); } public String toString() { return "[Rule]\n" + "Name: " + iName + "\n" + "FromYear: " + iFromYear + "\n" + "ToYear: " + iToYear + "\n" + "Type: " + iType + "\n" + iDateTimeOfYear + "SaveMillis: " + iSaveMillis + "\n" + "LetterS: " + iLetterS + "\n"; } } private static class RuleSet { private List iRules; RuleSet(Rule rule) { iRules = new ArrayList(); iRules.add(rule); } void addRule(Rule rule) { if (!(rule.iName.equals(iRules.get(0).iName))) { throw new IllegalArgumentException("Rule name mismatch"); } iRules.add(rule); } /** * Adds recurring savings rules to the builder. */ public void addRecurring(DateTimeZoneBuilder builder, String nameFormat) { for (int i=0; i ruleSets) { addToBuilder(this, builder, ruleSets); } private static void addToBuilder(Zone zone, DateTimeZoneBuilder builder, Map ruleSets) { for (; zone != null; zone = zone.iNext) { builder.setStandardOffset(zone.iOffsetMillis); if (zone.iRules == null) { builder.setFixedSavings(zone.iFormat, 0); } else { try { // Check if iRules actually just refers to a savings. int saveMillis = parseTime(zone.iRules); builder.setFixedSavings(zone.iFormat, saveMillis); } catch (Exception e) { RuleSet rs = ruleSets.get(zone.iRules); if (rs == null) { throw new IllegalArgumentException ("Rules not found: " + zone.iRules); } rs.addRecurring(builder, zone.iFormat); } } if (zone.iUntilYear == Integer.MAX_VALUE) { break; } zone.iUntilDateTimeOfYear.addCutover(builder, zone.iUntilYear); } } public String toString() { String str = "[Zone]\n" + "Name: " + iName + "\n" + "OffsetMillis: " + iOffsetMillis + "\n" + "Rules: " + iRules + "\n" + "Format: " + iFormat + "\n" + "UntilYear: " + iUntilYear + "\n" + iUntilDateTimeOfYear; if (iNext == null) { return str; } return str + "...\n" + iNext.toString(); } } } joda-time-2.3/src/main/java/org/joda/time/tz/Provider.java0000644000175000017500000000231311564251363022754 0ustar ebourgebourg/* * Copyright 2001-2009 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.tz; import java.util.Set; import org.joda.time.DateTimeZone; /** * Service provider factory for time zones. * * @author Brian S O'Neill * @since 1.0 */ public interface Provider { /** * Retrieves a DateTimeZone for the given id. All providers must at * least support id "UTC". * * @return null if not found */ DateTimeZone getZone(String id); /** * Returns an unmodifiable set of ids. All providers must at least * support id "UTC". */ Set getAvailableIDs(); } joda-time-2.3/src/main/java/org/joda/time/tz/package.html0000644000175000017500000000200011564251363022571 0ustar ebourgebourg org.joda.time.tz package

Implementation package supporting the time zones.

Provides support for implementing time zones. {@link org.joda.time.DateTimeZone} uses these classes internally, but most applications need not use them directly.

joda-time-2.3/src/main/java/org/joda/time/Period.java0000644000175000017500000021604112162055431021745 0ustar ebourgebourg/* * Copyright 2001-2010 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import java.io.Serializable; import org.joda.convert.FromString; import org.joda.time.base.BasePeriod; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * An immutable time period specifying a set of duration field values. *

* A time period is divided into a number of fields, such as hours and seconds. * Which fields are supported is defined by the PeriodType class. * The default is the standard period type, which supports years, months, weeks, days, * hours, minutes, seconds and millis. *

* When this time period is added to an instant, the effect is of adding each field in turn. * As a result, this takes into account daylight savings time. * Adding a time period of 1 day to the day before daylight savings starts will only add * 23 hours rather than 24 to ensure that the time remains the same. * If this is not the behaviour you want, then see {@link Duration}. *

* The definition of a period also affects the equals method. A period of 1 * day is not equal to a period of 24 hours, nor 1 hour equal to 60 minutes. * This is because periods represent an abstracted definition of a time period * (eg. a day may not actually be 24 hours, it might be 23 or 25 at daylight * savings boundary). To compare the actual duration of two periods, convert * both to durations using toDuration, an operation that emphasises that the * result may differ according to the date you choose. *

* Period is thread-safe and immutable, provided that the PeriodType is as well. * All standard PeriodType classes supplied are thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 * @see MutablePeriod */ public final class Period extends BasePeriod implements ReadablePeriod, Serializable { /** * A period of zero length and standard period type. * @since 1.4 */ public static final Period ZERO = new Period(); /** Serialization version */ private static final long serialVersionUID = 741052353876488155L; //----------------------------------------------------------------------- /** * Parses a {@code Period} from the specified string. *

* This uses {@link ISOPeriodFormat#standard()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static Period parse(String str) { return parse(str, ISOPeriodFormat.standard()); } /** * Parses a {@code Period} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static Period parse(String str, PeriodFormatter formatter) { return formatter.parsePeriod(str); } //----------------------------------------------------------------------- /** * Create a period with a specified number of years. *

* The standard period type is used, thus you can add other fields such * as months or days using the withXxx() methods. * For example, Period.years(2).withMonths(6); *

* If you want a year-based period that cannot have other fields added, * then you should consider using {@link Years}. * * @param years the amount of years in this period * @return the period */ public static Period years(int years) { return new Period(new int[] {years, 0, 0, 0, 0, 0, 0, 0, 0}, PeriodType.standard()); } /** * Create a period with a specified number of months. *

* The standard period type is used, thus you can add other fields such * as years or days using the withXxx() methods. * For example, Period.months(2).withDays(6); *

* If you want a month-based period that cannot have other fields added, * then you should consider using {@link Months}. * * @param months the amount of months in this period * @return the period */ public static Period months(int months) { return new Period(new int[] {0, months, 0, 0, 0, 0, 0, 0}, PeriodType.standard()); } /** * Create a period with a specified number of weeks. *

* The standard period type is used, thus you can add other fields such * as months or days using the withXxx() methods. * For example, Period.weeks(2).withDays(6); *

* If you want a week-based period that cannot have other fields added, * then you should consider using {@link Weeks}. * * @param weeks the amount of weeks in this period * @return the period */ public static Period weeks(int weeks) { return new Period(new int[] {0, 0, weeks, 0, 0, 0, 0, 0}, PeriodType.standard()); } /** * Create a period with a specified number of days. *

* The standard period type is used, thus you can add other fields such * as months or weeks using the withXxx() methods. * For example, Period.days(2).withHours(6); *

* If you want a day-based period that cannot have other fields added, * then you should consider using {@link Days}. * * @param days the amount of days in this period * @return the period */ public static Period days(int days) { return new Period(new int[] {0, 0, 0, days, 0, 0, 0, 0}, PeriodType.standard()); } /** * Create a period with a specified number of hours. *

* The standard period type is used, thus you can add other fields such * as months or days using the withXxx() methods. * For example, Period.hours(2).withMinutes(30); *

* If you want a hour-based period that cannot have other fields added, * then you should consider using {@link Hours}. * * @param hours the amount of hours in this period * @return the period */ public static Period hours(int hours) { return new Period(new int[] {0, 0, 0, 0, hours, 0, 0, 0}, PeriodType.standard()); } /** * Create a period with a specified number of minutes. *

* The standard period type is used, thus you can add other fields such * as days or hours using the withXxx() methods. * For example, Period.minutes(2).withSeconds(30); *

* If you want a minute-based period that cannot have other fields added, * then you should consider using {@link Minutes}. * * @param minutes the amount of minutes in this period * @return the period */ public static Period minutes(int minutes) { return new Period(new int[] {0, 0, 0, 0, 0, minutes, 0, 0}, PeriodType.standard()); } /** * Create a period with a specified number of seconds. *

* The standard period type is used, thus you can add other fields such * as days or hours using the withXxx() methods. * For example, Period.seconds(2).withMillis(30); *

* If you want a second-based period that cannot have other fields added, * then you should consider using {@link Seconds}. * * @param seconds the amount of seconds in this period * @return the period */ public static Period seconds(int seconds) { return new Period(new int[] {0, 0, 0, 0, 0, 0, seconds, 0}, PeriodType.standard()); } /** * Create a period with a specified number of millis. *

* The standard period type is used, thus you can add other fields such * as days or hours using the withXxx() methods. * For example, Period.millis(20).withSeconds(30); * * @param millis the amount of millis in this period * @return the period */ public static Period millis(int millis) { return new Period(new int[] {0, 0, 0, 0, 0, 0, 0, millis}, PeriodType.standard()); } //----------------------------------------------------------------------- /** * Creates a period from two partially specified times, calculating * by field difference. *

* The two partials must contain the same fields, thus you can specify * two LocalDate objects, or two LocalTime objects, * but not one of each. Also, the partial may not contain overlapping * fields, such as dayOfWeek and dayOfMonth. *

* Calculation by field difference works by extracting the difference * one field at a time and not wrapping into other fields. * Thus 2005-06-09/2007-04-12 will yield P1Y-2M3D. *

* For example, you have an event that always runs from the 27th of * each month to the 2nd of the next month. If you calculate this * period using a standard constructor, then you will get between * P3D and P6D depending on the month. If you use this method, then * you will get P1M-25D. This field-difference based period can * be successfully applied to each month of the year to obtain the * correct end date for a given start date. * * @param start the start of the period, must not be null * @param end the end of the period, must not be null * @throws IllegalArgumentException if the partials are null or invalid * @since 1.1 */ public static Period fieldDifference(ReadablePartial start, ReadablePartial end) { if (start == null || end == null) { throw new IllegalArgumentException("ReadablePartial objects must not be null"); } if (start.size() != end.size()) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } DurationFieldType[] types = new DurationFieldType[start.size()]; int[] values = new int[start.size()]; for (int i = 0, isize = start.size(); i < isize; i++) { if (start.getFieldType(i) != end.getFieldType(i)) { throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields"); } types[i] = start.getFieldType(i).getDurationType(); if (i > 0 && types[i - 1] == types[i]) { throw new IllegalArgumentException("ReadablePartial objects must not have overlapping fields"); } values[i] = end.getValue(i) - start.getValue(i); } return new Period(values, PeriodType.forFields(types)); } //----------------------------------------------------------------------- /** * Creates a new empty period with the standard set of fields. *

* One way to initialise a period is as follows: *

     * Period = new Period().withYears(6).withMonths(3).withSeconds(23);
     * 
* Bear in mind that this creates four period instances in total, three of * which are immediately discarded. * The alterative is more efficient, but less readable: *
     * Period = new Period(6, 3, 0, 0, 0, 0, 23, 0);
     * 
* The following is also slightly less wasteful: *
     * Period = Period.years(6).withMonths(3).withSeconds(23);
     * 
*/ public Period() { super(0L, null, null); } /** * Create a period from a set of field values using the standard set of fields. * Note that the parameters specify the time fields hours, minutes, * seconds and millis, not the date fields. * * @param hours amount of hours in this period * @param minutes amount of minutes in this period * @param seconds amount of seconds in this period * @param millis amount of milliseconds in this period */ public Period(int hours, int minutes, int seconds, int millis) { super(0, 0, 0, 0, hours, minutes, seconds, millis, PeriodType.standard()); } /** * Create a period from a set of field values using the standard set of fields. * * @param years amount of years in this period * @param months amount of months in this period * @param weeks amount of weeks in this period * @param days amount of days in this period * @param hours amount of hours in this period * @param minutes amount of minutes in this period * @param seconds amount of seconds in this period * @param millis amount of milliseconds in this period */ public Period(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { super(years, months, weeks, days, hours, minutes, seconds, millis, PeriodType.standard()); } /** * Create a period from a set of field values. *

* There is usually little need to use this constructor. * The period type is used primarily to define how to split an interval into a period. * As this constructor already is split, the period type does no real work. * * @param years amount of years in this period, which must be zero if unsupported * @param months amount of months in this period, which must be zero if unsupported * @param weeks amount of weeks in this period, which must be zero if unsupported * @param days amount of days in this period, which must be zero if unsupported * @param hours amount of hours in this period, which must be zero if unsupported * @param minutes amount of minutes in this period, which must be zero if unsupported * @param seconds amount of seconds in this period, which must be zero if unsupported * @param millis amount of milliseconds in this period, which must be zero if unsupported * @param type which set of fields this period supports, null means AllType * @throws IllegalArgumentException if an unsupported field's value is non-zero */ public Period(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis, PeriodType type) { super(years, months, weeks, days, hours, minutes, seconds, millis, type); } /** * Creates a period from the given millisecond duration using the standard * set of fields. *

* Only precise fields in the period type will be used. * For the standard period type this is the time fields only. * Thus the year, month, week and day fields will not be populated. *

* If the duration is small, less than one day, then this method will perform * as you might expect and split the fields evenly. *

* If the duration is larger than one day then all the remaining duration will * be stored in the largest available precise field, hours in this case. *

* For example, a duration equal to (365 + 60 + 5) days will be converted to * ((365 + 60 + 5) * 24) hours by this constructor. *

* For more control over the conversion process, you have two options: *

    *
  • convert the duration to an {@link Interval}, and from there obtain the period *
  • specify a period type that contains precise definitions of the day and larger * fields, such as UTC *
* * @param duration the duration, in milliseconds */ public Period(long duration) { super(duration); } /** * Creates a period from the given millisecond duration. *

* Only precise fields in the period type will be used. * Imprecise fields will not be populated. *

* If the duration is small then this method will perform * as you might expect and split the fields evenly. *

* If the duration is large then all the remaining duration will * be stored in the largest available precise field. * For details as to which fields are precise, review the period type javadoc. * * @param duration the duration, in milliseconds * @param type which set of fields this period supports, null means standard */ public Period(long duration, PeriodType type) { super(duration, type, null); } /** * Creates a period from the given millisecond duration using the standard * set of fields. *

* Only precise fields in the period type will be used. * Imprecise fields will not be populated. *

* If the duration is small then this method will perform * as you might expect and split the fields evenly. *

* If the duration is large then all the remaining duration will * be stored in the largest available precise field. * For details as to which fields are precise, review the period type javadoc. * * @param duration the duration, in milliseconds * @param chronology the chronology to use to split the duration, null means ISO default */ public Period(long duration, Chronology chronology) { super(duration, null, chronology); } /** * Creates a period from the given millisecond duration. *

* Only precise fields in the period type will be used. * Imprecise fields will not be populated. *

* If the duration is small then this method will perform * as you might expect and split the fields evenly. *

* If the duration is large then all the remaining duration will * be stored in the largest available precise field. * For details as to which fields are precise, review the period type javadoc. * * @param duration the duration, in milliseconds * @param type which set of fields this period supports, null means standard * @param chronology the chronology to use to split the duration, null means ISO default */ public Period(long duration, PeriodType type, Chronology chronology) { super(duration, type, chronology); } /** * Creates a period from the given interval endpoints using the standard * set of fields. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ public Period(long startInstant, long endInstant) { super(startInstant, endInstant, null, null); } /** * Creates a period from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param type which set of fields this period supports, null means standard */ public Period(long startInstant, long endInstant, PeriodType type) { super(startInstant, endInstant, type, null); } /** * Creates a period from the given interval endpoints using the standard * set of fields. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param chrono the chronology to use, null means ISO in default zone */ public Period(long startInstant, long endInstant, Chronology chrono) { super(startInstant, endInstant, null, chrono); } /** * Creates a period from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @param type which set of fields this period supports, null means standard * @param chrono the chronology to use, null means ISO in default zone */ public Period(long startInstant, long endInstant, PeriodType type, Chronology chrono) { super(startInstant, endInstant, type, chrono); } /** * Creates a period between the given instants using the standard set of fields. *

* Most calculations performed by this method have obvious results. * The special case is where the calculation is from a "long" month to a "short" month. * Here, the result favours increasing the months field rather than the days. * For example, 2013-01-31 to 2013-02-28 is treated as one whole month. * By contrast, 2013-01-31 to 2013-03-30 is treated as one month and 30 days * (exposed as 4 weeks and 2 days). * The results are explained by considering that the start date plus the * calculated period result in the end date. * * @param startInstant interval start, null means now * @param endInstant interval end, null means now */ public Period(ReadableInstant startInstant, ReadableInstant endInstant) { super(startInstant, endInstant, null); } /** * Creates a period between the given instants. *

* Most calculations performed by this method have obvious results. * The special case is where the calculation is from a "long" month to a "short" month. * Here, the result favours increasing the months field rather than the days. * For example, 2013-01-31 to 2013-02-28 is treated as one whole month. * By contrast, 2013-01-31 to 2013-03-30 is treated as one month and 30 days. * The results are explained by considering that the start date plus the * calculated period result in the end date. * * @param startInstant interval start, null means now * @param endInstant interval end, null means now * @param type which set of fields this period supports, null means standard */ public Period(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) { super(startInstant, endInstant, type); } /** * Creates a period from two partially specified times. *

* The two partials must contain the same fields, thus you can specify * two LocalDate objects, or two LocalTime objects, * but not one of each. * As these are Partial objects, time zones have no effect on the result. *

* The two partials must also both be contiguous - see * {@link DateTimeUtils#isContiguous(ReadablePartial)} for a definition. * Both LocalDate and LocalTime are contiguous. *

* Most calculations performed by this method have obvious results. * The special case is where the calculation is from a "long" month to a "short" month. * Here, the result favours increasing the months field rather than the days. * For example, 2013-01-31 to 2013-02-28 is treated as one whole month. * By contrast, 2013-01-31 to 2013-03-30 is treated as one month and 30 days * (exposed as 4 weeks and 2 days). * The results are explained by considering that the start date plus the * calculated period result in the end date. *

* An alternative way of constructing a Period from two Partials * is {@link #fieldDifference(ReadablePartial, ReadablePartial)}. * That method handles all kinds of partials. * * @param start the start of the period, must not be null * @param end the end of the period, must not be null * @throws IllegalArgumentException if the partials are null or invalid * @since 1.1 */ public Period(ReadablePartial start, ReadablePartial end) { super(start, end, null); } /** * Creates a period from two partially specified times. *

* The two partials must contain the same fields, thus you can specify * two LocalDate objects, or two LocalTime objects, * but not one of each. * As these are Partial objects, time zones have no effect on the result. *

* The two partials must also both be contiguous - see * {@link DateTimeUtils#isContiguous(ReadablePartial)} for a definition. * Both LocalDate and LocalTime are contiguous. *

* Most calculations performed by this method have obvious results. * The special case is where the calculation is from a "long" month to a "short" month. * Here, the result favours increasing the months field rather than the days. * For example, 2013-01-31 to 2013-02-28 is treated as one whole month. * By contrast, 2013-01-31 to 2013-03-30 is treated as one month and 30 days. * The results are explained by considering that the start date plus the * calculated period result in the end date. *

* An alternative way of constructing a Period from two Partials * is {@link #fieldDifference(ReadablePartial, ReadablePartial)}. * That method handles all kinds of partials. * * @param start the start of the period, must not be null * @param end the end of the period, must not be null * @param type which set of fields this period supports, null means standard * @throws IllegalArgumentException if the partials are null or invalid * @since 1.1 */ public Period(ReadablePartial start, ReadablePartial end, PeriodType type) { super(start, end, type); } /** * Creates a period from the given start point and the duration. * * @param startInstant the interval start, null means now * @param duration the duration of the interval, null means zero-length */ public Period(ReadableInstant startInstant, ReadableDuration duration) { super(startInstant, duration, null); } /** * Creates a period from the given start point and the duration. * * @param startInstant the interval start, null means now * @param duration the duration of the interval, null means zero-length * @param type which set of fields this period supports, null means standard */ public Period(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { super(startInstant, duration, type); } /** * Creates a period from the given duration and end point. * * @param duration the duration of the interval, null means zero-length * @param endInstant the interval end, null means now */ public Period(ReadableDuration duration, ReadableInstant endInstant) { super(duration, endInstant, null); } /** * Creates a period from the given duration and end point. * * @param duration the duration of the interval, null means zero-length * @param endInstant the interval end, null means now * @param type which set of fields this period supports, null means standard */ public Period(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) { super(duration, endInstant, type); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public Period(Object period) { super(period, null, null); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @param type which set of fields this period supports, null means use converter * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public Period(Object period, PeriodType type) { super(period, type, null); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @param chrono the chronology to use, null means ISO in default zone * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public Period(Object period, Chronology chrono) { super(period, null, chrono); } /** * Creates a period by converting or copying from another object. *

* The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadablePeriod, ReadableInterval and String. * The String formats are described by {@link ISOPeriodFormat#standard()}. * * @param period period to convert * @param type which set of fields this period supports, null means use converter * @param chrono the chronology to use, null means ISO in default zone * @throws IllegalArgumentException if period is invalid * @throws UnsupportedOperationException if an unsupported field's value is non-zero */ public Period(Object period, PeriodType type, Chronology chrono) { super(period, type, chrono); } /** * Constructor used when we trust ourselves. * * @param values the values to use, not null, not cloned * @param type which set of fields this period supports, not null */ private Period(int[] values, PeriodType type) { super(values, type); } //----------------------------------------------------------------------- /** * Get this period as an immutable Period object * by returning this. * * @return this */ public Period toPeriod() { return this; } //----------------------------------------------------------------------- /** * Gets the years field part of the period. * * @return the number of years in the period, zero if unsupported */ public int getYears() { return getPeriodType().getIndexedField(this, PeriodType.YEAR_INDEX); } /** * Gets the months field part of the period. * * @return the number of months in the period, zero if unsupported */ public int getMonths() { return getPeriodType().getIndexedField(this, PeriodType.MONTH_INDEX); } /** * Gets the weeks field part of the period. * * @return the number of weeks in the period, zero if unsupported */ public int getWeeks() { return getPeriodType().getIndexedField(this, PeriodType.WEEK_INDEX); } /** * Gets the days field part of the period. * * @return the number of days in the period, zero if unsupported */ public int getDays() { return getPeriodType().getIndexedField(this, PeriodType.DAY_INDEX); } //----------------------------------------------------------------------- /** * Gets the hours field part of the period. * * @return the number of hours in the period, zero if unsupported */ public int getHours() { return getPeriodType().getIndexedField(this, PeriodType.HOUR_INDEX); } /** * Gets the minutes field part of the period. * * @return the number of minutes in the period, zero if unsupported */ public int getMinutes() { return getPeriodType().getIndexedField(this, PeriodType.MINUTE_INDEX); } /** * Gets the seconds field part of the period. * * @return the number of seconds in the period, zero if unsupported */ public int getSeconds() { return getPeriodType().getIndexedField(this, PeriodType.SECOND_INDEX); } /** * Gets the millis field part of the period. * * @return the number of millis in the period, zero if unsupported */ public int getMillis() { return getPeriodType().getIndexedField(this, PeriodType.MILLI_INDEX); } //----------------------------------------------------------------------- /** * Creates a new Period instance with the same field values but * different PeriodType. *

* This period instance is immutable and unaffected by this method call. * * @param type the period type to use, null means standard * @return the new period instance * @throws IllegalArgumentException if the new period won't accept all of the current fields */ public Period withPeriodType(PeriodType type) { type = DateTimeUtils.getPeriodType(type); if (type.equals(getPeriodType())) { return this; } return new Period(this, type); } /** * Creates a new Period instance with the fields from the specified period * copied on top of those from this period. *

* This period instance is immutable and unaffected by this method call. * * @param period the period to copy from, null ignored * @return the new period instance * @throws IllegalArgumentException if a field type is unsupported */ public Period withFields(ReadablePeriod period) { if (period == null) { return this; } int[] newValues = getValues(); // cloned newValues = super.mergePeriodInto(newValues, period); return new Period(newValues, getPeriodType()); } //----------------------------------------------------------------------- /** * Creates a new Period instance with the specified field set to a new value. *

* This period instance is immutable and unaffected by this method call. * * @param field the field to set, not null * @param value the value to set to * @return the new period instance * @throws IllegalArgumentException if the field type is null or unsupported */ public Period withField(DurationFieldType field, int value) { if (field == null) { throw new IllegalArgumentException("Field must not be null"); } int[] newValues = getValues(); // cloned super.setFieldInto(newValues, field, value); return new Period(newValues, getPeriodType()); } /** * Creates a new Period instance with the valueToAdd added to the specified field. *

* This period instance is immutable and unaffected by this method call. * * @param field the field to set, not null * @param value the value to add * @return the new period instance * @throws IllegalArgumentException if the field type is null or unsupported */ public Period withFieldAdded(DurationFieldType field, int value) { if (field == null) { throw new IllegalArgumentException("Field must not be null"); } if (value == 0) { return this; } int[] newValues = getValues(); // cloned super.addFieldInto(newValues, field, value); return new Period(newValues, getPeriodType()); } //----------------------------------------------------------------------- /** * Returns a new period with the specified number of years. *

* This period instance is immutable and unaffected by this method call. * * @param years the amount of years to add, may be negative * @return the new period with the increased years * @throws UnsupportedOperationException if the field is not supported */ public Period withYears(int years) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.YEAR_INDEX, values, years); return new Period(values, getPeriodType()); } /** * Returns a new period with the specified number of months. *

* This period instance is immutable and unaffected by this method call. * * @param months the amount of months to add, may be negative * @return the new period with the increased months * @throws UnsupportedOperationException if the field is not supported */ public Period withMonths(int months) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.MONTH_INDEX, values, months); return new Period(values, getPeriodType()); } /** * Returns a new period with the specified number of weeks. *

* This period instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to add, may be negative * @return the new period with the increased weeks * @throws UnsupportedOperationException if the field is not supported */ public Period withWeeks(int weeks) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.WEEK_INDEX, values, weeks); return new Period(values, getPeriodType()); } /** * Returns a new period with the specified number of days. *

* This period instance is immutable and unaffected by this method call. * * @param days the amount of days to add, may be negative * @return the new period with the increased days * @throws UnsupportedOperationException if the field is not supported */ public Period withDays(int days) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.DAY_INDEX, values, days); return new Period(values, getPeriodType()); } /** * Returns a new period with the specified number of hours. *

* This period instance is immutable and unaffected by this method call. * * @param hours the amount of hours to add, may be negative * @return the new period with the increased hours * @throws UnsupportedOperationException if the field is not supported */ public Period withHours(int hours) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.HOUR_INDEX, values, hours); return new Period(values, getPeriodType()); } /** * Returns a new period with the specified number of minutes. *

* This period instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to add, may be negative * @return the new period with the increased minutes * @throws UnsupportedOperationException if the field is not supported */ public Period withMinutes(int minutes) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.MINUTE_INDEX, values, minutes); return new Period(values, getPeriodType()); } /** * Returns a new period with the specified number of seconds. *

* This period instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to add, may be negative * @return the new period with the increased seconds * @throws UnsupportedOperationException if the field is not supported */ public Period withSeconds(int seconds) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.SECOND_INDEX, values, seconds); return new Period(values, getPeriodType()); } /** * Returns a new period with the specified number of millis. *

* This period instance is immutable and unaffected by this method call. * * @param millis the amount of millis to add, may be negative * @return the new period with the increased millis * @throws UnsupportedOperationException if the field is not supported */ public Period withMillis(int millis) { int[] values = getValues(); // cloned getPeriodType().setIndexedField(this, PeriodType.MILLI_INDEX, values, millis); return new Period(values, getPeriodType()); } //----------------------------------------------------------------------- /** * Returns a new period with the specified period added. *

* Each field of the period is added separately. Thus a period of * 2 hours 30 minutes plus 3 hours 40 minutes will produce a result * of 5 hours 70 minutes - see {@link #normalizedStandard()}. *

* If the period being added contains a non-zero amount for a field that * is not supported in this period then an exception is thrown. *

* This period instance is immutable and unaffected by this method call. * * @param period the period to add, null adds zero and returns this * @return the new updated period * @throws UnsupportedOperationException if any field is not supported * @since 1.5 */ public Period plus(ReadablePeriod period) { if (period == null) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.YEAR_INDEX, values, period.get(DurationFieldType.YEARS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.MONTH_INDEX, values, period.get(DurationFieldType.MONTHS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.WEEK_INDEX, values, period.get(DurationFieldType.WEEKS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.DAY_INDEX, values, period.get(DurationFieldType.DAYS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.HOUR_INDEX, values, period.get(DurationFieldType.HOURS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.MINUTE_INDEX, values, period.get(DurationFieldType.MINUTES_TYPE)); getPeriodType().addIndexedField(this, PeriodType.SECOND_INDEX, values, period.get(DurationFieldType.SECONDS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.MILLI_INDEX, values, period.get(DurationFieldType.MILLIS_TYPE)); return new Period(values, getPeriodType()); } //----------------------------------------------------------------------- /** * Returns a new period with the specified number of years added. *

* This period instance is immutable and unaffected by this method call. * * @param years the amount of years to add, may be negative * @return the new period with the increased years * @throws UnsupportedOperationException if the field is not supported */ public Period plusYears(int years) { if (years == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.YEAR_INDEX, values, years); return new Period(values, getPeriodType()); } /** * Returns a new period plus the specified number of months added. *

* This period instance is immutable and unaffected by this method call. * * @param months the amount of months to add, may be negative * @return the new period plus the increased months * @throws UnsupportedOperationException if the field is not supported */ public Period plusMonths(int months) { if (months == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.MONTH_INDEX, values, months); return new Period(values, getPeriodType()); } /** * Returns a new period plus the specified number of weeks added. *

* This period instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to add, may be negative * @return the new period plus the increased weeks * @throws UnsupportedOperationException if the field is not supported */ public Period plusWeeks(int weeks) { if (weeks == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.WEEK_INDEX, values, weeks); return new Period(values, getPeriodType()); } /** * Returns a new period plus the specified number of days added. *

* This period instance is immutable and unaffected by this method call. * * @param days the amount of days to add, may be negative * @return the new period plus the increased days * @throws UnsupportedOperationException if the field is not supported */ public Period plusDays(int days) { if (days == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.DAY_INDEX, values, days); return new Period(values, getPeriodType()); } /** * Returns a new period plus the specified number of hours added. *

* This period instance is immutable and unaffected by this method call. * * @param hours the amount of hours to add, may be negative * @return the new period plus the increased hours * @throws UnsupportedOperationException if the field is not supported */ public Period plusHours(int hours) { if (hours == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.HOUR_INDEX, values, hours); return new Period(values, getPeriodType()); } /** * Returns a new period plus the specified number of minutes added. *

* This period instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to add, may be negative * @return the new period plus the increased minutes * @throws UnsupportedOperationException if the field is not supported */ public Period plusMinutes(int minutes) { if (minutes == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.MINUTE_INDEX, values, minutes); return new Period(values, getPeriodType()); } /** * Returns a new period plus the specified number of seconds added. *

* This period instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to add, may be negative * @return the new period plus the increased seconds * @throws UnsupportedOperationException if the field is not supported */ public Period plusSeconds(int seconds) { if (seconds == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.SECOND_INDEX, values, seconds); return new Period(values, getPeriodType()); } /** * Returns a new period plus the specified number of millis added. *

* This period instance is immutable and unaffected by this method call. * * @param millis the amount of millis to add, may be negative * @return the new period plus the increased millis * @throws UnsupportedOperationException if the field is not supported */ public Period plusMillis(int millis) { if (millis == 0) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.MILLI_INDEX, values, millis); return new Period(values, getPeriodType()); } //----------------------------------------------------------------------- /** * Returns a new period with the specified period subtracted. *

* Each field of the period is subtracted separately. Thus a period of * 3 hours 30 minutes minus 2 hours 40 minutes will produce a result * of 1 hour and -10 minutes - see {@link #normalizedStandard()}. *

* If the period being added contains a non-zero amount for a field that * is not supported in this period then an exception is thrown. *

* This period instance is immutable and unaffected by this method call. * * @param period the period to add, null adds zero and returns this * @return the new updated period * @throws UnsupportedOperationException if any field is not supported * @since 1.5 */ public Period minus(ReadablePeriod period) { if (period == null) { return this; } int[] values = getValues(); // cloned getPeriodType().addIndexedField(this, PeriodType.YEAR_INDEX, values, -period.get(DurationFieldType.YEARS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.MONTH_INDEX, values, -period.get(DurationFieldType.MONTHS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.WEEK_INDEX, values, -period.get(DurationFieldType.WEEKS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.DAY_INDEX, values, -period.get(DurationFieldType.DAYS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.HOUR_INDEX, values, -period.get(DurationFieldType.HOURS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.MINUTE_INDEX, values, -period.get(DurationFieldType.MINUTES_TYPE)); getPeriodType().addIndexedField(this, PeriodType.SECOND_INDEX, values, -period.get(DurationFieldType.SECONDS_TYPE)); getPeriodType().addIndexedField(this, PeriodType.MILLI_INDEX, values, -period.get(DurationFieldType.MILLIS_TYPE)); return new Period(values, getPeriodType()); } //----------------------------------------------------------------------- /** * Returns a new period with the specified number of years taken away. *

* This period instance is immutable and unaffected by this method call. * * @param years the amount of years to take away, may be negative * @return the new period with the increased years * @throws UnsupportedOperationException if the field is not supported */ public Period minusYears(int years) { return plusYears(-years); } /** * Returns a new period minus the specified number of months taken away. *

* This period instance is immutable and unaffected by this method call. * * @param months the amount of months to take away, may be negative * @return the new period minus the increased months * @throws UnsupportedOperationException if the field is not supported */ public Period minusMonths(int months) { return plusMonths(-months); } /** * Returns a new period minus the specified number of weeks taken away. *

* This period instance is immutable and unaffected by this method call. * * @param weeks the amount of weeks to take away, may be negative * @return the new period minus the increased weeks * @throws UnsupportedOperationException if the field is not supported */ public Period minusWeeks(int weeks) { return plusWeeks(-weeks); } /** * Returns a new period minus the specified number of days taken away. *

* This period instance is immutable and unaffected by this method call. * * @param days the amount of days to take away, may be negative * @return the new period minus the increased days * @throws UnsupportedOperationException if the field is not supported */ public Period minusDays(int days) { return plusDays(-days); } /** * Returns a new period minus the specified number of hours taken away. *

* This period instance is immutable and unaffected by this method call. * * @param hours the amount of hours to take away, may be negative * @return the new period minus the increased hours * @throws UnsupportedOperationException if the field is not supported */ public Period minusHours(int hours) { return plusHours(-hours); } /** * Returns a new period minus the specified number of minutes taken away. *

* This period instance is immutable and unaffected by this method call. * * @param minutes the amount of minutes to take away, may be negative * @return the new period minus the increased minutes * @throws UnsupportedOperationException if the field is not supported */ public Period minusMinutes(int minutes) { return plusMinutes(-minutes); } /** * Returns a new period minus the specified number of seconds taken away. *

* This period instance is immutable and unaffected by this method call. * * @param seconds the amount of seconds to take away, may be negative * @return the new period minus the increased seconds * @throws UnsupportedOperationException if the field is not supported */ public Period minusSeconds(int seconds) { return plusSeconds(-seconds); } /** * Returns a new period minus the specified number of millis taken away. *

* This period instance is immutable and unaffected by this method call. * * @param millis the amount of millis to take away, may be negative * @return the new period minus the increased millis * @throws UnsupportedOperationException if the field is not supported */ public Period minusMillis(int millis) { return plusMillis(-millis); } //----------------------------------------------------------------------- /** * Returns a new instance with each element in this period multiplied * by the specified scalar. * * @param scalar the scalar to multiply by, not null * @return a {@code Period} based on this period with the amounts multiplied by the scalar, never null * @throws ArithmeticException if the capacity of any field is exceeded * @since 2.1 */ public Period multipliedBy(int scalar) { if (this == ZERO || scalar == 1) { return this; } int[] values = getValues(); // cloned for (int i = 0; i < values.length; i++) { values[i] = FieldUtils.safeMultiply(values[i], scalar); } return new Period(values, getPeriodType()); } /** * Returns a new instance with each amount in this period negated. * * @return a {@code Period} based on this period with the amounts negated, never null * @throws ArithmeticException if any field has the minimum value * @since 2.1 */ public Period negated() { return multipliedBy(-1); } //----------------------------------------------------------------------- /** * Converts this period to a period in weeks assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all * weeks are 7 days, all days are 24 hours, all hours are 60 minutes and * all minutes are 60 seconds. This is not true when daylight savings time * is considered, and may also not be true for some unusual chronologies. * However, it is included as it is a useful operation for many * applications and business rules. *

* If the period contains years or months, an exception will be thrown. * * @return a period representing the number of standard weeks in this period * @throws UnsupportedOperationException if the period contains years or months * @throws ArithmeticException if the number of weeks is too large to be represented * @since 1.5 */ public Weeks toStandardWeeks() { checkYearsAndMonths("Weeks"); long millis = getMillis(); // assign to a long millis += ((long) getSeconds()) * DateTimeConstants.MILLIS_PER_SECOND; millis += ((long) getMinutes()) * DateTimeConstants.MILLIS_PER_MINUTE; millis += ((long) getHours()) * DateTimeConstants.MILLIS_PER_HOUR; millis += ((long) getDays()) * DateTimeConstants.MILLIS_PER_DAY; long weeks = ((long) getWeeks()) + millis / DateTimeConstants.MILLIS_PER_WEEK; return Weeks.weeks(FieldUtils.safeToInt(weeks)); } /** * Converts this period to a period in days assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all * weeks are 7 days, all days are 24 hours, all hours are 60 minutes and * all minutes are 60 seconds. This is not true when daylight savings time * is considered, and may also not be true for some unusual chronologies. * However, it is included as it is a useful operation for many * applications and business rules. *

* If the period contains years or months, an exception will be thrown. * * @return a period representing the number of standard days in this period * @throws UnsupportedOperationException if the period contains years or months * @throws ArithmeticException if the number of days is too large to be represented * @since 1.5 */ public Days toStandardDays() { checkYearsAndMonths("Days"); long millis = getMillis(); // assign to a long millis += ((long) getSeconds()) * DateTimeConstants.MILLIS_PER_SECOND; millis += ((long) getMinutes()) * DateTimeConstants.MILLIS_PER_MINUTE; millis += ((long) getHours()) * DateTimeConstants.MILLIS_PER_HOUR; long days = millis / DateTimeConstants.MILLIS_PER_DAY; days = FieldUtils.safeAdd(days, getDays()); days = FieldUtils.safeAdd(days, ((long) getWeeks()) * ((long) DateTimeConstants.DAYS_PER_WEEK)); return Days.days(FieldUtils.safeToInt(days)); } /** * Converts this period to a period in hours assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all * weeks are 7 days, all days are 24 hours, all hours are 60 minutes and * all minutes are 60 seconds. This is not true when daylight savings time * is considered, and may also not be true for some unusual chronologies. * However, it is included as it is a useful operation for many * applications and business rules. *

* If the period contains years or months, an exception will be thrown. * * @return a period representing the number of standard hours in this period * @throws UnsupportedOperationException if the period contains years or months * @throws ArithmeticException if the number of hours is too large to be represented * @since 1.5 */ public Hours toStandardHours() { checkYearsAndMonths("Hours"); long millis = getMillis(); // assign to a long millis += ((long) getSeconds()) * DateTimeConstants.MILLIS_PER_SECOND; millis += ((long) getMinutes()) * DateTimeConstants.MILLIS_PER_MINUTE; long hours = millis / DateTimeConstants.MILLIS_PER_HOUR; hours = FieldUtils.safeAdd(hours, getHours()); hours = FieldUtils.safeAdd(hours, ((long) getDays()) * ((long) DateTimeConstants.HOURS_PER_DAY)); hours = FieldUtils.safeAdd(hours, ((long) getWeeks()) * ((long) DateTimeConstants.HOURS_PER_WEEK)); return Hours.hours(FieldUtils.safeToInt(hours)); } /** * Converts this period to a period in minutes assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all * weeks are 7 days, all days are 24 hours, all hours are 60 minutes and * all minutes are 60 seconds. This is not true when daylight savings time * is considered, and may also not be true for some unusual chronologies. * However, it is included as it is a useful operation for many * applications and business rules. *

* If the period contains years or months, an exception will be thrown. * * @return a period representing the number of standard minutes in this period * @throws UnsupportedOperationException if the period contains years or months * @throws ArithmeticException if the number of minutes is too large to be represented * @since 1.5 */ public Minutes toStandardMinutes() { checkYearsAndMonths("Minutes"); long millis = getMillis(); // assign to a long millis += ((long) getSeconds()) * DateTimeConstants.MILLIS_PER_SECOND; long minutes = millis / DateTimeConstants.MILLIS_PER_MINUTE; minutes = FieldUtils.safeAdd(minutes, getMinutes()); minutes = FieldUtils.safeAdd(minutes, ((long) getHours()) * ((long) DateTimeConstants.MINUTES_PER_HOUR)); minutes = FieldUtils.safeAdd(minutes, ((long) getDays()) * ((long) DateTimeConstants.MINUTES_PER_DAY)); minutes = FieldUtils.safeAdd(minutes, ((long) getWeeks()) * ((long) DateTimeConstants.MINUTES_PER_WEEK)); return Minutes.minutes(FieldUtils.safeToInt(minutes)); } /** * Converts this period to a period in seconds assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert between different types of period. * However to achieve this it makes the assumption that all * weeks are 7 days, all days are 24 hours, all hours are 60 minutes and * all minutes are 60 seconds. This is not true when daylight savings time * is considered, and may also not be true for some unusual chronologies. * However, it is included as it is a useful operation for many * applications and business rules. *

* If the period contains years or months, an exception will be thrown. * * @return a period representing the number of standard seconds in this period * @throws UnsupportedOperationException if the period contains years or months * @throws ArithmeticException if the number of seconds is too large to be represented * @since 1.5 */ public Seconds toStandardSeconds() { checkYearsAndMonths("Seconds"); long seconds = getMillis() / DateTimeConstants.MILLIS_PER_SECOND; seconds = FieldUtils.safeAdd(seconds, getSeconds()); seconds = FieldUtils.safeAdd(seconds, ((long) getMinutes()) * ((long) DateTimeConstants.SECONDS_PER_MINUTE)); seconds = FieldUtils.safeAdd(seconds, ((long) getHours()) * ((long) DateTimeConstants.SECONDS_PER_HOUR)); seconds = FieldUtils.safeAdd(seconds, ((long) getDays()) * ((long) DateTimeConstants.SECONDS_PER_DAY)); seconds = FieldUtils.safeAdd(seconds, ((long) getWeeks()) * ((long) DateTimeConstants.SECONDS_PER_WEEK)); return Seconds.seconds(FieldUtils.safeToInt(seconds)); } //----------------------------------------------------------------------- /** * Converts this period to a duration assuming a * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to convert from a period to a duration. * However to achieve this it makes the assumption that all * weeks are 7 days, all days are 24 hours, all hours are 60 minutes and * all minutes are 60 seconds. This is not true when daylight savings time * is considered, and may also not be true for some unusual chronologies. * However, it is included as it is a useful operation for many * applications and business rules. *

* If the period contains years or months, an exception will be thrown. * * @return a duration equivalent to this period * @throws UnsupportedOperationException if the period contains years or months * @since 1.5 */ public Duration toStandardDuration() { checkYearsAndMonths("Duration"); long millis = getMillis(); // no overflow can happen, even with Integer.MAX_VALUEs millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND)); millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE)); millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR)); millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY)); millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK)); return new Duration(millis); } /** * Check that there are no years or months in the period. * * @param destintionType the destination type, not null * @throws UnsupportedOperationException if the period contains years or months */ private void checkYearsAndMonths(String destintionType) { if (getMonths() != 0) { throw new UnsupportedOperationException("Cannot convert to " + destintionType + " as this period contains months and months vary in length"); } if (getYears() != 0) { throw new UnsupportedOperationException("Cannot convert to " + destintionType + " as this period contains years and years vary in length"); } } //----------------------------------------------------------------------- /** * Normalizes this period using standard rules, assuming a 12 month year, * 7 day week, 24 hour day, 60 minute hour and 60 second minute. *

* This method allows you to normalize a period. * However to achieve this it makes the assumption that all years are * 12 months, all weeks are 7 days, all days are 24 hours, * all hours are 60 minutes and all minutes are 60 seconds. This is not * true when daylight savings time is considered, and may also not be true * for some chronologies. However, it is included as it is a useful operation * for many applications and business rules. *

* If the period contains years or months, then the months will be * normalized to be between 0 and 11. The days field and below will be * normalized as necessary, however this will not overflow into the months * field. Thus a period of 1 year 15 months will normalize to 2 years 3 months. * But a period of 1 month 40 days will remain as 1 month 40 days. *

* The result will always have a PeriodType of standard, thus * days will be grouped into weeks. * * @return a normalized period equivalent to this period * @throws ArithmeticException if any field is too large to be represented * @since 1.5 */ public Period normalizedStandard() { return normalizedStandard(PeriodType.standard()); } //----------------------------------------------------------------------- /** * Normalizes this period using standard rules, assuming a 12 month year, * 7 day week, 24 hour day, 60 minute hour and 60 second minute, * providing control over how the result is split into fields. *

* This method allows you to normalize a period. * However to achieve this it makes the assumption that all years are * 12 months, all weeks are 7 days, all days are 24 hours, * all hours are 60 minutes and all minutes are 60 seconds. This is not * true when daylight savings time is considered, and may also not be true * for some chronologies. However, it is included as it is a useful operation * for many applications and business rules. *

* If the period contains years or months, then the months will be * normalized to be between 0 and 11. The days field and below will be * normalized as necessary, however this will not overflow into the months * field. Thus a period of 1 year 15 months will normalize to 2 years 3 months. * But a period of 1 month 40 days will remain as 1 month 40 days. *

* The PeriodType parameter controls how the result is created. It allows * you to omit certain fields from the result if desired. For example, * you may not want the result to include weeks, in which case you pass * in PeriodType.yearMonthDayTime(). * * @param type the period type of the new period, null means standard type * @return a normalized period equivalent to this period * @throws ArithmeticException if any field is too large to be represented * @throws UnsupportedOperationException if this period contains non-zero * years or months but the specified period type does not support them * @since 1.5 */ public Period normalizedStandard(PeriodType type) { long millis = getMillis(); // no overflow can happen, even with Integer.MAX_VALUEs millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND)); millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE)); millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR)); millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY)); millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK)); Period result = new Period(millis, DateTimeUtils.getPeriodType(type), ISOChronology.getInstanceUTC()); int years = getYears(); int months = getMonths(); if (years != 0 || months != 0) { years = FieldUtils.safeAdd(years, months / 12); months = months % 12; if (years != 0) { result = result.withYears(years); } if (months != 0) { result = result.withMonths(months); } } return result; } } joda-time-2.3/NOTICE.txt0000644000175000017500000000047411564251353014313 0ustar ebourgebourg============================================================================= = NOTICE file corresponding to section 4d of the Apache License Version 2.0 = ============================================================================= This product includes software developed by Joda.org (http://www.joda.org/).