有一个表格有一个国家/地区下拉菜单,用户将选择国家/地区,然后有一个时区下拉菜单,用户将选择用户选择的国家/地区可用的时区。然后用户将输入本地日期(例如: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);
}
我想以某种格式 (2014 年 2 月 24 日 12:34) 将日期传递给此函数,但它不采用此格式
//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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)