Home > database >  Invalid java.util.TimeZone is automatically converted to GMT
Invalid java.util.TimeZone is automatically converted to GMT

Time:10-20

I am using java.util.TimeZone to get a time-zone in a json request, but when an invalid time-zone is provided, it is automatically converted to GMT, as shown in the code below. So, how can I avoid that automatic conversion so that I know that the provided time-zone is not valid?

import java.util.*;

public class MyClass {
    
    public static void main(String args[]) {

        TimeZone tz = TimeZone.getTimeZone("invalid time zone");
        
        System.out.println( tz.getID() ); //this prints GMT instead of "invalid time zone"
      
    }
}

CodePudding user response:

Java has 3 completely separate APIs for 'date stuff'.

  • There's java.util.Date (as well as TimeZone, which is what you use here, and a bunch of things that hang off of this, such as java.sql.Timestamp which inherits it).

  • There's java.util.Calendar (and GregorianCalendar and a few others).

  • There's everything in the java.time package.

Why are there 3 APIs? Because the Date one is so incredibly boneheaded, it needed to be replaced. Unfortunately, the replacement was even worse, so that too needed to be replaced. Fortunately, the third time really was the charm, and java.time is fantastic.

SOLUTION: Don't use the old obsolete bad APIs. If it starts with java.util, you don't want it.

You want java.time.ZoneId which represents an actual zone. This is something like Europe/Amsterdam, not something useless, like CEST or even the most useless, 01:00. Those latter two are fragile as all get out and do not allow any actual math. For example, an offset-based zone doesn't let you 'add an hour' - depending on where on the planet an appointment was made, 'add an hour' can mean different things (Daylight Savings Time is a thing!). CEST is too broad; the places on the planet that 'use CEST' changes all the time. Case in point: The EU passed a motion that all EU countries should move away from DST. But not all of the EU may choose the same zone to 'stick to', so that's an upcoming change of definition right there already.

If nevertheless you have one of these mostly useless zones, java.time.ZoneOffset can represent this.

They will error if you provide gobbledygook.

CodePudding user response:

You can use java.time.ZoneId.of, which will throw an Exception for an invalid zone.

import java.time.ZoneId;
import java.time.DateTimeException;
// ...
try {
    ZoneId zone = ZoneId.of("invalid time zone");
    System.out.println(zone);
} catch(DateTimeException e){
    System.out.println("Invalid time zone");
}
  •  Tags:  
  • java
  • Related