如何将给定的偏移时间(以秒为单位)转换为java中的+hh:mm格式



我想支持时区。。我用UTC时间将日期值存储在数据库中,然后根据用户的本地时区转换时间。。我在数据库查询中使用这一行

CONVERT_TZ(modifiedtime,'+00:00','+05:30')这将给我印度标准时间的本地时区。。。但我的问题是,我只有特定用户的偏移量(以秒为单位(和其他id。。

所以不管怎样,我可以将偏移量转换为类似+05:30 or say +04.00 ,+04.30..的格式有人能给我一个合适的解决方案吗?如果我能把这个以秒为单位的偏移量转换成+hh:mm这样的格式,这样我就可以直接把它给查询。。。

我使用的是liferay 6.1门户,因为我已经创建了我的自定义portlet。。所以我需要用java语言编写这段代码。。。那么请谁来指引我好吗?

下面的可能会短一点,方便一点

private static SimpleDateFormat plus = new SimpleDateFormat("+hh:mm");
private static SimpleDateFormat minus = new SimpleDateFormat("-hh:mm");
private static String getTimeCode(int seconds) {
    SimpleDateFormat simpleDateFormat = (seconds < 0) ? minus : plus;
    if (seconds < 0) seconds = 12 * 3600 - seconds;
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return simpleDateFormat.format(new Date(seconds * 1000));
}
int seconds = 5 * 3600 + 30 * 60;
String format = getTime(seconds); //+05:30
format = getTime(-1 * seconds);   //-05:30

上述代码可能不适用所有编码标准,但是SO 的缩写

您可以尝试编码自己的转换或尝试以下操作:

  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);

最新更新