使用现代日期时间 API:
import java.time.OffsetDateTime;
public class Main {
public static void main(String[] args) {
String dateTimeStr = "2020-10-20T13:00:00-05:00";
OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr);
System.out.println("Given date time: " + odt);
// 3-hours ago
OffsetDateTime threeHoursAgo = odt.minusHours(3);
System.out.println("Three hours ago: " + threeHoursAgo);
}
}
输出:
Given date time: 2020-10-20T13:00-05:00
Three hours ago: 2020-10-20T10:00-05:00
通过 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
如果您正在为您的 Android 项目执行此操作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
使用 Joda-Time:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dateTimeStr = "2020-10-20T13:00:00-05:00";
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withOffsetParsed();
DateTime dateTime = dtf.parseDateTime(dateTimeStr);
System.out.println("Given date time: " + dateTime);
// 3-hours ago
DateTime threeHoursAgo = dateTime.minusHours(3);
System.out.println("Three hours ago: " + threeHoursAgo);
}
}
输出:
Given date time: 2020-10-20T13:00:00.000-05:00
Three hours ago: 2020-10-20T10:00:00.000-05:00
注意:在Home Page of Joda-Time查看以下通知
Joda-Time 是 Java 的事实上的标准日期和时间库
在 Java SE 8 之前。现在要求用户迁移到 java.time
(JSR-310)。
使用旧版 API:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
String dateTimeStr = "2020-10-20T13:00:00-05:00";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT-5"));
Date date = sdf.parse(dateTimeStr);
System.out.println("Given date time: " + sdf.format(date));
// 3-hours ago
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, -3);
System.out.println("Three hours ago: " + sdf.format(calendar.getTime()));
}
}
输出:
Given date time: 2020-10-20T13:00:00-05:00
Three hours ago: 2020-10-20T10:00:00-05:00
建议:java.util 的日期时间 API 及其格式 API SimpleDateFormat 已过时且容易出错。我建议你应该完全停止使用它们并切换到modern date-time API。