从指定的日期时间 Kotlin Android 获取几个小时之前的日期时间

Get a dateTime before some hours from a specified dateTime Kotlin Android

我想获得比指定日期时间早几个小时的日期时间。日期时间将采用字符串格式,并且根据配置,需要在给定时间前 n 小时的日期时间(例如在给定时间前 3 或 4 小时)。

我的时间格式是2020-10-20T13:00:00-05:00

使用现代date-time 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.

了解有关现代 date-time API 的更多信息

如果您正在为您的 Android 项目执行此操作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring and .

使用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 is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to 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 的 date-time API 及其格式 API、SimpleDateFormat 已过时和 error-prone。我建议你应该完全停止使用它们并切换到 modern date-time API.