2

I would like to fetch the current date / time based on the locale. If I pass locale object, I need to get the relevant date / time of the country.

Michu93
  • 5,058
  • 7
  • 47
  • 80
Sriram
  • 2,909
  • 8
  • 27
  • 35

3 Answers3

2

Since Java 8 you have LocalDateTime and ZonedDateTime

So you can do the same as @Babar said:

Get a zone id

ZoneId zoneId = ZoneId.of("Europe/Brussels");

And then get date and time

ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);

dehasi
  • 2,644
  • 1
  • 19
  • 31
  • What happens when zone (for example `"Europe/Zurich"`) have daylight saving? Will hour change automatically? – Michu93 Jan 18 '20 at 12:52
0
    public static void main(String[] arg){
        String[] timeZoneIDList = TimeZone.getAvailableIDs();
        //List of Time Zones
        for(String timeZoneID:timeZoneIDList){
            System.out.println(timeZoneID);
        }
        //What time is it in Fiji
        Calendar fijiCalendar = Calendar.getInstance(TimeZone.getTimeZone("Pacific/Fiji"));
        System.out.println("Time in Fiji->"+fijiCalendar.get(Calendar.HOUR)+":"+fijiCalendar.get(Calendar.MINUTE));
    }
zawhtut
  • 8,335
  • 5
  • 52
  • 76
  • How to know the country name from where the user is accessing ? – Sriram Apr 08 '11 at 10:49
  • @Sriram dantuch has already answered one solution. So another option is just ask the user to select the appropriate timezone for themselves if they do not want the default timezone offer by the application using host-name. – zawhtut Apr 10 '11 at 04:45
  • This way, 'm unable to get the Date. Giving a wrong value. Any alternative ? – Sriram Apr 12 '11 at 12:00
  • Yes `.getTime()` will not give you the relevant Date object with the above approach. But you can use `.get(Calendar.HOUR)`, `.get(Calendar.MONTH)` and so on to get a Date in string format. – zawhtut Apr 15 '11 at 02:30
0

If you use Joda Time then following should work. (Don't have the compiler at hand)

DateTimeZone tz = DateTimeZone.forID("America/Winnipeg");
DateTime dt = new DateTime(tz);

You can get the Timezone Ids here. Please check the link given by dantuch too.

Babar
  • 2,786
  • 3
  • 25
  • 35