How do you convert 2 dates one in BST(Current date) and the other in GMT so that the can be compared date before and after methods?

爱⌒轻易说出口 提交于 2019-12-02 02:29:27

What about:

Calendar calBst = new GregorianCalander();
calBst.setDate(date1);
calBst.setTimezone(TimeZone.getTimeZone("BST");

Calendar calGmt = new GregorianCalander();
calGmt.setDate(date2);
calGmt.setTimezone(TimeZone.getTimeZone("GMT");
calBst.before(calGmt);

I had the same problem and finding the answer was not evident. We are using this solution in production now and it works fine. It's based on jodatime library

public static Date convertDateTimeZone(Date date, TimeZone currentTimeZone, TimeZone newTimeZone) {
    return convertJodaTimezone(new LocalDateTime(date), DateTimeZone.forTimeZone(currentTimeZone), DateTimeZone.forTimeZone(newTimeZone));
}

public static Date convertDateTimeZone(Date date, TimeZone newTimeZone) {
    return convertDateTimeZone(date, null, newTimeZone);
}

public static Date convertJodaTimezone(LocalDateTime date, String srcTz, String destTz) {
    return convertJodaTimezone(date, DateTimeZone.forID(srcTz), DateTimeZone.forID(destTz));
}

public static Date convertJodaTimezone(LocalDateTime date, DateTimeZone srcTz, DateTimeZone destTz) {
    DateTime srcDateTime = date.toDateTime(srcTz);
    DateTime dstDateTime = srcDateTime.withZone(destTz);
    return dstDateTime.toLocalDateTime().toDateTime().toDate();
}

All you have to do is to use the first method to convert your dates into a specific common Timezone and do the comparaison.

To get the timezone instance all you have to do is :

TimeZone.getTimeZone("BST");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!