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?

前端 未结 2 841
天命终不由人
天命终不由人 2021-01-22 12:09

How do you convert 2 dates one in BST(Current date) and the other in GMT so that they can be compared using the calendar date before() and after() methods? I don\'t know if BS

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 12:33

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

提交回复
热议问题