有一个国家/地区下拉的表单,用户将选择国家/地区,然后有一个时区下拉,用户将选择用户选择的国家/地区可用的时区。然后用户将进入本地日期(例如:2014年12月26日)和时间(23:11)(24小时时间)此输入的日期和时间适用于所选国家和时区。 现在我必须将此日期和时间转换为GMT时区。我怎么能用joda时间呢?
如何计算夏令时(DST)?
我已经创建了一个接受从时区到时区,日期
的参数的函数public static String convertTimeZones( String fromTimeZoneString,
String toTimeZoneString, String fromDateTime) {
DateTimeZone fromTimeZone = DateTimeZone.forID(fromTimeZoneString);
DateTimeZone toTimeZone = DateTimeZone.forID(toTimeZoneString);
DateTime dateTime = new DateTime(fromDateTime, fromTimeZone);
DateTimeFormatter outputFormatter
= DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm").withZone(toTimeZone);
return outputFormatter.print(dateTime);
}
我想以一种格式(24-Feb-2014 12:34)将日期传递给此功能,但它没有采用这种格式
答案 0 :(得分:4)
//so we can get the local date
//UTC = true, translate from UTC time to local
//UTC = false, translate from local to UTC
public static String formatUTCToLocalAndBackTime(String datetime, boolean UTC) {
String returnTimeDate = "";
DateTime dtUTC = null;
DateTimeZone timezone = DateTimeZone.getDefault();
DateTimeFormatter formatDT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateDateTime1 = formatDT.parseDateTime(datetime);
DateTime now = new DateTime();
DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC);
long instant = now.getMillis();
long instantUTC = nowUTC.getMillis();
long offset = instantUTC - instant;
if (UTC) {
//convert to local time
dtUTC = dateDateTime1.withZoneRetainFields(DateTimeZone.UTC);
//dtUTC = dateDateTime1.toDateTime(timezone);
dtUTC = dtUTC.plusMillis((int) offset);
} else {
//convert to UTC time
dtUTC = dateDateTime1.withZoneRetainFields(timezone);
dtUTC = dtUTC.minusMillis((int) offset);
}
returnTimeDate = dtUTC.toString(formatDT);
return returnTimeDate;
}
答案 1 :(得分:0)
Java time api 在各种时区方面比 joda time api 更好,特别是在夏令时
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
LocalDateTime start = LocalDateTime.of(2021, 02, 25, 14, 25, 00);
ZoneId zone = ZoneId.of("Asia/Singapore");
start = start.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();