├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
└── java
│ └── com
│ └── cronutils
│ └── htime
│ ├── DateTimeFormatParser.java
│ ├── DatetimeFormatterConstants.java
│ ├── HDateTimeFormat.java
│ ├── HDateTimeFormatBuilder.java
│ ├── jdk12
│ ├── JDK12DatetimeFormatterConstants.java
│ └── JDK12HDateTimeFormat.java
│ └── jodatime
│ ├── JodaTimeDatetimeFormatterConstants.java
│ └── JodaTimeHDateTimeFormat.java
└── test
└── java
└── com
└── cronutils
└── htime
├── jdk12
└── JDK12HDateTimeFormatTest.java
└── jodatime
└── JodaTimeHDateTimeFormatTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | .settings/
3 | .classpath
4 | .project
5 | *.idea
6 | *.iml
7 | nbbuild
8 | nb-build.xml
9 | nbproject
10 | *.sh
11 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 |
3 | branches:
4 | only:
5 | - master
6 |
7 | jdk:
8 | - oraclejdk8
9 | - oraclejdk7
10 | - openjdk7
11 | - openjdk6
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | htime
2 | ===========
3 | A Java library to make it easy for humans format a date. You no longer need to remember date time formatting chars: just write an example, and you will get the appropriate formatter.
4 |
5 | The project follows the [Semantic Versioning Convention](http://semver.org/) and uses Apache 2.0 license.
6 |
7 | [](https://flattr.com/submit/auto?user_id=jmrozanec&url=https://github.com/jmrozanec/htime)
8 | [](https://travis-ci.org/jmrozanec/htime)
9 |
10 | [](https://www.openhub.net/p/htime/)
11 |
12 | **Download**
13 |
14 | htime is available on [Maven central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.cronutils%22) repository.
15 |
16 |
17 | com.cronutils
18 | htime
19 | 1.0.0
20 |
21 |
22 |
23 | **Features**
24 |
25 | * Provide any date time format written in human readable text, and get the appropriate date time formatter!
26 |
27 | **Usage Examples**
28 |
29 | ***Get JDK SimpleDateFormatter***
30 |
31 | //define your own expressions to be formatted
32 | HDateTimeFormat hDateTimeFormat =
33 | HDateTimeFormatBuilder.getInstance().forJDK12().getFormatter();
34 | SimpleDateFormat jdkTimeFormatter = hDateTimeFormat.forPattern("June 9, 2011");
35 | String formattedDate = jdkTimeFormatter.format(new Date());
36 | //formattedDate will be ex.: "June 9, 2015"
37 |
38 | ***Get JodaTime DateTimeFormatter***
39 |
40 | //define your own expressions to be formatted
41 | HDateTimeFormat hDateTimeFormat =
42 | HDateTimeFormatBuilder.getInstance().forJodaTime().getFormatter();
43 | DateTimeFormatter jodaTimeFormatter = hDateTimeFormat.forPattern("June 9, 2011");
44 | String formattedDate = jodaTimeFormatter.print(DateTime.now());
45 | //formattedDate will be ex.: "June 9, 2015"
46 |
47 |
48 | **Contribute & Support!**
49 |
50 | Contributions are welcome! You can contribute by
51 | * star and/or Flattr this repo!
52 | * requesting or adding new features. Check our [roadmap](https://github.com/jmrozanec/htime/wiki/Roadmap)!
53 | * enhancing existing code: ex.: provide more accurate description cases
54 | * testing
55 | * enhancing documentation
56 | * providing translations to support new locales
57 | * bringing suggestions and reporting bugs
58 | * spreading the word / telling us how you use it!
59 |
60 |
61 | Check [our page](http://cronutils.com)! For stats about the project, you can visit our [OpenHUB profile](https://www.openhub.net/p/htime).
62 |
63 | Support us donating once or by subscription through Flattr!
64 |
65 | [](https://flattr.com/submit/auto?user_id=jmrozanec&url=https://github.com/jmrozanec/htime)
66 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 |
8 | org.sonatype.oss
9 | oss-parent
10 | 7
11 |
12 |
13 | com.cronutils
14 | htime
15 | 1.0.1-SNAPSHOT
16 |
17 | htime
18 | A Java library for human readable date and time formatters
19 | http://cron-utils.com/
20 |
21 |
22 |
23 | Apache 2.0
24 | http://www.apache.org/licenses/LICENSE-2.0.html
25 | repo
26 |
27 |
28 |
29 |
30 |
31 | jmrozanec
32 | https://github.com/jmrozanec
33 |
34 |
35 |
36 |
37 | https://github.com/jmrozanec/htime/issues
38 | GitHub Issues
39 |
40 |
41 |
42 | https://github.com/jmrozanec/htime
43 | scm:git:git@github.com:jmrozanec/htime.git
44 | scm:git:git@github.com:jmrozanec/htime.git
45 | HEAD
46 |
47 |
48 |
49 |
50 | ossrh
51 | Release Repository
52 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
53 |
54 |
55 | ossrh
56 | Snapshots Repository
57 | https://oss.sonatype.org/content/repositories/snapshots/
58 |
59 |
60 |
61 |
62 | 3.3.2
63 | 2.3
64 | 18.0
65 | 4.11
66 | 1.9.5
67 | 1.5.5
68 |
69 | github
70 | UTF-8
71 |
72 |
73 |
74 |
75 | org.apache.commons
76 | commons-lang3
77 | ${commonsLang.version}
78 |
79 |
80 | joda-time
81 | joda-time
82 | ${jodatime.version}
83 |
84 |
85 |
86 | com.google.guava
87 | guava
88 | ${guava.version}
89 |
90 |
91 |
92 | org.mockito
93 | mockito-core
94 | ${mockito.version}
95 | test
96 |
97 |
98 | org.powermock
99 | powermock-module-junit4
100 | ${powermock.version}
101 | test
102 |
103 |
104 | org.powermock
105 | powermock-api-mockito
106 | ${powermock.version}
107 | test
108 |
109 |
110 |
111 |
112 |
113 |
114 | org.apache.maven.plugins
115 | maven-compiler-plugin
116 | 3.1
117 |
118 | 1.6
119 | 1.6
120 |
121 |
122 |
123 | org.apache.maven.plugins
124 | maven-source-plugin
125 | 2.2.1
126 |
127 |
128 | attach-sources
129 |
130 | jar
131 |
132 |
133 |
134 |
135 |
136 | org.apache.maven.plugins
137 | maven-clean-plugin
138 | 2.5
139 |
140 |
141 | org.apache.maven.plugins
142 | maven-install-plugin
143 | 2.5.1
144 |
145 |
146 | org.apache.maven.plugins
147 | maven-jar-plugin
148 | 2.4
149 |
150 |
151 | org.apache.maven.plugins
152 | maven-resources-plugin
153 | 2.6
154 |
155 |
156 | org.apache.maven.plugins
157 | maven-javadoc-plugin
158 | 2.9.1
159 |
160 |
161 | attach-javadocs
162 |
163 | jar
164 |
165 |
166 |
167 |
168 |
169 | org.codehaus.mojo
170 | sonar-maven-plugin
171 | 1.0
172 |
173 |
174 | org.apache.maven.plugins
175 | maven-surefire-plugin
176 | 2.17
177 |
178 |
179 | org.apache.maven.plugins
180 | maven-deploy-plugin
181 | 2.8.1
182 |
183 |
184 | org.sonatype.plugins
185 | nexus-staging-maven-plugin
186 | 1.6.2
187 | true
188 |
189 | ossrh
190 | https://oss.sonatype.org/
191 | true
192 |
193 |
194 |
195 | org.codehaus.mojo
196 | findbugs-maven-plugin
197 | 2.5.3
198 |
199 |
200 | org.codehaus.mojo
201 | clirr-maven-plugin
202 | 2.6.1
203 |
204 |
205 | org.codehaus.mojo
206 | versions-maven-plugin
207 | 2.1
208 |
209 |
210 |
211 |
212 | org.codehaus.mojo
213 | cobertura-maven-plugin
214 | 2.6
215 |
216 | xml
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 | org.apache.maven.wagon
225 | wagon-webdav
226 | 1.0-beta-2
227 |
228 |
229 |
230 |
231 |
232 |
233 | release-sign-artifacts
234 |
235 |
236 | performRelease
237 | true
238 |
239 |
240 |
241 |
242 |
243 | org.apache.maven.plugins
244 | maven-gpg-plugin
245 | 1.5
246 |
247 |
248 | sign-artifacts
249 | verify
250 |
251 | sign
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 | travis
263 |
264 |
265 | env.TRAVIS
266 | true
267 |
268 |
269 |
270 |
271 |
272 | org.eluder.coveralls
273 | coveralls-maven-plugin
274 | 2.2.0
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/DateTimeFormatParser.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime;
2 |
3 | import com.google.common.annotations.VisibleForTesting;
4 | import com.google.common.collect.Maps;
5 | import org.apache.commons.lang3.Validate;
6 | import org.joda.time.DateTimeZone;
7 | import org.joda.time.LocalDate;
8 |
9 | import java.util.Locale;
10 | import java.util.Map;
11 |
12 | /*
13 | * Copyright 2015 jmrozanec
14 | * Licensed under the Apache License, Version 2.0 (the "License");
15 | * you may not use this file except in compliance with the License.
16 | * You may obtain a copy of the License at
17 | * http://www.apache.org/licenses/LICENSE-2.0
18 | * Unless required by applicable law or agreed to in writing, software
19 | * distributed under the License is distributed on an "AS IS" BASIS,
20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 | * See the License for the specific language governing permissions and
22 | * limitations under the License.
23 | */
24 | public class DateTimeFormatParser {
25 | private DatetimeFormatterConstants constants;
26 | private Locale locale;
27 | private Map dayOfWeek;
28 | private Map months;
29 | private Map dateFormatByCountry;
30 |
31 | public DateTimeFormatParser(DatetimeFormatterConstants constants, Locale locale) {
32 | this.constants = Validate.notNull(constants, "ConstantsConfiguration must not be null");
33 | this.locale = Validate.notNull(locale, "Locale must not be null");
34 | dayOfWeek = initDaysOfWeek(locale);
35 | months = initMonths(locale);
36 | dateFormatByCountry = initDateFormatByCountry();
37 | }
38 |
39 | public String parsePattern(String expression) {
40 | if (isTimezone(expression.replaceAll("[^A-Za-z0-9/_:\\-\\+ ]", ""))) {
41 | return timezonePattern(expression);
42 | }
43 | expression = expression.toLowerCase();
44 | if (expression.contains("/")) {
45 | return parseDateSlashes(expression);
46 | }
47 | if (expression.contains(":")) {
48 | return parseTimeWithColons(expression);
49 | }
50 |
51 | String clean = expression.replaceAll("[^A-Za-z0-9 ]", "");
52 | if (isNumberPattern(clean)) {
53 | return expression.replace(clean, numberPattern(clean));
54 | }
55 | if (dayOfWeek.containsKey(clean)) {
56 | return expression.replace(clean, dayOfWeek.get(clean));
57 | }
58 | if (months.containsKey(clean)) {
59 | return expression.replace(clean, months.get(clean));
60 | }
61 |
62 | return expression;
63 | }
64 |
65 | @VisibleForTesting
66 | String parseDateSlashes(String expression) {
67 | return dateFormatByCountry.containsKey(locale.getCountry()) ?
68 | dateFormatByCountry.get(locale.getCountry()) :
69 | String.format("%s%s/%s%s/%s%s", constants.dayOfMonth(), constants.dayOfMonth(),
70 | constants.monthOfYear(), constants.monthOfYear(),
71 | constants.year(), constants.year()
72 | );
73 | }
74 |
75 | @VisibleForTesting
76 | String parseTimeWithColons(String expression) {
77 | String hour = String.format("%s%s", constants.hourOfDay(), constants.hourOfDay());
78 | String pattern = "%s";
79 | if (expression.contains("am") || expression.contains("pm")) {
80 | hour = String.format("%s%s", constants.clockhourOfHalfday(), constants.clockhourOfHalfday());
81 | pattern = "%s " + constants.halfOfDay();
82 | }
83 | String[] parts = expression.split(":");
84 | if (parts.length == 2) {
85 | return String.format(pattern, String.format("%s:%s%s", hour, constants.minuteOfHour(), constants.minuteOfHour()));
86 | }
87 | return String.format(pattern,
88 | String.format("%s:%s%s:%s%s", hour,
89 | constants.minuteOfHour(), constants.minuteOfHour(),
90 | constants.secondOfMinute(), constants.secondOfMinute())
91 | );
92 | }
93 |
94 | @VisibleForTesting
95 | boolean isNumberPattern(String string) {
96 | try {
97 | Integer.parseInt(string);
98 | } catch (NumberFormatException e) {
99 | return false;
100 | }
101 | return true;
102 | }
103 |
104 | @VisibleForTesting
105 | String numberPattern(String string) {
106 | switch (string.length()) {
107 | case 4:
108 | return String.format("%s%s%s%s", constants.year(), constants.year(), constants.year(), constants.year());
109 | case 2:
110 | return String.format("%s%s", constants.dayOfMonth(), constants.dayOfMonth());
111 | default:
112 | return constants.dayOfMonth();
113 | }
114 | }
115 |
116 | @VisibleForTesting
117 | boolean isTimezone(String string) {
118 | try {
119 | DateTimeZone.forID(string);
120 | } catch (IllegalArgumentException e) {
121 | return false;
122 | }
123 | return true;
124 | }
125 |
126 | @VisibleForTesting
127 | String timezonePattern(String string) {
128 | return constants.timezoneRFC822();
129 | }
130 |
131 | @VisibleForTesting
132 | Map initDaysOfWeek(Locale locale) {
133 | String fullDoW =
134 | String.format("%s%s%s%s",
135 | constants.dayOfWeekName(), constants.dayOfWeekName(),
136 | constants.dayOfWeekName(), constants.dayOfWeekName()
137 | );
138 | LocalDate date = new LocalDate();
139 | Map mapping = Maps.newHashMap();
140 | for (int j = 1; j < 8; j++) {
141 | String dow = date.withDayOfWeek(j).dayOfWeek().getAsText(locale).toLowerCase();
142 | mapping.put(dow, fullDoW);
143 | mapping.put(dow.substring(0, 3), constants.dayOfWeekName());
144 | }
145 | return mapping;
146 | }
147 |
148 | @VisibleForTesting
149 | Map initMonths(Locale locale) {
150 | String fullMonth =
151 | String.format("%s%s%s%s",
152 | constants.monthOfYear(), constants.monthOfYear(),
153 | constants.monthOfYear(), constants.monthOfYear()
154 | );
155 | String shortMonth = String.format("%s%s%s", constants.monthOfYear(),
156 | constants.monthOfYear(), constants.monthOfYear());
157 | LocalDate date = new LocalDate();
158 | Map mapping = Maps.newHashMap();
159 | for (int j = 1; j < 13; j++) {
160 | String moy = date.withMonthOfYear(j).monthOfYear().getAsText(locale).toLowerCase();
161 | mapping.put(moy, fullMonth);
162 | mapping.put(moy.substring(0, 3), shortMonth);
163 | }
164 | return mapping;
165 | }
166 |
167 | /**
168 | * Information taken from http://en.wikipedia.org/wiki/Date_format_by_country
169 | *
170 | * @return
171 | */
172 | @VisibleForTesting
173 | Map initDateFormatByCountry() {
174 | String mmddyy = String.format("%s%s/%s%s/%s%s",
175 | constants.monthOfYear(), constants.monthOfYear(),
176 | constants.dayOfMonth(), constants.dayOfMonth(),
177 | constants.year(), constants.year()
178 | );
179 | String yymmdd = String.format("%s%s/%s%s/%s%s",
180 | constants.year(), constants.year(),
181 | constants.monthOfYear(), constants.monthOfYear(),
182 | constants.dayOfMonth(), constants.dayOfMonth()
183 | );
184 | Map dateFormatByCountry = Maps.newHashMap();
185 | dateFormatByCountry.put("US", mmddyy);
186 | dateFormatByCountry.put("BZ", mmddyy);
187 |
188 | dateFormatByCountry.put("CN", yymmdd);
189 | dateFormatByCountry.put("KR", yymmdd);
190 | dateFormatByCountry.put("KP", yymmdd);
191 | dateFormatByCountry.put("TW", yymmdd);
192 | dateFormatByCountry.put("HU", yymmdd);
193 | dateFormatByCountry.put("IR", yymmdd);
194 | dateFormatByCountry.put("JP", yymmdd);
195 | dateFormatByCountry.put("LT", yymmdd);
196 | dateFormatByCountry.put("MN", yymmdd);
197 | return dateFormatByCountry;
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/DatetimeFormatterConstants.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime;
2 |
3 | /*
4 | * Copyright 2015 jmrozanec
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 | public interface DatetimeFormatterConstants {
16 |
17 | String era();
18 |
19 | String centuryOfEra();
20 |
21 | String yearOfEra();
22 |
23 | String weekyear();
24 |
25 | String weekOfWeekyear();
26 |
27 | String weekOfMonth();
28 |
29 | String dayOfWeekInMonth();
30 |
31 | String dayOfWeekNumber();
32 |
33 | String dayOfWeekName();
34 |
35 | String year();
36 |
37 | String dayOfYear();
38 |
39 | String monthOfYear();
40 |
41 | String dayOfMonth();
42 |
43 | String halfOfDay();
44 |
45 | String hourOfHalfday();
46 |
47 | String clockhourOfHalfday();
48 |
49 | String hourOfDay();
50 |
51 | String clockHourOfDay();
52 |
53 | String minuteOfHour();
54 |
55 | String secondOfMinute();
56 |
57 | String fractionOfSecond();
58 |
59 | String timezonePST();
60 |
61 | String timezoneRFC822();
62 |
63 | String timezoneISO8601();
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/HDateTimeFormat.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime;
2 |
3 | /*
4 | * Copyright 2015 jmrozanec
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 | public interface HDateTimeFormat {
16 | /**
17 | * Creates a date time formatter for given expression
18 | *
19 | * @param expression - some expression, never null
20 | * @return some formatter instance, never null
21 | */
22 | public T forPattern(String expression);
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/HDateTimeFormatBuilder.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime;
2 |
3 | import com.cronutils.htime.jdk12.JDK12HDateTimeFormat;
4 | import com.cronutils.htime.jodatime.JodaTimeHDateTimeFormat;
5 | import org.joda.time.format.DateTimeFormatter;
6 |
7 | import java.text.SimpleDateFormat;
8 | import java.util.Locale;
9 |
10 | /*
11 | * Copyright 2015 jmrozanec
12 | * Licensed under the Apache License, Version 2.0 (the "License");
13 | * you may not use this file except in compliance with the License.
14 | * You may obtain a copy of the License at
15 | * http://www.apache.org/licenses/LICENSE-2.0
16 | * Unless required by applicable law or agreed to in writing, software
17 | * distributed under the License is distributed on an "AS IS" BASIS,
18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 | * See the License for the specific language governing permissions and
20 | * limitations under the License.
21 | */
22 | public class HDateTimeFormatBuilder {
23 | private static final HDateTimeFormatBuilder instance = new HDateTimeFormatBuilder();
24 |
25 | private HDateTimeFormatBuilder() {
26 | }
27 |
28 | public static HDateTimeFormatBuilder getInstance() {
29 | return instance;
30 | }
31 |
32 | public JodaTimeHDateTimeFormatBuilder forJodaTime() {
33 | return new JodaTimeHDateTimeFormatBuilder();
34 | }
35 |
36 | public JDK12TimeHDateTimeFormatBuilder forJDK12() {
37 | return new JDK12TimeHDateTimeFormatBuilder();
38 | }
39 |
40 | public static class JodaTimeHDateTimeFormatBuilder {
41 | public HDateTimeFormat getFormatter() {
42 | return new JodaTimeHDateTimeFormat(Locale.US);
43 | }
44 |
45 | public HDateTimeFormat getFormatter(Locale locale) {
46 | return new JodaTimeHDateTimeFormat(locale);
47 | }
48 | }
49 |
50 | public static class JDK12TimeHDateTimeFormatBuilder {
51 | public HDateTimeFormat getFormatter() {
52 | return new JDK12HDateTimeFormat(Locale.US);
53 | }
54 |
55 | public HDateTimeFormat getFormatter(Locale locale) {
56 | return new JDK12HDateTimeFormat(locale);
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/jdk12/JDK12DatetimeFormatterConstants.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime.jdk12;
2 |
3 | /*
4 | * Copyright 2015 jmrozanec
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 |
16 | import com.cronutils.htime.DatetimeFormatterConstants;
17 |
18 | /**
19 | * Implements mapping used from JDK 1.2 onward up to JDK7:
20 | * http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
21 | */
22 | public class JDK12DatetimeFormatterConstants implements DatetimeFormatterConstants {
23 |
24 | public String era() {
25 | return "G";
26 | }
27 |
28 | public String centuryOfEra() {
29 | throw new RuntimeException("Not supported method: weekOfMonth");
30 | }
31 |
32 | public String yearOfEra() {
33 | throw new RuntimeException("Not supported method: weekOfMonth");
34 | }
35 |
36 | public String weekyear() {
37 | return "Y";
38 | }
39 |
40 | public String weekOfWeekyear() {
41 | return "w";
42 | }
43 |
44 | @Override
45 | public String weekOfMonth() {
46 | return "W";
47 | }
48 |
49 | @Override
50 | public String dayOfWeekInMonth() {
51 | return "F";
52 | }
53 |
54 | public String dayOfWeekNumber() {
55 | return "u";
56 | }
57 |
58 | public String dayOfWeekName() {
59 | return "E";
60 | }
61 |
62 | public String year() {
63 | return "y";
64 | }
65 |
66 | public String dayOfYear() {
67 | return "D";
68 | }
69 |
70 | public String monthOfYear() {
71 | return "M";
72 | }
73 |
74 | public String dayOfMonth() {
75 | return "d";
76 | }
77 |
78 | public String halfOfDay() {
79 | return "a";
80 | }
81 |
82 | public String hourOfHalfday() {
83 | return "K";
84 | }
85 |
86 | @Override
87 | public String clockhourOfHalfday() {
88 | return "h";
89 | }
90 |
91 | public String hourOfDay() {
92 | return "H";
93 | }
94 |
95 | public String clockHourOfDay() {
96 | return "k";
97 | }
98 |
99 | public String minuteOfHour() {
100 | return "m";
101 | }
102 |
103 | public String secondOfMinute() {
104 | return "s";
105 | }
106 |
107 | public String fractionOfSecond() {
108 | return "S";
109 | }
110 |
111 | public String timezonePST() {
112 | return "z";
113 | }
114 |
115 | public String timezoneRFC822() {
116 | return "Z";
117 | }
118 |
119 | public String timezoneISO8601() {
120 | return "X";
121 | }
122 |
123 | }
124 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/jdk12/JDK12HDateTimeFormat.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime.jdk12;
2 |
3 | import com.cronutils.htime.DateTimeFormatParser;
4 | import com.cronutils.htime.DatetimeFormatterConstants;
5 | import com.cronutils.htime.HDateTimeFormat;
6 | import org.apache.commons.lang3.Validate;
7 |
8 | import java.text.SimpleDateFormat;
9 | import java.util.Locale;
10 |
11 | /*
12 | * Copyright 2015 jmrozanec
13 | * Licensed under the Apache License, Version 2.0 (the "License");
14 | * you may not use this file except in compliance with the License.
15 | * You may obtain a copy of the License at
16 | * http://www.apache.org/licenses/LICENSE-2.0
17 | * Unless required by applicable law or agreed to in writing, software
18 | * distributed under the License is distributed on an "AS IS" BASIS,
19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 | * See the License for the specific language governing permissions and
21 | * limitations under the License.
22 | */
23 | public class JDK12HDateTimeFormat implements HDateTimeFormat {
24 | private Locale locale;
25 | private DatetimeFormatterConstants constants;
26 |
27 | public JDK12HDateTimeFormat(Locale locale) {
28 | Validate.notNull(locale, "Locale should not be null");
29 | this.locale = locale;
30 | this.constants = new JDK12DatetimeFormatterConstants();
31 | }
32 |
33 | @Override
34 | public SimpleDateFormat forPattern(String expression) {
35 | Validate.notBlank(expression, "Expression must not be blank or null");
36 | DateTimeFormatParser parser = new DateTimeFormatParser(constants, locale);
37 | expression = expression.replaceAll("\\s+", " ");
38 | expression = expression.replace(" AM", "AM").replace(" am", "am").replace(" PM", "PM").replace(" pm", "pm");
39 | String[] parts = expression.split(" ");
40 | StringBuilder builder = new StringBuilder();
41 | for (String part : parts) {
42 | builder.append(String.format("%s ", parser.parsePattern(part)));
43 | }
44 | return new SimpleDateFormat(builder.toString().trim());
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/jodatime/JodaTimeDatetimeFormatterConstants.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime.jodatime;
2 |
3 | import com.cronutils.htime.DatetimeFormatterConstants;
4 |
5 | /**
6 | * Implements constants from
7 | * http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html
8 | */
9 | public class JodaTimeDatetimeFormatterConstants implements DatetimeFormatterConstants {
10 |
11 | public String era() {
12 | return "G";
13 | }
14 |
15 | public String centuryOfEra() {
16 | return "C";
17 | }
18 |
19 | public String yearOfEra() {
20 | return "Y";
21 | }
22 |
23 | public String weekyear() {
24 | return "x";
25 | }
26 |
27 | public String weekOfWeekyear() {
28 | return "w";
29 | }
30 |
31 | @Override
32 | public String weekOfMonth() {
33 | throw new RuntimeException("Not supported method: weekOfMonth");
34 | }
35 |
36 | @Override
37 | public String dayOfWeekInMonth() {
38 | throw new RuntimeException("Not supported method: dayOfWeekInMonth");
39 | }
40 |
41 | public String dayOfWeekNumber() {
42 | return "e";
43 | }
44 |
45 | public String dayOfWeekName() {
46 | return "E";
47 | }
48 |
49 | public String year() {
50 | return "y";
51 | }
52 |
53 | public String dayOfYear() {
54 | return "D";
55 | }
56 |
57 | public String monthOfYear() {
58 | return "M";
59 | }
60 |
61 | public String dayOfMonth() {
62 | return "d";
63 | }
64 |
65 | public String halfOfDay() {
66 | return "a";
67 | }
68 |
69 | public String hourOfHalfday() {
70 | return "K";
71 | }
72 |
73 | public String clockhourOfHalfday() {
74 | return "h";
75 | }
76 |
77 | public String hourOfDay() {
78 | return "H";
79 | }
80 |
81 | public String clockHourOfDay() {
82 | return "k";
83 | }
84 |
85 | public String minuteOfHour() {
86 | return "m";
87 | }
88 |
89 | public String secondOfMinute() {
90 | return "s";
91 | }
92 |
93 | public String fractionOfSecond() {
94 | return "S";
95 | }
96 |
97 | public String timezonePST() {
98 | return "z";
99 | }
100 |
101 | public String timezoneRFC822() {
102 | return "Z";
103 | }
104 |
105 | public String timezoneISO8601() {
106 | throw new RuntimeException("Not supported method: timezoneISO8601");
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/com/cronutils/htime/jodatime/JodaTimeHDateTimeFormat.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime.jodatime;
2 |
3 | import com.cronutils.htime.DateTimeFormatParser;
4 | import com.cronutils.htime.DatetimeFormatterConstants;
5 | import com.cronutils.htime.HDateTimeFormat;
6 | import org.apache.commons.lang3.Validate;
7 | import org.joda.time.format.DateTimeFormat;
8 | import org.joda.time.format.DateTimeFormatter;
9 |
10 | import java.util.Locale;
11 |
12 | public class JodaTimeHDateTimeFormat implements HDateTimeFormat {
13 | private Locale locale;
14 | private DatetimeFormatterConstants constants;
15 |
16 | public JodaTimeHDateTimeFormat(Locale locale) {
17 | Validate.notNull(locale, "Locale should not be null");
18 | this.locale = locale;
19 | this.constants = new JodaTimeDatetimeFormatterConstants();
20 | }
21 |
22 | public DateTimeFormatter forPattern(String expression) {
23 | Validate.notBlank(expression, "Expression must not be blank or null");
24 | DateTimeFormatParser parser = new DateTimeFormatParser(constants, locale);
25 | expression = expression.replaceAll("\\s+", " ");
26 | expression = expression.replace(" AM", "AM").replace(" am", "am").replace(" PM", "PM").replace(" pm", "pm");
27 | String[] parts = expression.split(" ");
28 | StringBuilder builder = new StringBuilder();
29 | for (String part : parts) {
30 | builder.append(String.format("%s ", parser.parsePattern(part)));
31 | }
32 | return DateTimeFormat.forPattern(builder.toString().trim());
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/com/cronutils/htime/jdk12/JDK12HDateTimeFormatTest.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime.jdk12;
2 |
3 | import com.cronutils.htime.HDateTimeFormat;
4 | import com.cronutils.htime.HDateTimeFormatBuilder;
5 | import org.joda.time.DateTime;
6 | import org.junit.Before;
7 |
8 | import java.text.SimpleDateFormat;
9 |
10 | import static org.junit.Assert.assertEquals;
11 |
12 | public class JDK12HDateTimeFormatTest {
13 | private HDateTimeFormat formatter;
14 |
15 | @Before
16 | public void setUp() {
17 | formatter = HDateTimeFormatBuilder.getInstance().forJDK12().getFormatter();
18 | }
19 |
20 |
21 | public void testForPattern() throws Exception {
22 | assertForPattern("MMMM d, YYYY", "June 9, 2011");
23 | assertForPattern("MMM d, YYYY", "Jun 9, 2011");
24 | assertForPattern("MMM dd", "Jun 09");
25 | assertForPattern("EEEE, MMMM d, YYYY", "Thursday, June 9, 2011");
26 | assertForPattern("EEE MMM d", "Thu Jun 9");
27 | assertForPattern("MM/dd/YY", "06/09/11");
28 | assertForPattern("hh:mm:ss a", "01:00:00 AM");
29 | assertForPattern("HH:mm", "20:52");
30 | assertForPattern("HH:mm:ss", "01:00:00");
31 | assertForPattern("HH:mm Z", "01:00 America/Los_Angeles");
32 | }
33 |
34 | private void assertForPattern(String dateTimePattern, String readablePattern) {
35 | DateTime now = DateTime.now();
36 | System.out.println(String.format("%s :: %s", dateTimePattern, readablePattern));
37 | assertEquals(
38 | new SimpleDateFormat(dateTimePattern).format(now.toDate()),
39 | formatter.forPattern(readablePattern).format(DateTime.now().toDate())
40 | );
41 | }
42 | }
--------------------------------------------------------------------------------
/src/test/java/com/cronutils/htime/jodatime/JodaTimeHDateTimeFormatTest.java:
--------------------------------------------------------------------------------
1 | package com.cronutils.htime.jodatime;
2 |
3 | import com.cronutils.htime.HDateTimeFormat;
4 | import com.cronutils.htime.HDateTimeFormatBuilder;
5 | import org.joda.time.DateTime;
6 | import org.joda.time.format.DateTimeFormat;
7 | import org.joda.time.format.DateTimeFormatter;
8 | import org.junit.Before;
9 | import org.junit.Test;
10 |
11 | import static org.junit.Assert.assertEquals;
12 |
13 | /*
14 | * Copyright 2015 jmrozanec
15 | * Licensed under the Apache License, Version 2.0 (the "License");
16 | * you may not use this file except in compliance with the License.
17 | * You may obtain a copy of the License at
18 | * http://www.apache.org/licenses/LICENSE-2.0
19 | * Unless required by applicable law or agreed to in writing, software
20 | * distributed under the License is distributed on an "AS IS" BASIS,
21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 | * See the License for the specific language governing permissions and
23 | * limitations under the License.
24 | */
25 | public class JodaTimeHDateTimeFormatTest {
26 | private HDateTimeFormat formatter;
27 |
28 | @Before
29 | public void setUp() {
30 | formatter = HDateTimeFormatBuilder.getInstance().forJodaTime().getFormatter();
31 | }
32 |
33 | @Test
34 | public void testCreatePatternFor() throws Exception {
35 | assertForPattern("MMMM d, YYYY", "June 9, 2011");
36 | assertForPattern("MMM d, YYYY", "Jun 9, 2011");
37 | assertForPattern("MMM dd", "Jun 09");
38 | assertForPattern("EEEE, MMMM d, YYYY", "Thursday, June 9, 2011");
39 | assertForPattern("EEE MMM d", "Thu Jun 9");
40 | assertForPattern("MM/dd/YY", "06/09/11");
41 | assertForPattern("hh:mm:ss a", "01:00:00 AM");
42 | assertForPattern("HH:mm", "20:52");
43 | assertForPattern("HH:mm:ss", "01:00:00");
44 | assertForPattern("HH:mm Z", "01:00 America/Los_Angeles");
45 | }
46 |
47 | private void assertForPattern(String dateTimePattern, String readablePattern) {
48 | DateTime now = DateTime.now();
49 | assertEquals(
50 | DateTimeFormat.forPattern(dateTimePattern).print(now),
51 | formatter.forPattern(readablePattern).print(DateTime.now())
52 | );
53 | }
54 | }
--------------------------------------------------------------------------------