├── .gitignore ├── .travis.settings.xml ├── .travis.yml ├── LICENSE.md ├── README.md ├── pom.xml ├── timezone-core ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── graphhopper │ └── timezone │ └── core │ ├── TZShapeReader.java │ └── TimeZones.java ├── timezone-webapp ├── app.yml ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── graphhopper │ └── timezone │ └── webservice │ ├── App.java │ ├── AppConfig.java │ ├── api │ ├── LocalTime.java │ └── TimeZoneResponse.java │ └── resources │ └── TimeZoneService.java └── world-data ├── tz_world.dbf ├── tz_world.png ├── tz_world.prj ├── tz_world.shp └── tz_world.shx /.gitignore: -------------------------------------------------------------------------------- 1 | /bin 2 | /target 3 | /output 4 | /in 5 | /input 6 | .DS_Store 7 | *~ 8 | vrp-app-old.log 9 | vrp-app.log 10 | *log.gz 11 | /logs/ 12 | 13 | # Netbeans 14 | nbactions.xml 15 | 16 | # IntelliJ 17 | *.ipr 18 | *.iws 19 | *.iml 20 | .idea/ 21 | 22 | # Eclipse 23 | .project 24 | .classpath 25 | -------------------------------------------------------------------------------- /.travis.settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | packagecloud-maiBlivnok 5 | ${env.PACKAGECLOUD_TOKEN} 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | # do not install anything instead return true via unix command true 5 | install: true 6 | script: mvn clean test 7 | notifications: 8 | email: 9 | - github@graphhopper.com 10 | 11 | # enable container-based stack 12 | sudo: false 13 | 14 | deploy: 15 | provider: script 16 | script: "cp .travis.settings.xml $HOME/.m2/settings.xml && mvn deploy" 17 | skip_cleanup: true 18 | on: 19 | tags: true 20 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | Apache License 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "[]" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright [yyyy] [name of copyright owner] 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | timezone 2 | ======== 3 | ![Build Status](https://travis-ci.org/graphhopper/timezone.svg?branch=master) 4 | 5 | Requires Java 1.8. 6 | 7 | ## Timezone Core 8 | 9 | The timezone project can be imported into your project and run by directly interfacing with the public methods, without needing to start the web service. Add the project as a dependency and create a new `TimeZones` object, which can be interacted with through `.getTimeZone()` and `.getOffsetDateTime()` including all local time and timezone information such as current time in the timezone and offset from GMT. 10 | 11 | Example: 12 | 13 | ```java 14 | TimeZones timeZones = new TimeZones(); 15 | timeZones.initWithWorldData(new File("./world-data/tz_world.shp").toURI().toURL()); 16 | 17 | TimeZone tz = timeZones.getTimeZone(40.713956,-75.767577); 18 | long unixTimeStamp = 1488363179; 19 | OffsetDateTime offsetDateTime = timeZones.getOffsetDateTime(unixTimeStamp,tz); 20 | System.out.println(offsetDateTime); 21 | 22 | //or even shorter 23 | OffsetDateTime offsetDateTime2 = timeZones.getOffsetDateTime(unixTimeStamp,40.713956,-75.767577); 24 | System.out.println(offsetDateTime2); 25 | ``` 26 | 27 | ## Timezone Webapp 28 | Our timezone app turns your location and timestamp into timezone and local time. Thus, if you need local time in your application, just ask GraphHopper timezone. It is microservice you can run wherever you like. 29 | 30 | ### Example 31 | 32 | #### Example 1 33 | 34 | request: `http://localhost:8080/timezone?timestamp=1488363179&location=40.713956,-75.767577` 35 | 36 | response: 37 | 38 | ```json 39 | { 40 | 41 | "timezone": "America/New_York", 42 | "timezone_name": "Eastern Standard Time", 43 | "local_time": { 44 | "offset": -18000, 45 | "year": 2017, 46 | "month": "March", 47 | "day_of_month": 2, 48 | "day_of_week": "Thursday", 49 | "month_value": 3, 50 | "hour": 16, 51 | "minute": 19, 52 | "second": 52, 53 | "nano": 0 54 | } 55 | 56 | } 57 | 58 | ``` 59 | 60 | #### Example 2 61 | 62 | request: `http://localhost:8080/timezone?timestamp=1488489592&location=48.873748,2.344482&language=fr` 63 | 64 | response: 65 | 66 | ```json 67 | { 68 | "timezone": "Europe/Paris", 69 | "timezone_name": "Heure d'Europe centrale", 70 | "local_time": { 71 | "offset": 3600, 72 | "year": 2017, 73 | "month": "mars", 74 | "day_of_month": 2, 75 | "day_of_week": "jeudi", 76 | "month_value": 3, 77 | "hour": 22, 78 | "minute": 19, 79 | "second": 52, 80 | "nano": 0 81 | } 82 | } 83 | 84 | ``` 85 | 86 | #### Example 3 87 | 88 | request: `http://localhost:8080/timezone?timestamp=1488489592&location=36.031332,138.796876&language=ja` 89 | 90 | response: 91 | 92 | ```json 93 | { 94 | "timezone": "Asia/Tokyo", 95 | "timezone_name": "日本標準時", 96 | "local_time": { 97 | "offset": 32400, 98 | "year": 2017, 99 | "month": "3月", 100 | "day_of_month": 3, 101 | "day_of_week": "金曜日", 102 | "month_value": 3, 103 | "hour": 6, 104 | "minute": 19, 105 | "second": 52, 106 | "nano": 0 107 | } 108 | } 109 | 110 | ``` 111 | 112 | try your own example: 113 | - get current unix timestamp from here: http://www.unixtimestamp.com/ 114 | - and coordinates from here: https://graphhopper.com/maps/ (just right click wherever you like to specify start and you will be provided with the coordinates in the start field. just copy and paste it as it is) 115 | 116 | ### Input & Output 117 | 118 | You need to specify two parameters, (Unix) timestamp and location (lat,lon), and you will be provided with the according timezone, local time and offset to UTC. Local time and offset consider daylight saving time (dst). 119 | 120 | Input: 121 | 122 | Parameter | Description 123 | :------|:----- 124 | timestamp | Unix timestamp (in seconds) 125 | location | latitude, longitude 126 | language | optional, default is 'en' - see the supported languages [here](http://www.oracle.com/technetwork/java/javase/javase7locales-334809.html) 127 | 128 | Output: 129 | 130 | Name | Description 131 | :------|:----- 132 | timezone | time zone id as defined here: http://efele.net/maps/tz/world/ 133 | timezone_name | full name of time zone 134 | local_time | local time information considering daylight saving time 135 | 136 | local_time: 137 | 138 | Name | Description 139 | :------|:----- 140 | offset | offset to UTC in seconds 141 | year | - 142 | month | - 143 | day_of_month | - 144 | day_of_week | - 145 | month_value | - 146 | hour | - 147 | minute | - 148 | second | - 149 | nano | - 150 | 151 | ## TZ data 152 | Make sure that you have updated your java environment with the latest tz data, otherwise old DST data might yield wrong local times. For example, such events ["Russia Returns to Standard Time All Year"](https://www.timeanddate.com/news/time/russia-abandons-permanent-summer-time.html) cause wrong local time calculations if you have not updated your JRE/JDK. You can update it as described here: 153 | 154 | http://www.oracle.com/technetwork/java/javase/tzupdater-readme-136440.html 155 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | timezone 8 | timezone 9 | 2.0.1-SNAPSHOT 10 | 11 | 12 | timezone-core 13 | timezone-webapp 14 | 15 | 16 | pom 17 | 18 | timezone 19 | It turns location and unix timestamp into timezone and local time. 20 | https://github.com/graphhopper/timezone 21 | 2017 22 | 23 | 24 | 25 | Apache License, Version 2.0 26 | http://www.apache.org/licenses/LICENSE-2.0 27 | 28 | 29 | 30 | 31 | 32 | Stefan Schroeder 33 | my.name@graphhopper.com 34 | 35 | 36 | 37 | 38 | scm:git:git@github.com:graphhopper/timezone.git 39 | scm:git:https://github.com/graphhopper/timezone.git 40 | http://github.com/graphhopper/timezone/tree/master 41 | HEAD 42 | 43 | 44 | 45 | github 46 | https://github.com/graphhopper/timezone/issues 47 | 48 | 49 | 50 | 0.9.2 51 | 2.7.3 52 | UTF-8 53 | 54 | 55 | 56 | 57 | packagecloud-maiBlivnok 58 | packagecloud+https://packagecloud.io/maiBlivnok/timezone 59 | 60 | 61 | packagecloud-maiBlivnok 62 | packagecloud+https://packagecloud.io/maiBlivnok/timezone 63 | 64 | 65 | 66 | 67 | 68 | 69 | com.vividsolutions 70 | jts 71 | 1.13 72 | 73 | 74 | 75 | org.geotools 76 | gt-shapefile 77 | 16.2 78 | 79 | 80 | 81 | io.dropwizard 82 | dropwizard-core 83 | ${dropwizard.version} 84 | 85 | 86 | 87 | io.dropwizard 88 | dropwizard-metrics 89 | ${dropwizard.version} 90 | 91 | 92 | 93 | io.dropwizard 94 | dropwizard-testing 95 | ${dropwizard.version} 96 | 97 | 98 | 99 | io.dropwizard 100 | dropwizard-assets 101 | ${dropwizard.version} 102 | 103 | 104 | 105 | 106 | 107 | osgeo 108 | Open Source Geospatial Foundation Repository 109 | http://download.osgeo.org/webdav/geotools/ 110 | 111 | 112 | 113 | 114 | 115 | 116 | io.packagecloud.maven.wagon 117 | maven-packagecloud-wagon 118 | 0.0.4 119 | 120 | 121 | 122 | 123 | 124 | 125 | org.apache.maven.plugins 126 | maven-compiler-plugin 127 | 3.3 128 | 129 | 1.8 130 | 1.8 131 | 132 | 133 | 134 | 135 | org.apache.maven.plugins 136 | maven-surefire-plugin 137 | 2.19.1 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | org.apache.maven.plugins 146 | maven-jar-plugin 147 | 2.4 148 | 149 | 150 | 151 | true 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | selected-build 164 | 165 | timezone-core 166 | 167 | 168 | 169 | release 170 | 171 | false 172 | 173 | 174 | 175 | 176 | org.apache.maven.plugins 177 | maven-gpg-plugin 178 | 1.6 179 | 180 | 181 | sign-artifacts 182 | verify 183 | 184 | sign 185 | 186 | 187 | 188 | 189 | 190 | org.sonatype.plugins 191 | nexus-staging-maven-plugin 192 | 1.6.7 193 | true 194 | 195 | ossrh 196 | https://oss.sonatype.org/ 197 | true 198 | 199 | 200 | 201 | 202 | org.apache.maven.plugins 203 | maven-javadoc-plugin 204 | 2.10.3 205 | 206 | 207 | attach-javadocs 208 | 209 | jar 210 | 211 | 212 | 213 | 214 | 215 | org.apache.maven.plugins 216 | maven-source-plugin 217 | 3.0.0 218 | 219 | 220 | attach-sources 221 | 222 | jar-no-fork 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | -------------------------------------------------------------------------------- /timezone-core/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | timezone 7 | timezone 8 | 2.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | timezone-core 13 | 14 | 15 | -------------------------------------------------------------------------------- /timezone-core/src/main/java/com/graphhopper/timezone/core/TZShapeReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to GraphHopper GmbH under one or more contributor 3 | * license agreements. See the NOTICE file distributed with this work for 4 | * additional information regarding copyright ownership. 5 | * 6 | * GraphHopper GmbH licenses this file to you under the Apache License, 7 | * Version 2.0 (the "License"); you may not use this file except in 8 | * compliance with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.graphhopper.timezone.core; 20 | 21 | import com.vividsolutions.jts.index.quadtree.Quadtree; 22 | import org.geotools.data.DataStore; 23 | import org.geotools.data.DataStoreFinder; 24 | import org.geotools.data.FeatureSource; 25 | import org.geotools.feature.FeatureCollection; 26 | import org.geotools.feature.FeatureIterator; 27 | import org.geotools.geometry.jts.ReferencedEnvelope; 28 | import org.opengis.feature.simple.SimpleFeature; 29 | import org.opengis.feature.simple.SimpleFeatureType; 30 | 31 | import java.io.IOException; 32 | import java.net.URL; 33 | import java.util.HashMap; 34 | import java.util.Map; 35 | 36 | /** 37 | * Created by schroeder on 01/03/17. 38 | */ 39 | public class TZShapeReader { 40 | 41 | private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TZShapeReader.class); 42 | 43 | private Quadtree quadtree; 44 | 45 | public TZShapeReader(Quadtree quadtree) { 46 | this.quadtree = quadtree; 47 | } 48 | 49 | public void read(URL file) throws IOException { 50 | Map map = new HashMap<>(); 51 | map.put("url", file); 52 | FeatureIterator features = null; 53 | DataStore dataStore = null; 54 | int count = 0; 55 | try{ 56 | dataStore = DataStoreFinder.getDataStore(map); 57 | String typeName = dataStore.getTypeNames()[0]; 58 | FeatureSource source = dataStore.getFeatureSource(typeName); 59 | FeatureCollection collection = source.getFeatures(); 60 | features = collection.features(); 61 | LOGGER.info("reading world time zones ..."); 62 | while (features.hasNext()) { 63 | count++; 64 | SimpleFeature feature = features.next(); 65 | ReferencedEnvelope referencedEnvelope = new ReferencedEnvelope(feature.getBounds()); 66 | quadtree.insert(referencedEnvelope,feature); 67 | } 68 | } catch (Exception e) { 69 | throw new RuntimeException(e); 70 | } finally { 71 | if (features != null) 72 | features.close(); 73 | if (dataStore != null) 74 | dataStore.dispose(); 75 | } 76 | LOGGER.info(count + " features read"); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /timezone-core/src/main/java/com/graphhopper/timezone/core/TimeZones.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to GraphHopper GmbH under one or more contributor 3 | * license agreements. See the NOTICE file distributed with this work for 4 | * additional information regarding copyright ownership. 5 | * 6 | * GraphHopper GmbH licenses this file to you under the Apache License, 7 | * Version 2.0 (the "License"); you may not use this file except in 8 | * compliance with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.graphhopper.timezone.core; 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | import java.net.MalformedURLException; 24 | import java.net.URL; 25 | import java.time.Instant; 26 | import java.time.OffsetDateTime; 27 | import java.time.ZoneId; 28 | import java.util.List; 29 | import java.util.TimeZone; 30 | 31 | import org.geotools.geometry.jts.JTSFactoryFinder; 32 | import org.opengis.feature.simple.SimpleFeature; 33 | 34 | import com.vividsolutions.jts.geom.Coordinate; 35 | import com.vividsolutions.jts.geom.Geometry; 36 | import com.vividsolutions.jts.geom.GeometryFactory; 37 | import com.vividsolutions.jts.geom.Point; 38 | import com.vividsolutions.jts.index.quadtree.Quadtree; 39 | 40 | public class TimeZones { 41 | 42 | private GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); 43 | 44 | private Quadtree quadtree; 45 | 46 | public void initWithWorldData(URL worldDataShp) throws IOException { 47 | this.quadtree = new Quadtree(); 48 | new TZShapeReader(quadtree).read(worldDataShp); 49 | } 50 | 51 | public Quadtree getQuadtree() { 52 | return this.quadtree; 53 | } 54 | 55 | public OffsetDateTime getOffsetDateTime(long epochSecond, double lat, double lon){ 56 | OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), ZoneId.of(getTimeZone(lat,lon).getID())); 57 | return offsetDateTime; 58 | } 59 | 60 | public OffsetDateTime getOffsetDateTime(long epochSecond, TimeZone timeZone){ 61 | OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), ZoneId.of(timeZone.getID())); 62 | return offsetDateTime; 63 | } 64 | 65 | 66 | public TimeZone getTimeZone(double lat, double lon) { 67 | Point point = geometryFactory.createPoint(new Coordinate(lon,lat)); 68 | List regions = quadtree.query(point.getEnvelopeInternal()); 69 | for(Object o : regions){ 70 | SimpleFeature feature = (SimpleFeature) o; 71 | Geometry geom = (Geometry) feature.getDefaultGeometry(); 72 | if(point.within(geom)) { 73 | return TimeZone.getTimeZone((String)(feature.getAttribute("TZID"))); 74 | } 75 | } 76 | //not found, thus find nearest time zone 77 | double minDistance = Double.MAX_VALUE; 78 | SimpleFeature minFeature = null; 79 | for(Object o : regions){ 80 | SimpleFeature feature = (SimpleFeature) o; 81 | Geometry geom = (Geometry) feature.getDefaultGeometry(); 82 | double distance = point.distance(geom); 83 | if(distance < minDistance){ 84 | minFeature = feature; 85 | minDistance = distance; 86 | } 87 | } 88 | if(minFeature != null) { 89 | return TimeZone.getTimeZone((String) (minFeature.getAttribute("TZID"))); 90 | } 91 | throw new IllegalStateException("could not determine a time zone for location: " + lat + ", " + lon); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /timezone-webapp/app.yml: -------------------------------------------------------------------------------- 1 | # general settings: 2 | # http://www.dropwizard.io/manual/configuration.html 3 | 4 | server: 5 | applicationConnectors: 6 | - type: http 7 | port: 8080 8 | 9 | adminConnectors: 10 | - type: http 11 | port: 8081 12 | 13 | logging: 14 | level: INFO 15 | 16 | loggers: 17 | "org.hibernate": INFO 18 | 19 | appenders: 20 | - type: console 21 | timeZone: UTC 22 | logFormat: "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" 23 | 24 | worldDataLocation: "/Users/schroeder/IdeaProjects/timezone/world-data/tz_world.shp" 25 | 26 | -------------------------------------------------------------------------------- /timezone-webapp/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | timezone 7 | timezone 8 | 2.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | timezone-webapp 13 | 14 | 15 | 16 | timezone 17 | timezone-core 18 | 2.0.1-SNAPSHOT 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /timezone-webapp/src/main/java/com/graphhopper/timezone/webservice/App.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to GraphHopper GmbH under one or more contributor 3 | * license agreements. See the NOTICE file distributed with this work for 4 | * additional information regarding copyright ownership. 5 | * 6 | * GraphHopper GmbH licenses this file to you under the Apache License, 7 | * Version 2.0 (the "License"); you may not use this file except in 8 | * compliance with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.graphhopper.timezone.webservice; 20 | 21 | import com.graphhopper.timezone.core.TimeZones; 22 | 23 | import com.graphhopper.timezone.webservice.resources.TimeZoneService; 24 | import io.dropwizard.Application; 25 | import io.dropwizard.assets.AssetsBundle; 26 | import io.dropwizard.setup.Bootstrap; 27 | import io.dropwizard.setup.Environment; 28 | import org.eclipse.jetty.servlets.CrossOriginFilter; 29 | 30 | import javax.servlet.DispatcherType; 31 | import javax.servlet.FilterRegistration; 32 | import java.io.File; 33 | import java.io.IOException; 34 | import java.util.EnumSet; 35 | 36 | /** 37 | * Created by schroeder on 22/12/14. 38 | */ 39 | public class App extends Application { 40 | 41 | /* 42 | 43 | @ToDo remove meta info 44 | @ToDo more stats such as expected waiting time queue 45 | 46 | */ 47 | public static void main(String[] args) throws Exception { 48 | new App().run(args); 49 | } 50 | 51 | @Override 52 | public String getName() { 53 | return "timezone app"; 54 | } 55 | 56 | @Override 57 | public void initialize(Bootstrap bootstrap) { 58 | 59 | // we need only the spec json to be in sync with repo 60 | bootstrap.addBundle(new AssetsBundle("/assets", "/lib", null, "lib")); 61 | } 62 | 63 | @Override 64 | public void run(AppConfig configuration, Environment environment) throws IOException { 65 | 66 | // Enable CORS headers 67 | final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); 68 | 69 | // Configure CORS parameters 70 | cors.setInitParameter("allowedOrigins", "*"); 71 | cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin"); 72 | cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); 73 | 74 | // Add URL mapping 75 | cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); 76 | 77 | TimeZones timeZones = new TimeZones(); 78 | timeZones.initWithWorldData(new File(configuration.getWorldDataLocation()).toURI().toURL()); 79 | TimeZoneService timeZoneService = new TimeZoneService(timeZones); 80 | 81 | environment.jersey().register(timeZoneService); 82 | 83 | // // healthChecks 84 | // environment.healthChecks().register("app-health-check", new AppHealthCheck()); 85 | // 86 | // // filter 87 | // environment.servlets().addFilter("ip-filter", new IPFilter(configuration.getIPWhiteList(), configuration.getIPBlackList())).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /timezone-webapp/src/main/java/com/graphhopper/timezone/webservice/AppConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to GraphHopper GmbH under one or more contributor 3 | * license agreements. See the NOTICE file distributed with this work for 4 | * additional information regarding copyright ownership. 5 | * 6 | * GraphHopper GmbH licenses this file to you under the Apache License, 7 | * Version 2.0 (the "License"); you may not use this file except in 8 | * compliance with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.graphhopper.timezone.webservice; 20 | 21 | import com.fasterxml.jackson.annotation.JsonProperty; 22 | 23 | /** 24 | * Created by schroeder on 22/12/14. 25 | */ 26 | public class AppConfig extends io.dropwizard.Configuration { 27 | 28 | // private String ipBlackList = ""; 29 | // 30 | // private String ipWhiteList = ""; 31 | 32 | @JsonProperty("worldDataLocation") 33 | private String worldDataLocation = ""; 34 | 35 | // @JsonProperty(value = "ipBlackList") 36 | // public String getIPBlackList() { 37 | // return ipBlackList; 38 | // } 39 | // 40 | // @JsonProperty(value = "ipBlackList") 41 | // public void setIPBlackList(String ipBlackList) { 42 | // this.ipBlackList = ipBlackList; 43 | // } 44 | // 45 | // @JsonProperty(value = "ipWhiteList") 46 | // public String getIPWhiteList() { 47 | // return ipWhiteList; 48 | // } 49 | // 50 | // @JsonProperty(value = "ipWhiteList") 51 | // public void setIPWhiteList(String ipWhiteList) { 52 | // this.ipWhiteList = ipWhiteList; 53 | // } 54 | 55 | public String getWorldDataLocation(){ 56 | return worldDataLocation; 57 | } 58 | 59 | public void setWorldDataLocation(String worldDataLocation){ 60 | this.worldDataLocation = worldDataLocation; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /timezone-webapp/src/main/java/com/graphhopper/timezone/webservice/api/LocalTime.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to GraphHopper GmbH under one or more contributor 3 | * license agreements. See the NOTICE file distributed with this work for 4 | * additional information regarding copyright ownership. 5 | * 6 | * GraphHopper GmbH licenses this file to you under the Apache License, 7 | * Version 2.0 (the "License"); you may not use this file except in 8 | * compliance with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.graphhopper.timezone.webservice.api; 20 | 21 | import com.fasterxml.jackson.annotation.JsonProperty; 22 | 23 | import java.time.OffsetDateTime; 24 | import java.time.format.TextStyle; 25 | import java.util.Locale; 26 | 27 | /** 28 | * Created by schroeder on 02/03/17. 29 | */ 30 | public class LocalTime { 31 | 32 | private final int offset; 33 | private final String offsetString; 34 | private final int year; 35 | private final String month; 36 | private final int dayOfMonth; 37 | private final String dayOfWeek; 38 | private final int monthValue; 39 | private final int hour; 40 | private final int minute; 41 | private final int second; 42 | private final int nano; 43 | 44 | public LocalTime(OffsetDateTime offsetDateTime, Locale locale) { 45 | offset = offsetDateTime.getOffset().getTotalSeconds(); 46 | offsetString = offsetDateTime.getOffset().toString(); 47 | year = offsetDateTime.getYear(); 48 | month = offsetDateTime.getMonth().getDisplayName(TextStyle.FULL,locale); 49 | dayOfMonth = offsetDateTime.getDayOfMonth(); 50 | dayOfWeek = offsetDateTime.getDayOfWeek().getDisplayName(TextStyle.FULL,locale); 51 | monthValue = offsetDateTime.getMonthValue(); 52 | hour = offsetDateTime.getHour(); 53 | minute = offsetDateTime.getMinute(); 54 | second = offsetDateTime.getSecond(); 55 | nano = offsetDateTime.getNano(); 56 | } 57 | 58 | public LocalTime(OffsetDateTime offsetDateTime) { 59 | this(offsetDateTime, Locale.forLanguageTag("en")); 60 | } 61 | 62 | @JsonProperty("offset") 63 | public int getOffset() { 64 | return offset; 65 | } 66 | 67 | @JsonProperty("offset_string") 68 | public String getOffsetString() { 69 | return "GMT" + offsetString; 70 | } 71 | 72 | @JsonProperty("day_of_month") 73 | public int getDayOfMonth() { 74 | return dayOfMonth; 75 | } 76 | 77 | @JsonProperty("day_of_week") 78 | public String getDayOfWeek() { 79 | return dayOfWeek; 80 | } 81 | 82 | @JsonProperty("month_value") 83 | public int getMonthValue() { 84 | return monthValue; 85 | } 86 | 87 | @JsonProperty("hour") 88 | public int getHour() { 89 | return hour; 90 | } 91 | 92 | @JsonProperty("minute") 93 | public int getMinute() { 94 | return minute; 95 | } 96 | 97 | @JsonProperty("second") 98 | public int getSecond() { 99 | return second; 100 | } 101 | 102 | @JsonProperty("nano") 103 | public int getNano() { 104 | return nano; 105 | } 106 | 107 | @JsonProperty("year") 108 | public int getYear() { 109 | return year; 110 | } 111 | 112 | @JsonProperty("month") 113 | public String getMonth() { 114 | return month; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /timezone-webapp/src/main/java/com/graphhopper/timezone/webservice/api/TimeZoneResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to GraphHopper GmbH under one or more contributor 3 | * license agreements. See the NOTICE file distributed with this work for 4 | * additional information regarding copyright ownership. 5 | * 6 | * GraphHopper GmbH licenses this file to you under the Apache License, 7 | * Version 2.0 (the "License"); you may not use this file except in 8 | * compliance with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.graphhopper.timezone.webservice.api; 20 | 21 | import com.fasterxml.jackson.annotation.JsonProperty; 22 | 23 | 24 | import javax.validation.constraints.NotNull; 25 | 26 | /** 27 | * Created by schroeder on 01/03/17. 28 | */ 29 | public class TimeZoneResponse { 30 | 31 | @NotNull 32 | private String timeZoneId; 33 | 34 | private String displayName; 35 | 36 | private LocalTime localTime; 37 | 38 | public TimeZoneResponse(String timeZoneId, LocalTime localTime, String displayName) { 39 | this.timeZoneId = timeZoneId; 40 | this.localTime = localTime; 41 | this.displayName = displayName; 42 | } 43 | 44 | @JsonProperty("timezone") 45 | public String getTimeZoneId() { 46 | return timeZoneId; 47 | } 48 | 49 | @JsonProperty("timezone_name") 50 | public String getDisplayName() { 51 | return displayName; 52 | } 53 | 54 | @JsonProperty("local_time") 55 | public LocalTime getLocalTime() { 56 | return localTime; 57 | } 58 | 59 | public String toString() { 60 | return timeZoneId + " (" + displayName + " : " + localTime.getOffsetString() + ")"; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /timezone-webapp/src/main/java/com/graphhopper/timezone/webservice/resources/TimeZoneService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to GraphHopper GmbH under one or more contributor 3 | * license agreements. See the NOTICE file distributed with this work for 4 | * additional information regarding copyright ownership. 5 | * 6 | * GraphHopper GmbH licenses this file to you under the Apache License, 7 | * Version 2.0 (the "License"); you may not use this file except in 8 | * compliance with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | package com.graphhopper.timezone.webservice.resources; 19 | 20 | 21 | import com.codahale.metrics.annotation.Timed; 22 | import com.graphhopper.timezone.core.TimeZones; 23 | 24 | import com.graphhopper.timezone.webservice.api.LocalTime; 25 | import com.graphhopper.timezone.webservice.api.TimeZoneResponse; 26 | import io.dropwizard.jersey.errors.ErrorMessage; 27 | 28 | import javax.ws.rs.*; 29 | 30 | import javax.ws.rs.core.Context; 31 | import javax.ws.rs.core.MediaType; 32 | import javax.ws.rs.core.Response; 33 | import javax.ws.rs.core.UriInfo; 34 | import java.time.OffsetDateTime; 35 | import java.util.ArrayList; 36 | import java.util.List; 37 | import java.util.Locale; 38 | import java.util.TimeZone; 39 | 40 | import static javax.ws.rs.core.Response.Status.BAD_REQUEST; 41 | 42 | @Path("/timezone") 43 | @Consumes(MediaType.APPLICATION_JSON) 44 | @Produces(MediaType.APPLICATION_JSON) 45 | public class TimeZoneService { 46 | 47 | private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TimeZoneService.class); 48 | 49 | private TimeZones timeZones; 50 | 51 | public TimeZoneService(TimeZones timeZoneReader) { 52 | this.timeZones = timeZoneReader; 53 | } 54 | 55 | @GET 56 | @Timed 57 | public Response handle(@Context UriInfo uriInfo){ 58 | List location = new ArrayList<>(); 59 | if(uriInfo.getQueryParameters().containsKey("location")) { 60 | location = uriInfo.getQueryParameters().get("location"); 61 | if (location.size() != 1) 62 | throwError(BAD_REQUEST.getStatusCode(), "only one location needs to be specified"); 63 | } 64 | else throwError(BAD_REQUEST.getStatusCode(), "location missing. a location needs to be specified");; 65 | List timestamps = new ArrayList<>(); 66 | if(uriInfo.getQueryParameters().containsKey("timestamp")) { 67 | timestamps = uriInfo.getQueryParameters().get("timestamp"); 68 | if (timestamps.size() != 1) 69 | throwError(BAD_REQUEST.getStatusCode(), "only one unix timestamp needs to be specified"); 70 | } 71 | else throwError(BAD_REQUEST.getStatusCode(), "timestamp missing. unix timestamp needs to be specified"); 72 | Locale locale = Locale.forLanguageTag("en"); 73 | if(uriInfo.getQueryParameters().containsKey("language")) { 74 | List languages = uriInfo.getQueryParameters().get("language"); 75 | if (languages.size() != 1) throwError(BAD_REQUEST.getStatusCode(), "only one language needs to be specified"); 76 | locale = Locale.forLanguageTag(languages.get(0)); 77 | } 78 | 79 | String[] locationTokens = location.get(0).split(","); 80 | 81 | double lat = Double.parseDouble(locationTokens[0]); 82 | double lon = Double.parseDouble(locationTokens[1]); 83 | long timestamp = Long.parseLong(timestamps.get(0)); 84 | 85 | String timeZoneId = timeZones.getTimeZone(lat,lon).getID(); 86 | 87 | if(timeZoneId == null) { 88 | throwError(BAD_REQUEST.getStatusCode(),"could not localize location " + lat + ", " + lon); 89 | } 90 | 91 | TimeZone timeZone = TimeZone.getTimeZone(timeZoneId); 92 | OffsetDateTime localTime = timeZones.getOffsetDateTime(timestamp,timeZone); 93 | 94 | String displayName = timeZone.getDisplayName(locale); 95 | TimeZoneResponse timeZoneResponse = new TimeZoneResponse(timeZoneId, new LocalTime(localTime,locale), displayName); 96 | return Response.status(Response.Status.OK).entity(timeZoneResponse).build(); 97 | } 98 | 99 | private void throwError(int statusCode, String msg){ 100 | ErrorMessage errorMessage = new ErrorMessage(statusCode, msg); 101 | throw new WebApplicationException(errorMessage.getMessage(), Response.status(statusCode) 102 | .entity(errorMessage) 103 | .type(MediaType.APPLICATION_JSON). 104 | build()); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /world-data/tz_world.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/graphhopper/timezone/7220c5d63e6d78849a5485edd9c31c0f85fec350/world-data/tz_world.png -------------------------------------------------------------------------------- /world-data/tz_world.prj: -------------------------------------------------------------------------------- 1 | GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]] -------------------------------------------------------------------------------- /world-data/tz_world.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/graphhopper/timezone/7220c5d63e6d78849a5485edd9c31c0f85fec350/world-data/tz_world.shp -------------------------------------------------------------------------------- /world-data/tz_world.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/graphhopper/timezone/7220c5d63e6d78849a5485edd9c31c0f85fec350/world-data/tz_world.shx --------------------------------------------------------------------------------