0

I want to fetch the date and time based on user's location (country basically) and store it in table. For this I have tried below code, but I am not sure it fetches the server time or the timezone of user where he is located. Can someone please guide me to clear this doubt?

@RequestMapping(value = "/tzonee", method = RequestMethod.GET)
public static void main(String[] args) {

    // get Calendar instance
    Calendar now = Calendar.getInstance();

    // get current TimeZone using getTimeZone method of Calendar class
    TimeZone timeZone = now.getTimeZone();
    Date d = new Date();
    timeZone.getID();

    System.out.println("in day light time is:" + timeZone.getID());

    Calendar c = Calendar.getInstance(TimeZone.getTimeZone(timeZone.getID()));

    System.out.println("Timestamp is:" + c.getTime());
    // display current TimeZone using getDisplayName() method of TimeZone
    // class
    System.out.println("Current TimeZone is : " + timeZone.getDisplayName());
}
Vaibhav D
  • 7
  • 5
Pragati Kerur
  • 145
  • 1
  • 13
  • 1
    This should get the time according to the timezone of the server not the user. If you can, use JavaScript for this. – VPK Dec 15 '17 at 05:45
  • 1
    Country != Timezone, countries can have multiple timezones. – Jim Garrison Dec 15 '17 at 05:48
  • Thank you for quick reply.. I have country stored in table using which I need to display the date and time.. Is there any way how can I achieve it.? – Pragati Kerur Dec 15 '17 at 06:35
  • 1
    If you want to get the time according to the user's timezone you can use JavaScript. Refer this site's example: https://coderanch.com/t/486127/java/Query-timezone. BTW, I didn't understand this statement `'I have country stored in table using which I need to display the date and time'` – VPK Dec 15 '17 at 06:39
  • 1
    Most countries of the world have just a single time zone (but the biggest ones where maybe most of your users live have more). Even for small countries the translation isn’t trivial. Time zone names go like *region/city*, so if you know the country’s continent and capital, you have a chance of guessing the time zone. I know, it won’t be good enough. – Ole V.V. Dec 15 '17 at 07:58
  • 1
    Any reason why you are using the classes `Calendar`, `TimeZone` and `Date`? They are long outdated (almost 20 years old), and today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). I think you want `ZonedDateTime` and `ZoneId` and possibly `Instant`. – Ole V.V. Dec 15 '17 at 09:05
  • 2
    @VPK - A better solution for JavaScript is to get a time zone ID from the user (not the offset), [as described here](https://stackoverflow.com/q/22618056/634824). – Matt Johnson-Pint Dec 15 '17 at 18:25

0 Answers0