Search code examples
javatimezoneliferayconvert-tz

how to convert given offset time(in seconds) to Format like +hh:mm in java?


i want to give support of timezone..for that am storing the value of date in the database with the UTC Time and then i am converting the time depends on the user local time zone..for that am using this line in my database query

CONVERT_TZ(modifiedtime,'+00:00','+05:30') this will give me local time zone for the Indian Standard time...but my question is i have only offset in econds and ther id for the particular user..

so is ther anyway that i can convert offset to format like +05:30 or say +04.00 ,+04.30.. can anyone give me proper solution that if i can convert this offset which is given in seconds to format like +hh:mm so i can directly give it to query...

Am using liferay 6.1 portal in that i have created My custom portlet..so i need to make it this code in java language...so please can any one guide me?


Solution

  • you could try coding your own conversion or try this:

      long offset = 19800; //offset IST (seconds)
      long time = TimeUnit.SECONDS.toMinutes(offset); //or offset/60
      long hour = time / 60;
      long min = Math.abs(time % 60);
      String hrStr = "";
      if (hour > 0 && hour < 10) {
        hrStr = "+0" + String.valueOf(hour);
      } else if (hour >= 10) {
        hrStr = "+" + String.valueOf(hour);
      } else if (hour < 0 && hour > -10) {
        hrStr = "-0" + String.valueOf(hour).substring(1);
      } else {
        hrStr = String.valueOf(hour);
      }
      String minStr = String.valueOf(min);
      if (min < 10) {
        minStr = "0" + (time % 60);
      }
      String timeStr = hrStr + ":" + minStr;
      System.out.println(timeStr);