问题
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 BST is referring to British Summer Time. I am running on a laptop with English settings. I don't know how best to do the comparison to see if one is greater than the other or equals. I figure the timezone is the problem to me successfully using the calander date after() and before() methods. I was checking equality based on the 2 calendars.
I am wanting to compare dates and have been using gregorian calendars. I have 3 gregorian calendars dates and have subtracted 78 from the first date, 48 from the second and 24 from 3rd date from the HOURS_OF_DAY for each. These dates are in GMT. I then get my current date and this is in BST. I am looking to determine when my current date i.e booking date is within the 3 dates i.e withing 78 hours, 48 hours and 24 hours. I am hoping to do this with Java.Util.Date
Any help gratefully recieved
回答1:
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);
回答2:
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");
来源:https://stackoverflow.com/questions/10044807/how-do-you-convert-2-dates-one-in-bstcurrent-date-and-the-other-in-gmt-so-that